<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="evaluation-header">
        <h1 class="evaluation-title">{{ activityRegistrationDetail.planName || '' }}</h1>
        <div class="evaluation-meta">
          <span>考核部门: {{ activityRegistrationDetail.responsibleDeptName || '-' }}</span>
          <span>创建人: {{ activityRegistrationDetail.createdByName || '-' }}</span>
          <span>创建时间: {{ formatDateTime(activityRegistrationDetail.startTime) || '-' }}</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.keyword" 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="selectDeptType">
                添加
              </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 && normalForm.id ? '编辑' : '添加'}活动报名信息`" width="800px"
      :close-on-click-modal="false" @close="handleDialogClose">
      <div class="add-dialog-content">

        <!-- 普通部门表单 -->
        <el-form ref="normalFormRef" :model="normalForm" :rules="normalFormRules" label-width="140px">
          <!-- <el-form-item label="部门名称" prop="employeeDeptName">
            <el-cascader style="width: 100%" size="large" :ref="(el) => (cascaderRef['employeeDeptName'] = el)"
              :options="firstLevelDepts" :props="cascaderProp" :show-all-levels="false" placeholder="请选择安全责任部门"
              filterable v-model="normalForm.deptId" @change="(val) => handleChangeDept(val, 'employeeDeptName')" />
          </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>

      <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 '../configs/activityTables';
import { ACTIVITY_REGISTRATION_ADVANCED_PERSON_TABLE_COLUMNS } from '../configs/activityTargetTables';
import type { QueryPageRequest } from '@/types/basic-query';
import {
  querySafetyCultureActivityDetail,
  saveSafetyCultureActivityExecutorManagement,
  getAllDepartments,
  addSafetyCultureActivityRegistration,
  deleteSafetyCultureActivityRegistration,
  updateSafetyCultureActivityManagement,
  type ActivityRegistrationTargetItem,
  type safetyCultureFilePageQuery,
} from '@/api/safety-culture';
import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
import { id } from 'element-plus/es/locale';

const route = useRoute();

const currentId = computed(() => Number(route.query.id));

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

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

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

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

const activityRegistrationId = computed(() => {
  const id = route.query.id;
  return id ? Number(id) : undefined;
});

// 考核表详情
const activityRegistrationDetail = ref<Partial<ActivityRegistrationTargetItem>>({});

// 添加对话框相关
const addDialogVisible = ref(false);
const isEditMode = ref(false);
const currentEditRow = ref<any>(null);
const editDetailData = ref(null);

const normalFormRef = ref<FormInstance>();
const normalForm = reactive({
  id: '',
  // employeeDeptName: '',
  employeeCode: '',
  employeeName: '',
  employeeContact: '',
  remark: '',
  deptId: '',
});

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

const normalFormRules: FormRules = {
  // employeeDeptName: [
  //   { required: true, message: '请选择部门名称', trigger: 'blur' },
  // ],
  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 cascaderProp = {
  expandTrigger: 'click',
  checkStrictly: true,
  // emitPath: false,
  value: 'id',
  label: 'deptName',
};

const cascaderRef = ref({});

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 = {
      pageNumber: tableQuery.pageNumber,
      pageSize: tableQuery.pageSize,
      queryParam: {
        keyword: tableQuery.queryParam.keyword,
        startDate: tableQuery.queryParam.startTime,
        endDate: tableQuery.queryParam.endTime,
        activityId: activityRegistrationId.value,
      },
    };

    const res = await saveSafetyCultureActivityExecutorManagement(params);
    if (res) {
      tableData.value = res.records
    }
  } 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.keyword = '';
  tableQuery.queryParam.dateRange = null;
  handleSearch();
};

// 添加注册活动
const selectDeptType = () => {
  isEditMode.value = true;
  addDialogVisible.value = true;
};

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

// 关闭对话框
const handleDialogClose = () => {
  addDialogVisible.value = false;
  isEditMode.value = false;
  currentEditRow.value = null;
  editDetailData.value = null;
  // 重置表单
  if (normalFormRef.value) {
    normalFormRef.value.resetFields();
    normalForm.deptId = '';
  }
};

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

// 保存
const handleSave = async () => {

  type ActivityUserParams = {
    id?: number; // 编辑时必传，新增时可选
    activityId?: number;
    deptId?: number;
    employeeId: string;
    employeeName: string;
    employeeContact: string;
    remark: string;
  };
  
  const isValid = await validateNormalForm();
  if (!isValid) {
    return;
  }
  const addUsers: ActivityUserParams = {
    ...(normalForm.id && { id: Number(normalForm.id) }),
    activityId: activityRegistrationDetail.value.id,
    deptId: normalForm.deptId ? Number(normalForm.deptId) : undefined,
    employeeId: normalForm.employeeCode.trim(),
    employeeName: normalForm.employeeName.trim(),
    employeeContact: normalForm.employeeContact.trim(),
    remark: normalForm.remark.trim(),
  };
  try {
    if (isEditMode.value && normalForm.id) {
      await updateSafetyCultureActivityManagement(addUsers);
      ElMessage.success('更新成功');
    } else {
      await addSafetyCultureActivityRegistration(addUsers);
      ElMessage.success('添加成功');
    }
    handleDialogClose();
    getTableData();
  } catch (e) {
    console.error('保存失败:', e);
    ElMessage.error(isEditMode.value ? '更新失败' : '保存失败');
  }
};

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

  try {
    isEditMode.value = true;
    addDialogVisible.value = true;
    normalForm.id = row.id;
    normalForm.deptId = row.deptId;
    normalForm.employeeCode = row.employeeId;
    normalForm.employeeName = row.employeeName;
    normalForm.employeeContact = row.employeeContact;
    normalForm.remark = row.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 deleteSafetyCultureActivityRegistration(row.id);
    ElMessage.success('删除成功');
    getTableData();
  } catch (e: any) {
    // 用户取消删除或删除失败
    if (e !== 'cancel') {
      console.error('删除失败:', e);
      ElMessage.error('删除失败');
    }
  }
};

const handleExport = () => {
  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 getActivityRegistrationDetail = async () => {
  if (!activityRegistrationId.value) return;

  try {
    const res = await querySafetyCultureActivityDetail(activityRegistrationId.value);
    if (res) {
      activityRegistrationDetail.value = res;
    }
  } catch (e) {
    console.error('获取考核表详情失败:', e);
  }
};

const getDeptData = () => {
  getAllDepartments().then((res) => {
    firstLevelDepts.value = formatDeptTree(res);
    console.log('@res:', res);
  });
};

const handleChangeDept = (val, prop) => {
  // const cascader = cascaderRef.value?.[prop];
  // const deptInfo = cascader?.getCheckedNodes();
  // if (deptInfo && deptInfo.length > 0) {
  //   normalForm.employeeDeptName = deptInfo[0].label;
  //   normalForm.deptId = val[val.length - 1]
  // } else {
  //   normalForm.employeeDeptName = '';
  // }
};

onMounted(() => {
  getTableData();
  getActivityRegistrationDetail();
  getDeptData();
});
</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;
}


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