import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NDataTable,
  NDescriptions,
  NDescriptionsItem,
  NFormItem,
  NImage,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  NTooltip,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { sysNewsInformationPage, sysNewsInformationRemove, sysNewsInformationUpdate } from '../api'
import FlashOperation from './flash-operation'
import { clientTypeArray } from '@/utils/searchArray'
import { filterClientType } from '@/utils/filters'
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,
        type: 'FLASH_PAGE',
        pageTotal: 0
      },
      searchForm: {
        clientType: null,
        status: null,
        keyword: null
      },
      clientTypeList: [] as any,
      dataList: [] as any,
      visiableFlash: false,
      flashOperation: 'add',
      flashData: {} 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={70} height={70} src={row.coverImage} />
          }
        },
        {
          title: '跳转连接',
          key: 'linkUrl',
          render(row: any) {
            return <TheTooltip content={row.linkUrl} />
          }
        },
        {
          title: '生效时间',
          key: 'onlineTime',
          render(row: any) {
            return (
              <>
                <p>{row.onlineTime}</p>
                <p>{row.offlineTime}</p>
              </>
            )
          }
        },
        {
          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: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="sysNewsInformation/update1599695301404631042"
                  onClick={() => {
                    state.visiableFlash = true
                    state.flashOperation = 'edit'
                    state.flashData = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="sysNewsInformation/remove1599695493080129537"
                  onClick={() => onChangeStatus(row)}
                >
                  {row.status ? '停用' : '启用'}
                </NButton>
                {!row.status && (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    onClick={() => onRmove(row)}
                    //v-auth="sysNewsInformation/remove1599695493080129537"
                  >
                    删除
                  </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}？`,
        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()
    }

    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}
          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="status">
            <NSelect
              clearable
              v-model:value={state.searchForm.status}
              placeholder="请选择状态"
              options={
                [
                  {
                    label: '启用',
                    value: 1
                  },
                  {
                    label: '停用',
                    value: 0
                  }
                ] as any
              }
            />
          </NFormItem>
          <NFormItem label="客户端" path="clientType">
            <NSelect
              clearable
              v-model={[state.searchForm.clientType, '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="sysNewsInformation/save1599695226544693250"
              onClick={() => {
                state.visiableFlash = true
                state.flashOperation = 'add'
                state.flashData = {}
              }}
            >
              添加闪页
            </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.visiableFlash}
          title={state.flashOperation === 'add' ? '新增闪页' : '修改闪页'}
          preset="dialog"
          showIcon={false}
          style={{ width: '600px' }}
        >
          <FlashOperation
            type={state.flashOperation}
            data={state.flashData}
            clientTypeList={state.clientTypeList}
            onClose={() => (state.visiableFlash = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
