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 { sysNoticePage, sysNoticeRemove, sysNoticeStatus } from '../api'
import NoticeOperation from './notice-operation'
import { clientTypeArray } from '@/utils/searchArray'
import { filterClientType } from '@/utils/filters'
import TheTooltip from '@/components/TheTooltip'
// import StationOperation from './station-operation'

export default defineComponent({
  name: 'content-ad',
  setup() {
    const dialog = useDialog()
    const message = useMessage()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        catalogType: null,
        status: null
      },
      clientTypeList: [] as any,
      dataList: [] as any,
      visiableAd: false,
      adOperation: 'add',
      adData: {} 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: 'releaseTime'
        // },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return (
              <NTag type={row.status ? 'primary' : 'default'}>{row.status ? '启用' : '停用'}</NTag>
            )
          }
        },
        {
          title: '客户端',
          key: 'catalogType',
          render(row: any) {
            return filterClientType(row.catalogType)
          }
        },
        {
          title: '操作人',
          key: 'updateUser'
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="sysNotice/update1599958936240640001"
                  onClick={() => {
                    state.visiableAd = true
                    state.adOperation = 'edit'
                    state.adData = row
                  }}
                >
                  修改
                </NButton>

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

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

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await sysNoticePage({ ...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(() => {
      clientTypeArray.forEach((item: any) => {
        if (item.value != 'BACKEND') {
          state.clientTypeList.push(item)
        }
      })
      getList()
    })
    return () => (
      <div class="system-menu-container">
        <h2>公告管理</h2>
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="关键字" path="keyword">
            <NInput v-model={[state.searchForm.keyword, 'value']} placeholder="公告编号/标题" />
          </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
              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="sysNotice/save1599958862773211137"
              onClick={() => {
                state.visiableAd = true
                state.adOperation = 'add'
                state.adData = {}
              }}
            >
              添加公告
            </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.visiableAd}
          preset="dialog"
          showIcon={false}
          title={state.adOperation === 'add' ? '新增公告' : '修改公告'}
          style={{ width: '750px' }}
        >
          <NoticeOperation
            type={state.adOperation}
            data={state.adData}
            clientTypeList={state.clientTypeList}
            onClose={() => (state.visiableAd = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
