<script setup lang="tsx">
import { onMounted, reactive, ref, unref, useTemplateRef } from 'vue'
import { getStaffJobs, delStaffJobs, addStaffJobs, putStaffJobs } from '@/api/staff'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
import { jobsData } from '@/api/staff/types'
import Write from './components/Write.vue'
import { getStaffCategory } from '@/api/staff'
const CategoryList = ref<any[]>([])
onMounted(() => {
  getStaffCategory({
    page: 1,
    limit: 100
  }).then((res) => {
    CategoryList.value = res.data.list.map((res) => {
      return {
        label: `${res.type_chs}[${res.name}]`,
        value: res.id
      }
    })
  })
})
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getStaffJobs({
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10
    })
    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: 'cate_id',
    label: '绑定业务',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        for (let i = 0; i < CategoryList.value.length; i++) {
          if (CategoryList.value[i].value === row.cate_id) {
            return <>{CategoryList.value[i].label}</>
          }
        }
        return <></>
      }
    }
  },
  {
    field: 'name',
    label: '名称',
    minWidth: 140
  },
  {
    field: 'is_show_chs',
    label: '是否显示',
    width: 120
  },
  {
    field: 'default_price',
    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 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,
      default_price: row.default_price //一口价
    }
  }
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delStaffJobs(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: jobsData = {
      id: formData.id || '',
      name: formData.name, //分类名称
      cate_id: formData.cate_id, //类型
      is_show: formData.is_show ? 1 : 0, //是否启用
      default_price: formData.default_price //一口价
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        res = await putStaffJobs(data)
      } else if (actionType.value === 'add') {
        res = await addStaffJobs(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>
    <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" :category="CategoryList" :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>
