import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NDataTable,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { filterClientType } from '@/utils/filters'
import {
  helpCenterCatalogPage,
  helpCenterContentPage,
  helpCenterContentRemove,
  helpCenterContentStatus
} from '../../api'
import HelpCenterOperation from '../modal/help-center-operation'
import { clientTypeArray } from '@/utils/searchArray'
import TheTooltip from '@/components/TheTooltip'

export default defineComponent({
  name: 'content-flash',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        catalogType: null,
        catalogId: null,
        keyword: null,
        status: null
      },
      clientTypeList: [] as any,
      dataList: [] as any,
      catalogList: [] as any,
      visiableHelp: false,
      helpOperation: 'add',
      helpData: {} as any
    })

    const columns = () => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '标题',
          key: 'title',
          render(row: any) {
            return <TheTooltip content={row.title} />
          }
        },
        {
          title: '分类',
          key: 'catalogName',
          render(row: any) {
            return <TheTooltip content={row.catalogName} />
          }
        },
        {
          title: '客户端',
          key: 'catalogType',
          render(row: any) {
            return filterClientType(row.catalogType)
          }
        },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return (
              <NTag type={row.status ? 'info' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="helpCenterContent/update1599694657725767681"
                  onClick={() => {
                    state.visiableHelp = true
                    state.helpOperation = 'edit'
                    state.helpData = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="helpCenterContent/status1611349854722027521"
                  onClick={() => onChangeStatus(row)}
                >
                  {row.status ? '停用' : '启用'}
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  onClick={() => onRmove(row)}
                  //v-auth="helpCenterContent/remove1599694768375701505"
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

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

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

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

    const getHelpCenterCategory = async () => {
      try {
        const { data } = await helpCenterCatalogPage({ page: 1, rows: 999 })
        state.catalogList = data.rows || []
      } catch {}
    }

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

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

    onMounted(() => {
      clientTypeArray.forEach((item: any) => {
        if (item.value != 'BACKEND') {
          state.clientTypeList.push(item)
        }
      })
      getList()
      getHelpCenterCategory()
    })
    return () => (
      <div class="system-menu-container">
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          label-width=""
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="标题" path="keyword">
            <NInput clearable v-model:value={state.searchForm.keyword} placeholder="请输入标题" />
          </NFormItem>
          <NFormItem label="分类" path="catalogId">
            <NSelect
              clearable
              v-model:value={state.searchForm.catalogId}
              placeholder="请选择分类"
              options={state.catalogList}
              valueField="id"
              labelField="name"
            />
          </NFormItem>
          <NFormItem label="状态" path="status">
            <NSelect
              clearable
              v-model:value={state.searchForm.status}
              placeholder="请选择状态"
              options={
                [
                  {
                    label: '启用',
                    value: 1
                  },
                  {
                    label: '停用',
                    value: 0
                  }
                ] as any
              }
            />
          </NFormItem>
          <NFormItem label="客户端" path="catalogType">
            <NSelect
              clearable
              v-model={[state.searchForm.catalogType, 'value']}
              placeholder="请选择客户端"
              options={state.clientTypeList}
            />
          </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="helpCenterContent/save1599694573994876929"
              onClick={() => {
                state.visiableHelp = true
                state.helpOperation = 'add'
                state.helpData = {}
              }}
            >
              添加帮助
            </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="help-center"
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.visiableHelp}
          preset="dialog"
          showIcon={false}
          title={state.helpOperation === 'add' ? '新增帮助' : '修改帮助'}
          style={{ width: '850px' }}
        >
          <HelpCenterOperation
            type={state.helpOperation}
            data={state.helpData}
            catalogList={state.catalogList}
            clientTypeList={state.clientTypeList}
            onClose={() => (state.visiableHelp = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
