<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-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" style="margin:0 10px;" @click="handleAdd">
                添加
              </el-button>
              <el-button plain  @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="员工工号：" 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 {
    querySecurityExamineDeptAdvancedUser,
    querySecurityExamineIssueDeptDetail,
    saveSecurityExamineDeptAdvUser,
    deleteSecurityExamineDeptAdvUser,
    querySecurityExamineDeptAdvUserDetail,
    updateSecurityExamineDeptAdvUser,
  } from '@/api/evaluationSystem';
  import type {
    QuerySecurityExamineDeptAdvancedUserParams,
    EvaluationDeptAdvancedUserItem,
    EvaluationTargetItem,
    UpdateSecurityExamineDeptAdvUserRequest,
  } from '@/api/evaluationSystem';

  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: {
      userName: '',
      dateRange: null as any,
      startTime: '',
      endTime: '',
    },
  });

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

  // 考核表详情
  const evaluationDetail = ref<Partial<EvaluationTargetItem>>({});
  // isAdvancedGroup 为 true 表示先进集体部门，false 表示普通部门
  const isAdvancedGroup = computed(() => Boolean(route.query.isAdvancedGroup));
  const deptId = ref<number | undefined>(undefined); // 部门ID
  const psemId = ref<number | undefined>(undefined); // 考核表ID（从接口获取）
  const deptUserId = 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 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: QuerySecurityExamineDeptAdvancedUserParams = {
        pageNumber: tableQuery.pageNumber,
        pageSize: tableQuery.pageSize,
        queryParam: {
          psemId: evaluationId.value, // 考核表ID（从路由参数获取）
          userName: tableQuery.queryParam.userName || undefined,
          planStartTime: tableQuery.queryParam.startTime || undefined,
          planEndTime: tableQuery.queryParam.endTime || undefined,
        },
      };

      const res = await querySecurityExamineDeptAdvancedUser(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.userName = '';
    tableQuery.queryParam.dateRange = null;
    handleSearch();
  };

  // 点击添加：根据 isAdvancedGroup 直接打开对应弹窗（true=先进集体部门，false=普通部门）
  const handleAdd = () => {
    deptType.value = isAdvancedGroup.value ? 'advanced' : 'normal';
    addDialogVisible.value = true;

    if (isAdvancedGroup.value) {
      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';
  };

  // 验证普通部门表单
  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 () => {
    if (!psemId.value || !deptId.value) {
      ElMessage.error('缺少必要参数');
      return;
    }

    let users: Array<{
      deptId: number;
      advUserStaffNo: string;
      advUserName: string;
      advUserLink: string;
      remark: string;
    }> = [];

    if (deptType.value === 'normal') {
      // 验证普通部门表单
      const isValid = await validateNormalForm();
      if (!isValid) {
        return;
      }
      users = [
        {
          deptId: deptId.value,
          advUserStaffNo: normalForm.employeeCode,
          advUserName: normalForm.employeeName,
          advUserLink: normalForm.employeeContact,
          remark: normalForm.remark,
        },
      ];
    } else {
      // 验证先进集体部门表单
      if (!validateAdvancedForm()) {
        return;
      }
      // 过滤掉空行
      users = advancedFormList.value
        .filter(
          (item) =>
            item.employeeCode || item.employeeName || item.employeeContact || item.remark,
        )
        .map((item) => ({
          deptId: deptId.value!,
          advUserStaffNo: item.employeeCode,
          advUserName: item.employeeName,
          advUserLink: item.employeeContact,
          remark: item.remark,
        }));
    }

    if (users.length === 0) {
      ElMessage.warning('请至少填写一条记录');
      return;
    }

    try {
      if (isEditMode.value && currentEditRow.value?.id && editDetailData.value) {
        // 编辑模式：调用更新接口
        // 验证表单
        const isValid = await validateNormalForm();
        if (!isValid) {
          return;
        }
        if (!psemId.value) {
          ElMessage.error('缺少必要参数');
          return;
        }
        // 使用详情接口返回的数据作为基础，但使用表单中修改后的字段
        const updateParams: UpdateSecurityExamineDeptAdvUserRequest = {
          id: currentEditRow.value.id,
          psemId: psemId.value,
          deptName: editDetailData.value.deptName,
          deptId: editDetailData.value.deptId || deptId.value || 0,
          deptUserId: editDetailData.value.deptUserId || deptUserId.value || 0,
          deptUserName: editDetailData.value.deptUserName,
          deptUserLink: editDetailData.value.deptUserLink,
          // 使用表单中修改后的字段
          advUserStaffNo: normalForm.employeeCode,
          advUserName: normalForm.employeeName,
          advUserLink: normalForm.employeeContact,
          remark: normalForm.remark,
        };
        await updateSecurityExamineDeptAdvUser(updateParams);
        ElMessage.success('更新成功');
      } else {
        // 新增模式：调用保存接口
        await saveSecurityExamineDeptAdvUser({
          psemId: psemId.value,
          users,
        });
        ElMessage.success('保存成功');
      }
      handleDialogClose();
      getTableData();
    } catch (e) {
      console.error('保存失败:', e);
      ElMessage.error(e?.message || e?.data || (isEditMode.value ? '更新失败' : '保存失败'));
    }
  };

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

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

  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(e?.message || e?.data || '删除失败');
      }
    }
  };

  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;
    }
  };

  // 获取考核表详情（使用考核对象ID，即psemId）
  const getEvaluationDetail = async () => {
    // 路由参数中的id是考核对象ID（psemId），直接使用
    if (!evaluationId.value) return;
    
    try {
      const res = await querySecurityExamineIssueDeptDetail(evaluationId.value);
      if (res) {
        evaluationDetail.value = {
          exName: res.exName,
          deptNames: res.deptName, // 部门端接口返回的是 deptName，不是 deptNames
          createdUserName: res.deptUserName || '-', // 部门端可能没有创建人字段，使用部门用户名
          createdAt: res.createdAt,
          isAdvancedGroup: res.isAdvancedGroup,
        };
        // 保存部门ID、考核表ID和部门用户ID，用于提交时使用
        deptId.value = res.deptId;
        psemId.value = res.psemId;
        deptUserId.value = res.deptUserId;
      }
    } catch (e) {
      console.error('获取考核表详情失败:', e);
    }
  };

  onMounted(() => {
    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>
