import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NDataTable,
  NDescriptions,
  NDescriptionsItem,
  NFormItem,
  NImage,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { sysNewsInformationPage, sysNewsInformationRemove, sysNewsInformationUpdate } from '../api'
import InformationOperation from './information-operation'
import { clientTypeArray } from '@/utils/searchArray'
import { filterClientType } from '@/utils/filters'
import TheTooltip from '@/components/TheTooltip'
import { sysEmployeePage } from '@/views/system-manage/api'
// import StationOperation from './station-operation'

export default defineComponent({
  name: 'content-ad',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        type: 'HOT_CONSULTATION',
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        status: null,
        updateBy: null,
        clientType: null
      },
      clientTypeList: [] as any,
      dataList: [] as any,
      visiableInfo: false,
      infoOperation: 'add',
      infoData: {} as any,
      staffList: [] as any
    })

    const columns = () => {
      return [
        {
          title: '编号',
          key: 'id',
          render: (row: any) => (
            <>
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="资讯标题">
                  <TheTooltip content={row.title} />{' '}
                </NDescriptionsItem>
                <NDescriptionsItem label="资讯编号">{row.id}</NDescriptionsItem>
              </NDescriptions>
            </>
          )
        },
        // {
        //   title: '资讯标题',
        //   key: 'title'
        // },
        {
          title: '资讯封面',
          key: 'coverImage',
          render(row: any) {
            return <NImage width={87} height={60} src={row.coverImage} />
          }
        },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return (
              <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '客户端',
          key: 'clientType',
          render(row: any) {
            return filterClientType(row.clientType)
          }
        },
        {
          title: '操作人',
          key: 'updateUser'
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="sysNewsInformation/update1599958605834342402"
                  onClick={() => {
                    state.visiableInfo = true
                    state.infoOperation = 'edit'
                    state.infoData = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="sysNewsInformation/update1599958777301684226"
                  onClick={() => onChangeStatus(row)}
                >
                  {row.status ? '停用' : '启用'}
                </NButton>
                {!row.status && (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    onClick={() => onRmove(row)}
                    //v-auth="sysNewsInformation/remove1599958687598104577"
                  >
                    删除
                  </NButton>
                )}
              </NSpace>
            )
          }
        }
      ]
    }

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

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

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await sysNewsInformationPage({ ...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()
    }

    // 获取操作人
    const getOperationList = async () => {
      try {
        const { data } = await sysEmployeePage({
          page: 1,
          rows: 999
          // jobType: 'STAFF'
        })

        if (Array.isArray(data.rows)) {
          state.staffList = data.rows.map((n: any) => ({ label: n.nickname, value: n.id }))
        }
      } catch {}
    }

    onMounted(() => {
      clientTypeArray.forEach((item: any) => {
        if (item.value != 'BACKEND' && item.value != 'SCHOOL' && item.value != 'REPAIR') {
          state.clientTypeList.push(item)
        }
      })
      getOperationList()
      getList()
    })
    return () => (
      <div class="system-menu-container">
        <h2>资讯管理</h2>
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          label-width=""
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="关键字" path="keyword">
            <NInput
              v-model={[state.searchForm.keyword, 'value']}
              placeholder="资讯标题"
              clearable
            />
          </NFormItem>
          <NFormItem label="状态" path="status">
            <NSelect
              v-model={[state.searchForm.status, 'value']}
              placeholder="请选择状态"
              clearable
              options={
                [
                  {
                    label: '启用',
                    value: true
                  },
                  {
                    label: '停用',
                    value: false
                  }
                ] as any
              }
            />
          </NFormItem>
          <NFormItem label="客户端" path="clientType">
            <NSelect
              clearable
              v-model={[state.searchForm.clientType, 'value']}
              placeholder="请选择客户端"
              options={state.clientTypeList}
            />
          </NFormItem>
          <NFormItem label="操作人" path="clientType">
            <NSelect
              clearable
              v-model={[state.searchForm.updateBy, 'value']}
              placeholder="请选择操作人"
              options={state.staffList}
            />
          </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="sysNewsInformation/save1599958516768296961"
              onClick={() => {
                state.visiableInfo = true
                state.infoOperation = 'add'
                state.infoData = {}
              }}
            >
              添加资讯
            </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
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.visiableInfo}
          preset="dialog"
          showIcon={false}
          title={state.infoOperation === 'add' ? '新增资讯' : '修改资讯'}
          style={{ width: '850px' }}
        >
          <InformationOperation
            type={state.infoOperation}
            data={state.infoData}
            clientTypeList={state.clientTypeList}
            onClose={() => (state.visiableInfo = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
