<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :span-method="spanMethod"
      :row-class-name="rowClassName"
    >
      <template #menu-left>
        <el-button type="danger" @click="handleDeletes">批量删除</el-button>
        <el-button type="primary" @click="handleMaintain">证书维护</el-button>
      </template>
      <template #menu-right>
        <!-- <el-button type="primary" @click="handleImport">导 入</el-button> -->
      </template>
      <template #menu="{ row }"> </template>

      <template #heatTreat="scope"> </template>
    </avue-crud>
    <!-- 证书维护 -->
    <maintain-dialog
      v-if="showMaintain"
      :show-maintain="showMaintain"
      @closeDialog="closeDialog"
      :maintain-list="maintainList"
    ></maintain-dialog>
   <!-- 导入 -->
    <basic-import
      v-if="isShowImport"
      title="导入"
      :isShow="isShowImport"
      templateUrl="/blade-desk/certificateMaintenance/downloadExcelTemplate"
      templateName="上岗台账导入模板.xlsx"
      importUrl="/blade-desk/certificateMaintenance/importExcel"
      @closeDialog="closeDialog"
    ></basic-import>
  </basic-container>
</template>

<script>
import maintainDialog from './components/maintainDialog.vue';

import { getList, remove, add, update, getCertificateType } from '@/api/workLicense/workLicense';
import basicImport from '@/components/basic-import/main.vue';

