<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="姓名" prop="staffName">
              <el-input v-model="queryParams.staffName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属部门" prop="deptId">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptList"
                node-key="deptId"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                placeholder="请选择部门"
                clearable
              />
            </el-form-item>
            <el-form-item label="所属岗位" prop="postId">
              <el-select v-model="queryParams.postId" placeholder="请选择岗位" clearable>
                <el-option v-for="post in postList" :key="post.postId" :label="post.postName" :value="post.postId" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="20"><span>岗位设定信息列表</span> </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:comStaff:add']">新增</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="comStaffList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="人员编码" align="center" prop="staffCode" />
        <el-table-column label="姓名" align="center" prop="staffName" />
        <el-table-column label="性别" align="center" prop="sex">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="部门编码" align="center" prop="deptCode" /> -->
        <el-table-column label="部门名称" align="center" prop="deptName" />
        <el-table-column label="手机号" align="center" prop="phone" />
        <el-table-column label="岗位" align="center" prop="postName" />
        <el-table-column label="是否显示" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:comStaff:edit']">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改人员信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="comStaffFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="人员编码" prop="staffCode">
              <el-input v-model="form.staffCode" placeholder="请输入人员编码" :disabled="!!form.staffId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="staffName">
              <el-input v-model="form.staffName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptList"
                node-key="deptId"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                placeholder="请选择部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="postId">
              <el-select v-model="form.postId" placeholder="请选择岗位">
                <el-option v-for="post in postList" :key="post.postId" :label="post.postName" :value="post.postId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="dict in sys_user_sex" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否启用" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_platform_yes_no" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ComStaff" lang="ts">
import { listComStaff, getComStaff, delComStaff, addComStaff, updateComStaff, changeStatus } from '@/api/company/comStaff';
import { ComStaffVO, ComStaffQuery, ComStaffForm } from '@/api/company/comStaff/types';
import { listDept, getDept, listDeptExcludeChild } from '@/api/system/dept';
import { DeptVO } from '@/api/system/dept/types';
import { listPost, getPost, deptTreeSelect } from '@/api/system/post';
import { PostVO } from '@/api/system/post/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_yes_no, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_platform_yes_no', 'sys_user_sex'));

const comStaffList = ref<ComStaffVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deptList = ref<DeptVO[]>([]);
const postList = ref<PostVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const comStaffFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ComStaffForm = {
  staffId: undefined,
  staffCode: undefined,
  staffName: undefined,
  deptId: undefined,
  phone: undefined,
  postId: undefined,
  sex: '1',
  roleId: undefined,
  dataSource: undefined,
  password: undefined,
  validFrom: undefined,
  validTo: undefined,
  status: '0',
  remark: undefined
};
const data = reactive<PageData<ComStaffForm, ComStaffQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    staffCode: undefined,
    staffName: undefined,
    deptId: undefined,
    phone: undefined,
    postId: undefined,
    sex: undefined,
    roleId: undefined,
    dataSource: undefined,
    password: undefined,
    validFrom: undefined,
    validTo: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    staffName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 获取部门列表（树结构） */
const getDeptList = async () => {
  const res = await listDept();
  const data = proxy?.handleTree<DeptVO>(res.data, 'deptId');
  if (data) {
    deptList.value = data;
  }
  loading.value = false;
};

/** 获取岗位列表 */
const getPostList = async (deptId?: number | string) => {
  try {
    const res = await listPost({ belongDeptId: deptId });
    postList.value = res.rows || [];
  } catch (error) {
    console.error('获取岗位列表失败', error);
  }
};

/** 监听部门选择变化，更新岗位列表 */
watch(
  () => queryParams.value.deptId,
  (newDeptId) => {
    // 清空岗位选择
    queryParams.value.postId = undefined;
    // 根据部门获取岗位列表
    if (newDeptId) {
      getPostList(newDeptId);
    } else {
      getPostList();
    }
  }
);

/** 监听对话框中部门选择变化，更新岗位列表 */
watch(
  () => form.value.deptId,
  (newDeptId) => {
    // 清空岗位选择
    form.value.postId = undefined;
    // 根据部门获取岗位列表
    if (newDeptId) {
      getPostList(newDeptId);
    } else {
      getPostList();
    }
  }
);

/** 查询人员信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listComStaff(queryParams.value);
  comStaffList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  comStaffFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleStatusChange = async (row: ComStaffVO) => {
  const oldValue = row.status; // 保存旧值（0 或 1）

  try {
    await changeStatus(row.postId, row.status); // 传新值
    proxy?.$modal.msgSuccess('操作成功');
  } catch {
    row.status = oldValue; // 失败回滚
    proxy?.$modal.msgError('操作失败，请重试');
  }
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ComStaffVO[]) => {
  ids.value = selection.map((item) => item.staffId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加人员信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ComStaffVO) => {
  reset();
  const _staffId = row?.staffId || ids.value[0];
  const res = await getComStaff(_staffId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改人员信息';
};

/** 提交按钮 */
const submitForm = () => {
  comStaffFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.staffId) {
        await updateComStaff(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addComStaff(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ComStaffVO) => {
  const _staffIds = row?.staffId || ids.value;
  await proxy?.$modal.confirm('是否确认删除人员信息编号为"' + _staffIds + '"的数据项？').finally(() => (loading.value = false));
  await delComStaff(_staffIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/comStaff/export',
    {
      ...queryParams.value
    },
    `comStaff_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getDeptList();
  getPostList();
  getList();
});
</script>
