<script setup lang="tsx">
import { reactive, ref, unref, useTemplateRef } from 'vue'
import { getStaffCategory, delStaffCategory, addStaffCategory, putStaffCategory } from '@/api/staff'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
import { staffCategoryData } from '@/api/staff/types'
import Write from './components/Write.vue'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getStaffCategory({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.count || 0
    }
  }
})

const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    align: 'center',
    width: 70
  },
  {
    field: 'type_chs',
    label: '类型',
    minWidth: 100
  },
  {
    field: 'name',
    label: '分类',
    minWidth: 140
  },
  {
    field: 'is_show_chs',
    label: '是否显示',
    width: 120
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action('edit', row)}>
              编辑
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              删除
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'type',
    label: '类型',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '全部',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '安装工',
          value: '2'
        },
        {
          label: '设计师',
          value: '1'
        }
      ]
    }
  }
])

const searchParams = ref<{
  type?: string
}>({
  type: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const currentRow = ref()
const dialogTitle = ref('')
const actionType = ref('')
const saveLoading = ref(false)
const writeRef = useTemplateRef('writeRef')

const action = async (type: string, row?: any) => {
  actionType.value = type
  if (type == 'add') {
    dialogTitle.value = t('exampleDemo.add')
    currentRow.value = undefined
  }
  if (type == 'edit') {
    dialogTitle.value = t('exampleDemo.edit')
    currentRow.value = {
      id: row.id,
      name: row.name,
      is_show: row.is_show == 1 ? true : false
    }
  }
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delStaffCategory(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const data: staffCategoryData = {
      id: formData.id || '',
      name: formData.name, //分类名称
      type: formData.type, //类型
      is_show: formData.is_show ? 1 : 0 //是否启用
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        res = await putStaffCategory(data)
      } else if (actionType.value === 'add') {
        res = await addStaffCategory(data)
      }
      if (res?.status == 200) {
        ElMessage({
          showClose: true,
          message: '保存成功',
          type: 'success'
        })
        getList()
        dialogVisible.value = false
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="action('add')">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      stripe
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500px" maxHeight="150px">
    <Write ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
