<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getWorkerGroup, addWorkerGroup, putWorkerGroup, delWorkerGroup } 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 Write from './components/workerWrite.vue'
import { BaseButton } from '@/components/Button'
import { ElMessage, ElDivider, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { staffGroupSearch, staffGroupData } from '@/api/staff/types'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getWorkerGroup({
      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: 'name',
    label: '组名',
    minWidth: 100
  },
  {
    field: 'group_leader_id',
    label: '组长',
    minWidth: 120,
    slots: {
      default: (data: any) => {
        const row = data.row
        return row.group_leader_id ? row.leader.name : '暂无'
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 110,
    align: 'center',
    headerAlign: 'center',
    fixed: 'right',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '组名',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入姓名'
    }
  }
])

const searchParams = ref<staffGroupSearch>({
  name: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const currentRow = ref()
const dialogTitle = ref('')
const actionType = ref('')
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const action = async (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = {
    name: row.name,
    id: row.id,
    province: row.province,
    city: row.city,
    area: row.area,
    group_leader_id: row.group_leader_id,
    address: [parseInt(row.province), parseInt(row.city), parseInt(row.area)]
  }
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const data: staffGroupData = {
      name: formData.name,
      id: formData.id,
      province: formData.province,
      city: formData.city,
      area: formData.area,
      group_leader_id: formData.group_leader_id
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        data.id = formData.id
        res = await putWorkerGroup(data)
      } else if (actionType.value === '') {
        res = await addWorkerGroup(data)
      }
      if (res?.status === 200) {
        ElMessage({
          showClose: true,
          message: '保存成功',
          type: 'success'
        })
        getList()
        dialogVisible.value = false
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}

const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delWorkerGroup(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ 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">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