export default {
  components: {
    maintainDialog,
    basicImport
  },
  data() {
    return {
      isShowImport: false,
      form: {},
      selectionList: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        columnSort: true,
        tip: false,
        height: 'auto',
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtnText: '修改',
        labelWidth: 120,
        menuWidth: 80,
        dialogWidth: 900,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        excelBtn: true,
        showOverflowTooltip: true,
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        gridBtn: false,
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        align: 'center',
        menu: false,
        column: [
          {
            label: '姓名',
            prop: 'name',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: true,
            fixed:'left',
            searchLabelWidth:50,
            rules: [
              {
                required: true,
                message: '请输入姓名',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '所属班组',
            prop: 'deptName',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
          },
          {
            label: '所属岗位',
            prop: 'station',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
          },
          {
            label: '技能等级',
            prop: 'skillName',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
          },
          {
            label: '性别',
            prop: 'userSex',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
          },
          {
            label: '最高学历',
            prop: 'education',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
          },
          {
            label: '出生年月',
            prop: 'dataBirth',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
          },
          {
            label: '证书类型',
            prop: 'certificateId',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
            type: 'select',
            dicUrl: '/blade-desk/certificateType/page?current=1&size=99999',
            props: {
              label: 'name',
              value: 'id',
              res: 'data.records',
            },
          },
          {
            label: '证书编号',
            prop: 'certificateCode',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
          },
          {
            label: '从事本岗位或工种时间',
            prop: 'workingYears',
            span: 24,
            width: 200,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入从事本岗位或工种时间',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '上岗证日期',
            prop: 'certificateDate',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入上岗证日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '上岗证有效期(年)',
            prop: 'validityPeriod',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入上岗证有效期(年)',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '到期日期',
            prop: 'conExpDate',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入到期日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '适航日期',
            prop: 'airworthinessDate',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入适航日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '适航有效期(年)',
            prop: 'airworthinessValidityPeriod',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入适航有效期(年)',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '适航到期日期',
            prop: 'airworthinessDateExpire',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入到期日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '宇航日期',
            prop: 'astronautDate',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入宇航日期',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '宇航到期日期',
            prop: 'astronautDateExpire',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入到期日期',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '状态',
            prop: 'phStatusName',
            span: 24,
            width: 150,
            overflow: true,
            rules: [
              {
                required: true,
                message: '请输入状态',
                trigger: 'blur',
              },
            ],
          },
        ],
      },
      spanArr: [
        { prop: 'name', span: [] },
        { prop: 'deptName', span: [] },
        { prop: 'station', span: [] },
        { prop: 'skillName', span: [] },
        { prop: 'userSex', span: [] },
        { prop: 'education', span: [] },
        { prop: 'dataBirth', span: [] },
        { prop: 'certificateId', span: [] },
        { prop: 'certificateCode', span: [] },
        { prop: 'workingYears', span: [] },
        { prop: 'certificateDate', span: [] },
        { prop: 'validityPeriod', span: [] },
        { prop: 'conExpDate', span: [] },
        { prop: 'airworthinessDate', span: [] },
        { prop: 'airworthinessValidityPeriod', span: [] },
        { prop: 'airworthinessDateExpire', span: [] },
        { prop: 'astronautDate', span: [] },
        { prop: 'astronautDateExpire', span: [] },
        { prop: 'phStatusName', span: [] },
      ],

      data: [],
      maintainList: [], //证书维护数据
      showMaintain: false, //证书维护弹窗
    };
  },
  methods: {
     // 点击导入按钮
    handleImport() {
      this.isShowImport = true;
    },
    closeDialog() {
      this.showMaintain = false;
      this.isShowImport = false;
      this.onLoad(this.page, this.query);
    },
    // 批量删除
    handleDeletes() {
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据');
      } else {
        // 检查是否所有选中项都有 certificateTypeId
        const invalidItem = this.selectionList.find(
          item => !item.certificateTypeId || item.certificateTypeId === ''
        );
        if (invalidItem) {
          this.$message.error('存在未分配证书的数据，无法删除');
          return;
        }

        this.$confirm('确定删除数据吗?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          let ids = [];

          this.selectionList.forEach(item => {
            ids.push(item.certificateTypeId);
          });
          remove({ ids: ids.join(',') }).then(res => {
            this.$message.success('操作成功');
            this.onLoad(this.page, this.query);
          });
        });
      }
    },
    // 证书维护
    handleMaintain() {
      if (this.selectionList.length > 0) {
        let tmp = this.data.filter(item1 =>
          this.selectionList.some(item2 => item2.name === item1.name)
        );
        let tmp1 = Array.from(new Set(tmp.map(item => item.certificateCode))).map(wlCode => {
          return tmp.find(item => item.certificateCode === wlCode);
        });
        this.maintainList = tmp1;
      } else {
        this.maintainList = [];
      }

      this.showMaintain = true;
    },
    // 行样式
    rowClassName: ({ row, rowIndex }) => {
      // 检查各种证书是否过期
      const now = new Date();
      let isExpired = false;

      // 检查上岗证是否过期
      if (row.wlDueDate) {
        const wlDueDate = new Date(row.wlDueDate);
        if (wlDueDate < now) {
          isExpired = true;
        }
      }

      // 检查适航证是否过期
      if (row.seaDueDate) {
        const seaDueDate = new Date(row.seaDueDate);
        if (seaDueDate < now) {
          isExpired = true;
        }
      }

      // 检查宇航证是否过期
      if (row.astrdueDate) {
        const astrDueDate = new Date(row.astrdueDate);
        if (astrDueDate < now) {
          isExpired = true;
        }
      }

      // 检查设备证是否过期
      if (row.deviceDueDate) {
        const deviceDueDate = new Date(row.deviceDueDate);
        if (deviceDueDate < now) {
          isExpired = true;
        }
      }
      // 如果状态本身就是过期，或者任何证书已过期，则应用过期样式
      if (isExpired || row.wlStatusTitle === '过期') {
        return 'expired-row';
      }
      return '';
    },
    // 合并单元格
    spanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        // 只处理“姓名”列（prop: 'name' 对应第0列）
        const rows = this.data;
        const currentName = row.name;
        let rowspan = 1;
        let isTopRow = true;

        // 向上查找是否是连续相同 name 的起始行
        for (let i = rowIndex - 1; i >= 0; i--) {
          if (rows[i].name === currentName) {
            isTopRow = false;
            break;
          } else {
            break;
          }
        }

        // 如果不是顶部行，则隐藏（rowspan=0）
        if (!isTopRow) {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
        // 向下统计相同 name 的行数
        for (let i = rowIndex + 1; i < rows.length; i++) {
          if (rows[i].name === currentName) {
            rowspan++;
          } else {
            break;
          }
        }

        return {
          rowspan: rowspan,
          colspan: 1,
        };
      }
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page, this.query);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        let resData = res.data.data.records;
        const result = [];
        resData.forEach(outerObj => {
          const { postHandleVO, certificateMaintenanceVOList = [] } = outerObj;
          if (certificateMaintenanceVOList.length > 0) {
            certificateMaintenanceVOList.forEach(innerObj => {
              innerObj.certificateTypeId = innerObj.id;
              result.push({ ...postHandleVO, ...innerObj });
            });
          } else {
            result.push({ ...postHandleVO, certificateTypeId: '' });
          }
        });
        this.data = result;
        console.log('result', result);
        this.loading = false;
        this.page.total = res.data.data.total;
      });
    },
  },
  mounted() {},
};
</script>
