<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      row-key="deptId"
      :pagination="false"
      :request-api="listDeptApi"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" v-auth="['system:dept:add']" :icon="CirclePlus" @click="openDialog(1, '部门新增')"> 新增 </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" v-auth="['system:dept:edit']" @click="openDialog(2, '部门编辑', scope.row)"> 编辑 </el-button>
        <el-button type="primary" link :icon="CirclePlus" v-auth="['system:dept:add']" @click="openDialog(4, '部门新增', scope.row)">
          新增
        </el-button>
        <el-button v-if="scope.row.parentId != 0" type="primary" link :icon="Delete" v-auth="['system:dept:remove']" @click="deleteDept(scope.row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="DeptManage">
import { ref, reactive } from 'vue'
import { useHandleData } from '@/hooks/useHandleData'
import ProTable from '@/components/ProTable/index.vue'
import ImportExcel from '@/components/ImportExcel/index.vue'
import FormDialog from '@/components/DialogOld/form.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import { Delete, EditPen, CirclePlus } from '@element-plus/icons-vue'
import { handleTree } from '@/utils/common'
import { listDeptApi, delDeptApi, addDeptApi, updateDeptApi, getDeptApi } from '@/api/modules/system/dept'
import { getDictsApi } from '@/api/modules/system/dictData'

// ProTable 实例
const proTable = ref<ProTableInstance>()

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({})
const deptOptions = ref<any[]>([])
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
const dataCallback = (res: any) => {
  const data = handleTree(res, 'deptId')
  deptOptions.value = data
  setFieldList()
  return data
}

// 删除用户信息
const deleteDept = async (params: any) => {
  await useHandleData(delDeptApi, params.deptId, `删除【${params.deptName}】部门`)
  proTable.value?.getTableList()
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.deptId) {
    res = await getDeptApi(row?.deptId || null)
  }

  // 重置表单项
  setFieldList()
  if (row?.parentId == 0 && type == 2) {
    fieldList.splice(0, 1)
  }
  // 增加子节点
  if (type == 4 && row?.parentId) {
    res.data = {
      parentId: row?.parentId
    }
  }
  const params = {
    title,
    width: 500,
    isEdit: type !== 3,
    fieldList: fieldList,
    model: type == 1 ? {} : res.data,
    api: type == 1 || type == 4 ? addDeptApi : updateDeptApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  // { type: 'selection', fixed: 'left', width: 70 },
  {
    prop: 'deptName',
    label: '部门名称',
    align: 'left',
    search: {
      el: 'input'
    },
    width: 180
  },
  {
    prop: 'orderNum',
    label: '显示顺序',
    width: 120
  },
  {
    prop: 'status',
    label: '部门状态',
    tag: true,
    enum: () => getDictsApi('sys_normal_disable'),
    search: {
      el: 'tree-select'
    },
    fieldNames: { label: 'dictLabel', value: 'dictValue' },
    width: 180
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: 230
  },
  { prop: 'operation', label: '操作' }
])
let fieldList: Form.FieldItem[] = []
const setFieldList = () => {
  fieldList = [
    {
      label: '上级部门',
      field: 'parentId',
      enum: deptOptions.value,
      type: 'select-tree',
      rules: [{ required: true, message: '请选择上级部门', trigger: 'change' }],
      options: {
        valueKey: 'deptId',
        labelKey: 'deptName',
        children: 'children'
      },
      placeholder: '请输入上级部门'
    },
    {
      label: '部门名称',
      field: 'deptName',
      rules: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
      span: 12,
      placeholder: '请输入部门名称'
    },
    {
      label: '显示顺序',
      field: 'orderNum',
      type: 'input-number',
      rules: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
      options: {
        min: 0
      },
      span: 12,
      placeholder: '请输入显示顺序'
    },
    {
      label: '负责人',
      field: 'leader',
      span: 12,
      placeholder: '请输入负责人'
    },
    {
      label: '联系电话',
      field: 'phone',
      span: 12,
      rules: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
      placeholder: '请输入联系电话'
    },
    {
      label: '邮箱',
      field: 'email',
      span: 12,
      rules: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
      placeholder: '请输入邮箱'
    },
    {
      label: '部门状态',
      field: 'status',
      enum: () => getDictsApi('sys_normal_disable'),
      type: 'radio',
      options: {
        labelKey: 'dictLabel',
        valueKey: 'dictValue'
      },
      span: 12,
      placeholder: '请选择部门状态'
    }
  ]
}
</script>
