import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NDataTable,
  NFormItem,
  NImage,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  NTooltip,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { sysMenuButtonPage, sysMenuButtonRemove, sysMenuButtonUpdate } from '../../api'
import AppButtonOperation from '../modal/app-button-operation'

export default defineComponent({
  name: 'content-flash',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        clientType: 'TEACHER',
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        status: null,
        auditFlag: null
      },
      dataList: [] as any,
      visiableApp: false,
      appOperation: 'add',
      appData: {} as any
    })

    const columns = () => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '按钮名称',
          key: 'title'
        },
        {
          title: '按钮图',
          key: 'buttonImage',
          render(row: any) {
            return <NImage width={44} height={44} src={row.buttonImage} />
          }
        },
        {
          title: '跳转链接',
          key: 'linkUrl',
          render(row: any) {
            return (
              <NTooltip style="max-width: 400px;">
                {{
                  default: () => row.linkUrl,
                  trigger: () => (
                    <span style="overflow: hidden;display: inline-block;max-width: 200px;white-space: nowrap;text-overflow: ellipsis;">
                      {row.linkUrl}
                    </span>
                  )
                }}
              </NTooltip>
            )
          }
        },
        {
          title: '排序值',
          key: 'order'
          // sorter: true,
          // sortOrder: false
        },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return (
              <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '审核版本',
          key: 'auditFlag',
          render(row: any) {
            return (
              <NTag type={row.auditFlag ? 'primary' : 'default'}>
                {row.auditFlag ? '是' : '否'}
              </NTag>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                {!row.status && (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    //v-auth="sysMenuButton/update1600386947867840517"
                    onClick={() => {
                      state.visiableApp = true
                      state.appOperation = 'edit'
                      state.appData = row
                    }}
                  >
                    修改
                  </NButton>
                )}

                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="sysMenuButton/update1600386947867840519"
                  onClick={() => onChangeStatus(row)}
                >
                  {row.status ? '停用' : '启用'}
                </NButton>
                {!row.status && (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    onClick={() => onRmove(row)}
                    //v-auth="sysMenuButton/remove1600386947867840518"
                  >
                    删除
                  </NButton>
                )}
              </NSpace>
            )
          }
        }
      ]
    }

    const onRmove = (row: any): void => {
      dialog.warning({
        title: '警告',
        content: `删除"${row.title}"，是否继续？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await sysMenuButtonRemove({ id: row.id })
            getList()
            message.success('删除成功')
          } catch {}
        }
      })
    }

    const onChangeStatus = (row: any) => {
      const statusStr = row.status ? '停用' : '启用'
      dialog.warning({
        title: '警告',
        content: `是否${statusStr}？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await sysMenuButtonUpdate({
              id: row.id,
              status: row.status ? false : true
            })
            getList()
            message.success(`${statusStr}成功`)
          } catch {}
        }
      })
    }

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await sysMenuButtonPage({ ...state.pagination, ...state.searchForm })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class="system-menu-container">
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          saveKey="app-button-teacher"
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="关键字" path="keyword">
            <NInput
              placeholder="请输入按钮名称"
              v-model:value={state.searchForm.keyword}
              clearable
            />
          </NFormItem>
          <NFormItem label="状态" path="status">
            <NSelect
              v-model:value={state.searchForm.status}
              clearable
              options={
                [
                  {
                    label: '启用',
                    value: 1
                  },
                  {
                    label: '停用',
                    value: 0
                  }
                ] as any
              }
              placeholder="请选择状态"
            />
          </NFormItem>
          <NFormItem label="审核版本" path="auditFlag">
            <NSelect
              v-model:value={state.searchForm.auditFlag}
              clearable
              options={
                [
                  {
                    label: '是',
                    value: 1
                  },
                  {
                    label: '否',
                    value: 0
                  }
                ] as any
              }
              placeholder="请选择审核版本"
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>

        <div class={['section-container']}>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              //v-auth="sysMenuButton/save1600386947867840516"
              onClick={() => {
                state.visiableApp = true
                state.appOperation = 'add'
                state.appData = {}
              }}
            >
              添加按钮
            </NButton>
          </NSpace>

          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
          ></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
            saveKey="app-button-teacher"
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.visiableApp}
          preset="dialog"
          showIcon={false}
          title={state.appOperation === 'add' ? '新增按钮' : '修改按钮'}
          style={{ width: '550px' }}
        >
          <AppButtonOperation
            type={state.appOperation}
            data={state.appData}
            clientType="TEACHER"
            onClose={() => (state.visiableApp = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
