<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="staffNo">
              <el-input v-model="queryParams.staffNo" placeholder="请输入工号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-select v-model="queryParams.role" placeholder="员工角色" clearable style="width: 180px">
                <el-option v-for="opt in staffRoleOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="员工状态" clearable style="width: 180px">
                <el-option v-for="opt in staffStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </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="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:staff:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:staff:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:staff:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:staff:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="staffList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工号" align="center" prop="staffNo" width="130" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="角色" align="center" prop="role" width="110">
          <template #default="scope">
            <el-tag :type="getRoleTag(scope.row.role)">{{ getRoleLabel(scope.row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="phone" width="130" />
        <el-table-column label="学科" align="center" prop="subject" width="90" />
        <el-table-column label="头衔" align="center" prop="title" width="100" />
        <el-table-column label="基本薪资" align="center" prop="baseSalary" width="110" />
        <el-table-column label="重大差错" align="center" prop="majorErrorCount" width="90" />
        <el-table-column label="状态" align="center" prop="status" width="90">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入职日期" align="center" prop="entryDate" width="110">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.entryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['edu:staff:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="分配学生" placement="top">
              <el-button v-hasPermi="['edu:staff:assign']" link type="primary" icon="Connection" @click="handleAssign(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:staff:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="780px" append-to-body>
      <el-form ref="staffFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工角色" prop="role">
              <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
                <el-option v-for="opt in staffRoleOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工号" prop="staffNo">
              <el-input v-model="form.staffNo" placeholder="留空则自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio value="0">男</el-radio>
                <el-radio value="1">女</el-radio>
                <el-radio value="2">未知</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option v-for="opt in staffStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="学科" prop="subject">
              <el-input v-model="form.subject" placeholder="擅长学科(辅导老师用)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="头衔" prop="title">
              <el-input v-model="form.title" placeholder="高级/资深/普通" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="entryDate">
              <el-date-picker v-model="form.entryDate" type="date" value-format="YYYY-MM-DD" placeholder="选择入职日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大带生数" prop="maxStudents">
              <el-input-number v-model="form.maxStudents" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="基本薪资" prop="baseSalary">
              <el-input-number v-model="form.baseSalary" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="重大差错数" prop="majorErrorCount">
              <el-input-number v-model="form.majorErrorCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="form.wechat" placeholder="请输入微信号" />
        </el-form-item>

        <el-divider content-position="left">紧急联系人</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input v-model="form.emergencyContact" placeholder="紧急联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急电话" prop="emergencyPhone">
              <el-input v-model="form.emergencyPhone" placeholder="紧急联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="简介" prop="intro">
          <el-input v-model="form.intro" type="textarea" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配学生对话框 -->
    <el-dialog v-model="assignDialog.visible" title="分配学生" width="480px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="员工">
          <span>{{ assignRow.name }}（{{ getRoleLabel(assignRow.role) }}）</span>
        </el-form-item>
        <el-form-item label="学生ID">
          <el-input
            v-model="assignStudentInput"
            type="textarea"
            :rows="4"
            placeholder="输入学生ID, 多个用逗号分隔, 如 1001,1002,1003"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssign">确 定</el-button>
          <el-button @click="assignDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduStaff" lang="ts">
import { listStaff, getStaff, addStaff, updateStaff, delStaff, assignStudents } from '@/api/edu/staff';
import { StaffForm, StaffQuery, StaffVO, staffRoleOptions, staffStatusOptions } from '@/api/edu/staff/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const staffList = ref<StaffVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const staffFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({ visible: false, title: '' });
const assignDialog = reactive<DialogOption>({ visible: false, title: '' });
const assignRow = ref<StaffVO>({} as StaffVO);
const assignStudentInput = ref('');

const initFormData: StaffForm = {
  id: undefined,
  userId: undefined,
  staffNo: '',
  name: '',
  role: 'TUTOR',
  phone: '',
  email: '',
  wechat: '',
  gender: '0',
  idCard: '',
  entryDate: '',
  leaveDate: '',
  subject: '',
  title: '',
  maxStudents: 0,
  commissionRate: 0,
  baseSalary: 0,
  bankAccount: '',
  majorErrorCount: 0,
  emergencyContact: '',
  emergencyPhone: '',
  deptId: undefined,
  intro: '',
  avatar: '',
  status: '0',
  remark: ''
};

const data = reactive<PageData<StaffForm, StaffQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    staffNo: '',
    name: '',
    role: '',
    phone: '',
    subject: '',
    status: '',
    deptId: undefined
  },
  rules: {
    name: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
    role: [{ required: true, message: '员工角色不能为空', trigger: 'change' }]
  }
});

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

// 本地字典查找(后端用独立 edu_dict, 前端不依赖 sys_dict)
const getRoleLabel = (val: string) => staffRoleOptions.find((o) => o.value === val)?.label || val;
const getRoleTag = (val: string) => staffRoleOptions.find((o) => o.value === val)?.elTagType || 'info';
const getStatusLabel = (val: string) => staffStatusOptions.find((o) => o.value === val)?.label || val;
const getStatusTag = (val: string) => staffStatusOptions.find((o) => o.value === val)?.elTagType || 'info';

/** 查询员工列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStaff(queryParams.value);
  staffList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

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

/** 修改按钮操作 */
const handleUpdate = async (row?: StaffVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getStaff(id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改员工';
};

/** 提交按钮 */
const submitForm = () => {
  staffFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.id ? await updateStaff(form.value) : await addStaff(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: StaffVO) => {
  const delIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除员工编号为"' + delIds + '"的数据项？');
  await delStaff(delIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

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

/** 分配学生按钮操作 */
const handleAssign = (row: StaffVO) => {
  assignRow.value = row;
  assignStudentInput.value = '';
  assignDialog.visible = true;
};

/** 提交分配 */
const submitAssign = async () => {
  const studentIds = assignStudentInput.value
    .split(/[,，\s]+/)
    .map((s) => s.trim())
    .filter((s) => s.length > 0)
    .map((s) => Number(s));
  if (studentIds.length === 0) {
    proxy?.$modal.msgWarning('请输入学生ID');
    return;
  }
  await assignStudents({
    staffId: assignRow.value.id,
    staffRole: assignRow.value.role,
    studentIds
  });
  proxy?.$modal.msgSuccess('分配成功');
  assignDialog.visible = false;
};

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