<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="evaluation-header">
        <h1 class="evaluation-title">{{ evaluationDetail.exName || '先进个人信息' }}</h1>
        <div class="evaluation-meta">
          <span>考核部门: {{ evaluationDetail.deptNames || '-' }}</span>
          <span>创建人: {{ evaluationDetail.createdUserName || '-' }}</span>
          <span>创建时间: {{ formatDateTime(evaluationDetail.createdAt) || '-' }}</span>
        </div>
      </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>部门：</span>
                <el-cascader
                  ref="deptCascaderRef"
                  v-model="deptId"
                  :options="deptTree"
                  :props="cascaderDeptProp"
                  :show-all-levels="false"
                  placeholder="请选择部门"
                  filterable
                  clearable
                  @change="handleDeptChange"
                />
              </div>
              <div class="select-box--item">
                <span>员工工号/名称：</span>
                <el-input
                  v-model="tableQuery.queryParam.userName"
                  placeholder="搜索员工工号或名称"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>时间范围：</span>
                <el-date-picker
                  v-model="tableQuery.queryParam.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary"  @click="openAddDialog">
                添加
              </el-button>
              <el-button plain class="search-table-container--button" @click="handleExport">
                导出
              </el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton text="编辑" @click="handleEdit(scope.row)" />
                <ActionButton text="删除" @click="handleDelete(scope.row)" />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>

    <!-- 添加/编辑先进个人对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="`${isEditMode ? '编辑' : '新增'}先进个人`"
      width="800px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <div class="add-dialog-content">
        <div class="description">
          <span class="description-label">说明：</span>
          <span class="description-text">
            评为先进集体部门,先进个人可以申报两位员工。非先进集体部门,只能申报一位员工为先进个人。
          </span>
        </div>

        <!-- 普通部门表单 -->
        <el-form
          v-if="deptType === 'normal'"
          ref="normalFormRef"
          :model="normalForm"
          :rules="normalFormRules"
          label-width="140px"
        >
          <el-form-item label="所属部门：">
            <el-cascader
              v-model="currentDeptId"
              :options="deptTree"
              :props="cascaderDeptProp"
              :show-all-levels="false"
              placeholder="请选择所属部门"
              filterable
              clearable
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="员工工号：" prop="employeeCode">
            <el-input
              v-model="normalForm.employeeCode"
              placeholder="请输入员工工号"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="员工姓名：" prop="employeeName">
            <el-input
              v-model="normalForm.employeeName"
              placeholder="请输入员工姓名"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="员工联系方式：" prop="employeeContact">
            <el-input
              v-model="normalForm.employeeContact"
              placeholder="请输入11位手机号码"
              maxlength="11"
              @input="handlePhoneInput"
            />
          </el-form-item>
          <el-form-item label="个人先进描述：" prop="remark">
            <el-input
              v-model="normalForm.remark"
              type="textarea"
              :rows="4"
              placeholder="请填写个人先进获取内容描述。"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </el-form>

        <!-- 先进集体部门表格表单（暂不使用） -->
        <!--
        <div v-if="deptType === 'advanced'">
          <el-table :data="advancedFormList" border style="width: 100%">
            <el-table-column label="编号" width="80" align="center">
              <template #default="{ $index }">
                {{ $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="员工工号" prop="employeeCode">
              <template #default="{ row, $index }">
                <el-input
                  v-model="row.employeeCode"
                  placeholder="请输入..."
                  maxlength="50"
                />
              </template>
            </el-table-column>
            <el-table-column label="员工姓名" prop="employeeName">
              <template #default="{ row }">
                <el-input
                  v-model="row.employeeName"
                  placeholder="请输入..."
                  maxlength="50"
                />
              </template>
            </el-table-column>
            <el-table-column label="员工联系方式" prop="employeeContact">
              <template #default="{ row }">
                <el-input
                  v-model="row.employeeContact"
                  placeholder="请输入11位手机号码"
                  maxlength="11"
                  @input="(val) => handlePhoneInputForTable(row, val)"
                />
              </template>
            </el-table-column>
            <el-table-column label="个人先进描述" prop="remark">
              <template #default="{ row }">
                <el-input
                  v-model="row.remark"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入..."
                  maxlength="300"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align-center>
              <template #default="{ $index }">
                <el-button
                  type="primary"
                  link
                  :disabled="advancedFormList.length >= 2"
                  @click="handleAddAdvancedRow"
                >
                  新增
                </el-button>
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveAdvancedRow($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        -->
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted, reactive, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS } from '../../evaluationSystem/configs/tables';
  import { EVALUATION_ADVANCED_PERSON_TABLE_COLUMNS } from '../../evaluationSystem/configs/targetTables';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    querySecurityExamineIssueAdvancedUser,
    querySecurityExamineDetail,
    saveSecurityExamineAdvUserAdmin,
    updateSecurityExamineAdvUserAdmin,
    deleteSecurityExamineDeptAdvUser,
    querySecurityExamineAdvUser,
  } from '@/api/evaluationSystem';
  import type {
    QuerySecurityExamineIssueAdvancedUserParams,
    EvaluationDeptAdvancedUserItem,
    EvaluationSystemItem,
    SaveSecurityExamineAdvUserAdminRequest,
    UpdateSecurityExamineAdvUserAdminRequest,
  } from '@/api/evaluationSystem';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';

  const route = useRoute();

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(EVALUATION_ADVANCED_PERSON_TABLE_COLUMNS, TABLE_OPTIONS);

  const tableData = ref<any[]>([]);

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      deptName: '',
      userName: '',
      dateRange: null as any,
      startTime: '',
      endTime: '',
    },
  });

  // 部门树（复用物品领取记录的部门下拉框逻辑）
  const deptCascaderRef = ref();
  const deptTree = ref<DeptTree[]>([]);
  const deptId = ref<number | null>(null);
  const cascaderDeptProp = {
    checkStrictly: true,
    expandTrigger: 'hover' as const,
    value: 'id',
    label: 'deptName',
    emitPath: false,
  };

  const getDeptTreeData = async () => {
    try {
      const res = await getAllDepartments();
      deptTree.value = res?.[0]?.children ?? [];
    } catch (e) {
      console.error('获取部门树失败:', e);
    }
  };

  const handleDeptChange = () => {
    const nodes = deptCascaderRef.value?.getCheckedNodes?.();
    tableQuery.queryParam.deptName = nodes?.[0]?.label ?? '';
  };

  // 从路由获取考核对象ID（psemId）
  const evaluationId = computed(() => {
    const id = route.query.id;
    return id ? Number(id) : undefined;
  });

  // 考核表详情
  const evaluationDetail = ref<Partial<EvaluationSystemItem>>({});
  const psemId = ref<number | undefined>(undefined); // 考核表ID（从接口获取）
  const deptUserId = ref<number | undefined>(undefined); // 部门用户ID（从接口获取）
  const currentDeptId = ref<number | undefined>(undefined); // 当前部门ID（用于保存操作）

  // 添加对话框相关
  const addDialogVisible = ref(false); // 添加对话框
  const deptType = ref<'normal' | 'advanced'>('normal'); // 当前部门类型
  const isEditMode = ref(false); // 是否为编辑模式
  const currentEditRow = ref<any>(null); // 当前编辑的行数据
  const editDetailData = ref<EvaluationDeptAdvancedUserItem | null>(null); // 编辑时的详情数据

  // 普通部门表单
  const normalFormRef = ref<FormInstance>();
  const normalForm = reactive({
    employeeCode: '',
    employeeName: '',
    employeeContact: '',
    remark: '',
  });

  const normalFormRules: FormRules = {
    employeeCode: [
      { required: true, message: '请输入员工工号', trigger: 'blur' },
    ],
    employeeName: [
      { required: true, message: '请输入员工姓名', trigger: 'blur' },
    ],
    employeeContact: [
      { required: true, message: '请输入员工联系方式', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' },
    ],
    remark: [
      { required: true, message: '请输入个人先进描述', trigger: 'blur' },
      { max: 300, message: '最多输入300个字符', trigger: 'blur' },
    ],
  };

  // 先进集体部门表单列表
  const advancedFormList = ref<Array<{
    employeeCode: string;
    employeeName: string;
    employeeContact: string;
    remark: string;
  }>>([
    {
      employeeCode: '',
      employeeName: '',
      employeeContact: '',
      remark: '',
    },
  ]);

  // 打开新增先进个人（普通部门）弹窗
  const openAddDialog = () => {
    deptType.value = 'normal';
    isEditMode.value = false;
    currentEditRow.value = null;
    editDetailData.value = null;
    // 重置部门与表单
    currentDeptId.value = undefined;
    if (normalFormRef.value) {
      normalFormRef.value.resetFields();
    }
    normalForm.employeeCode = '';
    normalForm.employeeName = '';
    normalForm.employeeContact = '';
    normalForm.remark = '';
    addDialogVisible.value = true;
  };

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const params: QuerySecurityExamineIssueAdvancedUserParams = {
        pageNumber: tableQuery.pageNumber,
        pageSize: tableQuery.pageSize,
        queryParam: {
          psemId: evaluationId.value, // 考核表ID（从路由参数获取）
          deptName: tableQuery.queryParam.deptName || undefined,
          userName: tableQuery.queryParam.userName || undefined,
          planStartTime: tableQuery.queryParam.startTime || undefined,
          planEndTime: tableQuery.queryParam.endTime || undefined,
        },
      };

      const res = await querySecurityExamineIssueAdvancedUser(params);
      if (res) {
        // 映射返回数据字段到表格字段（先进个人信息）
        tableData.value = res.records.map((item: EvaluationDeptAdvancedUserItem) => ({
          id: item.id, // 记录ID（用于删除等操作）
          employeeCode: item.advUserStaffNo || '-', // 员工工号
          employeeName: item.advUserName || '-', // 员工姓名
          employeeContact: item.advUserLink || '-', // 员工联系方式
          deptName: item.deptName || '-', // 所属部门
          departmentLeader: item.deptUserName || '-', // 部门负责人
          remark: item.remark || '-', // 先进个人描述
          reportDate: item.planEndTime || '-', // 上报日期
          // 保留原始数据，供编辑等操作使用
          originalData: item, // 保存列表接口返回的完整原始数据
        }));
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取先进个人信息列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  function handleSearch() {
    if (tableQuery.queryParam.dateRange && tableQuery.queryParam.dateRange.length === 2) {
      tableQuery.queryParam.startTime = tableQuery.queryParam.dateRange[0];
      tableQuery.queryParam.endTime = tableQuery.queryParam.dateRange[1];
    } else {
      tableQuery.queryParam.startTime = '';
      tableQuery.queryParam.endTime = '';
    }
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  }

  const handleReset = () => {
    tableQuery.queryParam.deptName = '';
    tableQuery.queryParam.userName = '';
    tableQuery.queryParam.dateRange = null;
    deptId.value = null;
    handleSearch();
  };

  // 选择部门类型（从下拉菜单触发）
  const selectDeptType = (type: 'normal' | 'advanced') => {
    deptType.value = type;
    addDialogVisible.value = true;
    
    // 如果是先进集体部门，初始化表格数据（默认1行）
    if (type === 'advanced') {
      advancedFormList.value = [
        {
          employeeCode: '',
          employeeName: '',
          employeeContact: '',
          remark: '',
        },
      ];
    }
  };

  // 处理电话号码输入（只允许数字）
  const handlePhoneInput = (value: string) => {
    // 只保留数字
    normalForm.employeeContact = value.replace(/\D/g, '');
  };

  // 处理表格中电话号码输入（只允许数字）
  const handlePhoneInputForTable = (row: any, value: string) => {
    // 只保留数字
    row.employeeContact = value.replace(/\D/g, '');
  };

  // 添加先进集体部门行
  const handleAddAdvancedRow = () => {
    if (advancedFormList.value.length < 2) {
      advancedFormList.value.push({
        employeeCode: '',
        employeeName: '',
        employeeContact: '',
        remark: '',
      });
    }
  };

  // 删除先进集体部门行
  const handleRemoveAdvancedRow = (index: number) => {
    if (advancedFormList.value.length > 1) {
      advancedFormList.value.splice(index, 1);
    } else {
      ElMessage.warning('至少需要保留一条记录');
    }
  };

  // 关闭对话框
  const handleDialogClose = () => {
    addDialogVisible.value = false;
    isEditMode.value = false;
    currentEditRow.value = null;
    editDetailData.value = null;
    // 重置表单
    if (normalFormRef.value) {
      normalFormRef.value.resetFields();
    }
    normalForm.employeeCode = '';
    normalForm.employeeName = '';
    normalForm.employeeContact = '';
    normalForm.remark = '';
    advancedFormList.value = [
      {
        employeeCode: '',
        employeeName: '',
        employeeContact: '',
        remark: '',
      },
    ];
    deptType.value = 'normal';
    currentDeptId.value = undefined;
  };

  // 验证普通部门表单
  const validateNormalForm = (): Promise<boolean> => {
    return new Promise((resolve) => {
      if (!normalFormRef.value) {
        resolve(false);
        return;
      }
      normalFormRef.value.validate((valid) => {
        resolve(valid);
      });
    });
  };

  // 验证先进集体部门表单
  const validateAdvancedForm = (): boolean => {
    const phonePattern = /^1[3-9]\d{9}$/;
    for (let i = 0; i < advancedFormList.value.length; i++) {
      const item = advancedFormList.value[i];
      if (!item.employeeCode || !item.employeeName || !item.employeeContact || !item.remark) {
        ElMessage.warning(`请填写第${i + 1}行的所有必填项`);
        return false;
      }
      if (!phonePattern.test(item.employeeContact)) {
        ElMessage.warning(`第${i + 1}行的员工联系方式请输入正确的11位手机号码`);
        return false;
      }
      if (item.remark.length > 300) {
        ElMessage.warning(`第${i + 1}行的个人先进描述最多输入300个字符`);
        return false;
      }
    }
    return true;
  };

  // 保存
  const handleSave = async () => {
    try {
      if (isEditMode.value) {
        // 编辑模式：直接使用详情接口返回的数据作为更新参数，
        // 并用弹窗表单中的输入值覆盖相应字段
        if (!editDetailData.value || !editDetailData.value.id) {
          ElMessage.error('缺少编辑记录数据，无法保存');
          return;
        }

        const updatePayload: UpdateSecurityExamineAdvUserAdminRequest = {
          ...editDetailData.value,
          advUserStaffNo: normalForm.employeeCode,
          advUserName: normalForm.employeeName,
          advUserLink: normalForm.employeeContact,
          remark: normalForm.remark,
        };

        // 编辑模式：调用更新接口
        await updateSecurityExamineAdvUserAdmin(updatePayload);
      } else {
        // 新增模式：psemId 使用路由参数的 id，deptId 使用选择的部门
        if (!evaluationId.value || !currentDeptId.value) {
          ElMessage.error('缺少必要参数');
          return;
        }

        // 目前仅保留普通部门表单逻辑
        // 验证普通部门表单
        const isValid = await validateNormalForm();
        if (!isValid) {
          return;
        }

        const createPayload: SaveSecurityExamineAdvUserAdminRequest = {
          psemId: evaluationId.value,
          deptId: currentDeptId.value,
          advUserStaffNo: normalForm.employeeCode,
          advUserName: normalForm.employeeName,
          advUserLink: normalForm.employeeContact,
          remark: normalForm.remark,
        };

        // 新增模式：调用保存接口
        await saveSecurityExamineAdvUserAdmin(createPayload);
      }
      ElMessage.success('保存成功');
      handleDialogClose();
      getTableData();
    } catch (e) {
      console.error('保存失败:', e);
      ElMessage.error('保存失败');
    }
  };

  const handleEdit = async (row: any) => {
    if (!row.id) {
      ElMessage.error('缺少记录ID，无法编辑');
      return;
    }

    try {
      // 调用管理员端详情接口获取数据
      const detail = await querySecurityExamineAdvUser(row.id);
      
      // 保存当前编辑的行数据和详情数据
      currentEditRow.value = row;
      editDetailData.value = detail;
      isEditMode.value = true;
      deptType.value = 'normal'; // 编辑时固定为普通部门
      addDialogVisible.value = true;
      
      // 回填表单数据（普通部门）- 使用详情数据
      currentDeptId.value = detail.deptId || undefined;
      normalForm.employeeCode = detail.advUserStaffNo || '';
      normalForm.employeeName = detail.advUserName || '';
      normalForm.employeeContact = detail.advUserLink || '';
      normalForm.remark = detail.remark || '';
    } catch (e) {
      console.error('获取详情失败:', e);
      ElMessage.error('获取详情失败');
    }
  };

  const handleDelete = async (row: any) => {
    try {
      await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      });
      
      if (!row.id) {
        ElMessage.error('缺少记录ID，无法删除');
        return;
      }
      
      await deleteSecurityExamineDeptAdvUser(row.id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e: any) {
      // 用户取消删除或删除失败
      if (e !== 'cancel') {
        console.error('删除失败:', e);
        ElMessage.error('删除失败');
      }
    }
  };

  const handleExport = () => {
    // TODO: 导出当前筛选结果
    console.log('export advanced person list', tableQuery);
  };

  // 格式化日期时间
  const formatDateTime = (dateTimeStr: string | undefined): string => {
    if (!dateTimeStr) return '';
    try {
      const date = new Date(dateTimeStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (e) {
      return dateTimeStr;
    }
  };

  // 获取考核表详情
  const getEvaluationDetail = async () => {
    // 路由参数中的id是考核表ID（psemId），直接使用
    if (!evaluationId.value) return;
    
    try {
      const res = await querySecurityExamineDetail(evaluationId.value);
      if (res) {
        evaluationDetail.value = {
          exName: res.exName,
          deptNames: res.deptNames,
          createdUserName: res.createdUserName,
          createdAt: res.createdAt,
        };
        // 保存考核表ID，用于提交时使用
        psemId.value = res.id;
      }
    } catch (e) {
      console.error('获取考核表详情失败:', e);
    }
  };

  onMounted(() => {
    getDeptTreeData();
    getTableData();
    getEvaluationDetail();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/styles/basic-table-file.scss' as *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;

  .safety-platform-container__header {
    padding-bottom: 0 !important;
  }

  .evaluation-header {
    width: 100%;
  }

  .evaluation-title {
    font-size: 20px;
    font-weight: bold;
    margin: 0 0 12px 0;
    color: #333;
  }

  .evaluation-meta {
    margin-bottom: 12px;
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: #666;
  }

  .evaluation-meta span {
    white-space: nowrap;
  }

  .add-dialog-content {
    .description {
      margin-bottom: 24px;
      padding: 12px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .description-label {
        font-weight: bold;
        color: #333;
      }

      .description-text {
        color: #666;
        line-height: 1.6;
      }
    }
  }


  .dialog-footer {
    text-align: right;
  }
</style>
