<!-- 部门管理详情 -->
<script name="DeptDetail" lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { el } from 'element-plus/es/locale'
import type { deptType } from '@/global'
import { getDictByCode } from '@/api/system/dict'
import type { IlistQueryType } from '@/views/system/user/user-interface'
import { getUserList } from '@/api/system/user'
import { updateDept } from '@/api/system/baseInfoDept'
import type { TableColumn } from '@/components/NormalTable/table_interface'
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 页面类型字典
const loading = ref(false) // 表单加载状态
const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // id
const form = ref({ // 表单数据
  deptId: '', // 部门编号
  fullName: '', // 部门名称
  deptType: '', // 部门类型
  directorId: '', // 负责人
  SYNC_ID: '', // 属地
  remark: '', // 备注
  tips: '', // 部门类别
})
const rules = reactive<FormRules>({ // 表单验证规则
  deptType: [{ required: true, message: '部门类型不能为空', trigger: ['blur', 'change'] }],
  SYNC_ID: [{ required: true, message: '属地不能为空', trigger: ['blur', 'change'] }],
  tips: [{ required: true, message: '部门类别不能为空', trigger: ['blur', 'change'] }],
  // directorId: [{ required: true, message: '负责人不能为空', trigger: ['blur', 'change'] }],
})
const ruleFormRef = ref() // 表单ref
// -----------------------------------------字典--------------------------------------------------------------
const deptTypeList = ref<deptType[]>([]) // 部门类型
const sexMap = ref({}) as any// 性别字典
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
const personTypeMap = ref({}) as any// 人员类别字典
const deptCategoryList = ref<deptType[]>([]) // 部门类别
const placeList = ref<deptType[]>([]) // 属地
/**
 * 获取字典
 */
function getDict() {
  loading.value = true
  // 获取部门类型
  getDictByCode('deptType').then((response) => {
    deptTypeList.value = response.data
    loading.value = false
  })
  // 性别
  getDictByCode('sex').then((response) => {
    response.data.forEach((item: any) => {
      sexMap.value[`${item.value}`] = item.name
    })
  })
  // 获取用户列表
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
  // 人员类别
  getDictByCode('bizStaffType').then((response) => {
    response.data.forEach((item: any) => {
      personTypeMap.value[`${item.value}`] = item.name
    })
  })

  // 获取部门类别
  getDictByCode('eqptDeviceType').then((response) => {
    deptCategoryList.value = response.data
  })
  // 属地
  getDictByCode('bizLabCode').then((response) => {
    placeList.value = response.data
  })
}

// -----------------------------------路由参数-------------------------------------------------
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const listRowData = ref({}) as any // 列表页行数据
// ---------------------------------------methods----------------------------------------------------
const $router = useRouter() // 路由实例
// 点击关闭
const close = () => {
  $router.back()
}
// 点击保存
const save = (ruleFormRef: FormInstance | undefined) => {
  if (!ruleFormRef) { return }
  ruleFormRef.validate((valid, fields) => {
    if (valid) { // 基本信息表单通过校验
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        const params = {
          deptType: form.value.deptType, // 部门类型
          fullName: listRowData.value.fullName, // 部门名称-列表原有数据-不变
          id: listRowData.value.id, // 列表原有数据-不变
          num: listRowData.value.num, // 列表原有数据-不变
          pid: listRowData.value.pid, // 列表原有数据-不变
          simpleName: listRowData.value.simpleName, // 列表原有数据-不变
          tips: form.value.tips, // 部门类别
          version: listRowData.value.version, // 列表原有数据-不变
        }
        // 调保存接口
        updateDept(params).then(() => {
          ElMessage.success('编辑成功')
          pageType.value = 'detail'
        })
      })
    }
  })
}
// -------------------------------------------部门人员-----------------------------------
const listQuery: IlistQueryType = reactive({
  keywords: '', // 关键字
  beginTime: '', // 开始时间
  endTime: '', // 结束时间
  deptId: '', // 部门id
  sort: 'id', // 排序
  deptType: '', // 部门类型
  offset: 1,
  limit: 20,
})
const list = ref([]) // 表格数据
const total = ref(0) // 数据总数
const columns = ref<TableColumn[]>([
  { text: '人员编号', value: 'id', align: 'center', width: '200' },
  { text: '名称', value: 'name', align: 'center' },
  { text: '性别', value: 'sexName', align: 'center', width: '90' },
  { text: '人员类别', value: 'personTypeName', align: 'center' },
])
const deptPersonLoading = ref(false) // 表格loading
// 获取部门人员
const fetchDeptPerson = (isNowPage = false) => {
  deptPersonLoading.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.offset = 1
  }
  getUserList(listQuery).then((res) => {
    list.value = res.data.rows.map((item: { sexName: string; sex: string; attr1: string }) => {
      return {
        ...item,
        sexName: item.sex ? sexMap.value[item.sex] : item.sex || '未知',
        personTypeName: item.attr1 ? personTypeMap.value[item.attr1] : item.attr1 || '未知',
      }
    })
    total.value = res.data.total
    deptPersonLoading.value = false
  }).catch(() => {
    deptPersonLoading.value = false
  })
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.limit = val.size
  }
  if (val && val.page) {
    listQuery.offset = val.page
  }
  fetchDeptPerson(true)
}

// ---------------------------------------钩子-------------------------------------------
onMounted(async () => {
  await getDict() // 获取字典
  listRowData.value = JSON.parse($route.query.row as string) // 列表页行数据
  listQuery.deptId = listRowData.value.deptId // 部门id
  form.value.deptId = listRowData.value.deptId // 部门id
  form.value.fullName = listRowData.value.fullName // 部门名称
  form.value.deptType = listRowData.value.deptType // 部门类型
  form.value.directorId = listRowData.value.directorId // 人员id
  fetchDeptPerson() // 获取部门人员
})
</script>

<template>
  <app-container>
    <detail-page v-loading="loading" :title="`部门管理--${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="form"
        :label-width="120"
        label-position="right"
        :rules="rules"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="部门编号:" prop="deptId">
              <el-input v-model="form.deptId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称:" prop="fullName">
              <el-input v-model="form.fullName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责人" prop="directorId">
              <el-select
                v-model.trim="form.directorId"
                filterable
                placeholder=" "
                disabled
                class="full-width-input"
              >
                <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门类型:" prop="deptType">
              <el-select
                v-model.trim="form.deptType"
                :placeholder="pageType === 'detail' ? ' ' : '请选择部门类型'"
                size="default"
                :disabled="pageType === 'detail'"
                class="full-width-input"
              >
                <el-option
                  v-for="item in deptTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门类别:" prop="tips">
              <el-select
                v-model.trim="form.tips"
                :placeholder="pageType === 'detail' ? ' ' : '请选择部门类别'"
                size="default"
                :disabled="pageType === 'detail'"
                class="full-width-input"
              >
                <el-option
                  v-for="item in deptCategoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="属地:" prop="SYNC_ID">
              <el-select
                v-model.trim="form.SYNC_ID"
                :placeholder="pageType === 'detail' ? ' ' : '请选择属地'"
                size="default"
                :disabled="pageType === 'detail'"
                class="full-width-input"
              >
                <el-option
                  v-for="item in placeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model="form.remark"
                type="textarea"
                autosize
                :placeholder="pageType === 'detail' ? '' : '请输入备注'"
                :disabled="pageType === 'detail'"
                :class="{ 'detail-input': pageType === 'detail' }"
              />
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
    </detail-page>
    <detail-block title="部门人员">
      <normal-table :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="deptPersonLoading" @change="changePage">
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </detail-block>
  </app-container>
</template>
