<!--
 * @Author: liuJie
 * @Date: 2026-02-13 16:04:29
 * @LastEditors: liuJie
 * @LastEditTime: 2026-02-25 16:10:44
 * @Describe: file describe
-->
<script setup lang="ts">
  import { ref, watch, reactive, onMounted } from 'vue';
  import { ElDialog, ElPopconfirm } from 'element-plus';
  import { EDIT_EMPLOYEE_FORM_RULES } from '../configs/form';
  import {
    getEmployeeDetailTableList,
    type EmployeeTableType,
    updateEducationStaffTrainingCardScore,
    delateEducationStaffTrainingCardScore,
  } from '@/api/employee-training-record-card-management';
  const props = defineProps({
    index: {
      type: Number,
      default: 1,
    },
    id: {
      type: Number,
      default: 0,
    },
  });
  const rules = ref(EDIT_EMPLOYEE_FORM_RULES);

  const pagination = reactive({
    pageNumber: 1,
    pageSize: 10,
    total: 0,
  });
  // 日期范围
  const dateRange = ref<[string, string] | null>(null);

  const tableQuery = reactive({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      logType: props.index,
      pestcId: props.id,
      keyword: '',
      dateStart: '',
      dateEnd: '',
    },
  });
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getActionTableList();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getActionTableList();
  };
  // 格式化时间
  const formatDate = (date) => {
    if (!date) return '';
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`; // 输出：2026-02-11
  };
  let tableData = ref<any[]>([]);
  const getActionTableList = async () => {
    tableQuery.queryParam.dateStart = dateRange.value ? formatDate(dateRange.value[0]) : '';
    tableQuery.queryParam.dateEnd = dateRange.value ? formatDate(dateRange.value[1]) : '';

    try {
      const res = await getEmployeeDetailTableList(tableQuery);
      if (res) {
        tableData.value = res.records;
        pagination.total = res.totalRow;
      }
    } catch (e) {
      tableData.value = [];
      pagination.total = 0;
    }
  };
  watch(
    () => props.index,
    (val) => {
      if (val === 3 || val === 4) {
        tableQuery.queryParam.logType = val;
        getActionTableList();
      }
    },
    { immediate: true, deep: true },
  );

  const ediDialogVisible = ref(false);
  const formData = reactive({
    id: 0,
    educationContent: '',
    scoreMust: '',
    score: '',
    operationCertificateNum: '',
  });
  const editHandle = (row) => {
    Object.assign(formData, {
      id: row.id,
      educationContent: row.educationContent,
      scoreMust: row.scoreMust,
      score: row.score,
      operationCertificateNum: row.operationCertificateNum,
    });
    ediDialogVisible.value = true;
  };
  const deleteHandle = (id) => {
    try {
      delateEducationStaffTrainingCardScore(id);
      getActionTableList();
    } catch (e) {
      console.error('删除失败', e);
    }
  };

  const cancelHandle = () => {
    ediDialogVisible.value = false;
  };
  const confirmHandle = async () => {
    ediDialogVisible.value = false;
    try {
      await updateEducationStaffTrainingCardScore(formData);
      getActionTableList();
    } catch (e) {
      console.error('保存失败', e);
    }
  };
  const handleSearch = () => {
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getActionTableList();
  };

  const handleReset = () => {
    tableQuery.queryParam.keyword = '';
    tableQuery.queryParam.dateStart = '';
    tableQuery.queryParam.dateEnd = '';
    dateRange.value = null;
    tableQuery.pageNumber = 1;
    handleSearch();
  };
</script>
<template>
  <div>
    <!-- 查询区 -->
    <el-form :inline="true" class="mb-12">
      <el-form-item>
        <el-date-picker type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" />
      </el-form-item>
      <el-form-item>
        <el-input placeholder="搜索关键词" v-model="tableQuery.queryParam.keyword" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="default" @click="handleReset">重置</el-button>
        <!-- <el-button type="primary">导出</el-button>
                <el-button type="danger">删除</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table border stripe :data="tableData">
      <el-table-column type="selection" width="50" />
      <el-table-column label="编号" prop="serialNum" width="100" />
      <el-table-column label="日期" prop="logDate" width="200" />
      <el-table-column label="工种名称" prop="educationContent" width="180" />
      <el-table-column label="考核成绩-应知" prop="score">
        <template #default="scope">
          <span>{{ scope.row.score }}分</span>
        </template>
      </el-table-column>
      <el-table-column label="考核成绩-应会" prop="scoreMust">
        <template #default="scope">
          <span>{{ scope.row.scoreMust }}分</span>
        </template>
      </el-table-column>
      <el-table-column label="操作证号" prop="operationCertificateNum" />
      <el-table-column label="培训单位" prop="trainingCompany" />
      <el-table-column label="学时" prop="creditHour">
        <template #default="scope">
          <span>{{ scope.row.creditHour }}时</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button link type="primary" @click="editHandle(scope.row)">编辑</el-button>
          <el-popconfirm title="确定要删除该条记录吗？" placement="top" @confirm="deleteHandle(scope.row.id)">
            <template #reference>
              <el-button link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        layout="total, prev, pager, next"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑 -->
    <el-dialog v-model="ediDialogVisible" title="编辑内容" width="550px">
      <el-form :rules="rules" :model="formData" label-width="140px">
        <el-form-item label="工种名称：" prop="educationContent">
          <el-input v-model="formData.educationContent" placeholder="输入工种名称" />
        </el-form-item>
        <el-form-item label="考核成绩-应知：" prop="score">
          <el-input v-model="formData.score" placeholder="输入成绩分数，单位分，0-200" />
        </el-form-item>
        <el-form-item label="考核成绩-应会：" prop="scoreMust">
          <el-input v-model="formData.scoreMust" placeholder="输入成绩分数，单位分，0-200" />
        </el-form-item>
        <el-form-item label="操作证号：" prop="operationCertificateNum">
          <el-input v-model="formData.operationCertificateNum" placeholder="输入操作证号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelHandle">取 消</el-button>
        <el-button type="primary" @click="confirmHandle">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
  .mb-12 {
    margin-bottom: 12px;
  }

  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
</style>
