<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"
     
      :row-class-name="rowClassName"
    >
     <!-- :span-method="spanMethod" -->
      <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 #equipmentDate="scope">
          {{ scope.row.equipmentDate ?scope.row.equipmentDate.substring(0, 10) : ''}}
      </template>
       <template #deviceDueDate="scope">
          {{ scope.row.deviceDueDate ?scope.row.deviceDueDate.substring(0, 10) : ''}}
      </template>
      <template #dataBirth="scope">
          {{ scope.row.dataBirth ?scope.row.dataBirth.substring(0, 10) : ''}}
      </template>
      
    </avue-crud>
    <!-- 设备维护 -->
    <equipmentDialog
      v-if="showMaintain"
      :show-maintain="showMaintain"
      @closeDialog="closeDialog"
      :maintain-list="maintainList"
    ></equipmentDialog>

    <!-- 导入 -->
    <basic-import
      v-if="isShowImport"
      title="导入"
      :isShow="isShowImport"
      templateUrl="/blade-desk/equipmentMaintenance/downloadExcelTemplate"
      templateName="人员设备台账导入模板.xlsx"
      importUrl="/blade-desk/equipmentMaintenance/importExcel"
      @closeDialog="closeDialog"
    ></basic-import>
  </basic-container>
</template>

<script>
import equipmentDialog from './components/equipmentDialog.vue';
import basicImport from '@/components/basic-import/main.vue';
import { getList, remove, add, update } from '@/api/workLicense/personnelEquipment';

export default {
  components: {
    equipmentDialog,
    basicImport,
  },
  data() {
    return {
      isShowImport: false,
      ccieDialog: false,
      indateDialog: false,
      deviceDialog: false,
      showMaintain: false,
      maintainList: [],
      deviceTime: '',
      showType: false,
      deviceLifespan: '',
      selectValue: '',
      dateNum: '',
      loading: false,
      setDialog: false,
      setForm: {},
      setRules: {},
      data: [],
      inDateArr: [],
      form: {},
      deviceData: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },

      selectionList: [],
      spanArr: [
        { prop: 'userName', span: [] },
        { prop: 'deptName', span: [] },
        { prop: 'station', span: [] },
        { prop: 'skillTitle', span: [] },
        { prop: 'userSex', span: [] },
        { prop: 'education', span: [] },
        { prop: 'dataBirth', span: [] },
        { prop: 'wlCode', span: [] },
        { prop: 'toNewJobDueDate', span: [] },
        { prop: 'wlTime', span: [] },
        { prop: 'wlLifespan', span: [] },
        { prop: 'wlDueDate', span: [] },
        { prop: 'seaTime', span: [] },
        { prop: 'seaLifespan', span: [] },
        { prop: 'seaDueDate', span: [] },
        { prop: 'astrTime', span: [] },
        { prop: 'astrLifespan', span: [] },
        { prop: 'astrdueDate', span: [] },
      ],
      option: {
        columnSort: true,
        tip: false,
        height: 'auto',
        align: 'center',
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        addBtn: false,
        labelWidth: 120,
        menu: false,
        menuWidth: 200,
        dialogWidth: 600,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: true,
        gridBtn: false,
        searchShowBtn: false,
        showOverflowTooltip: true,
        searchLabelPosition: 'left',
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        searchShowBtn: false,

        column: [
          {
            label: '姓名',
            prop: 'name',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: true,
            fixed: 'left',
            searchLabelWidth:50,
          },
          {
            label: '所属班组',
            prop: 'deptName',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
          },
          {
            label: '所属岗位',
            prop: 'station',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
          },
          {
            label: '技能等级',
            prop: 'skill',
            type: 'select',
            span: 8,
            labelWidth: 150,
            search: true,
            width: 200,
            dicUrl: '/blade-system/dict/dictionary?code=skill_level',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
          },
          {
            label: '性别',
            prop: 'genderName',
            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: 'macSpec',
          //   span: 24,
          //   width: 150,
          //   labelWidth: 140,
          //   overflow: true,
          //   search: false,
          // },
          {
            label: '设备名称',
            prop: 'deviceName',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
           {
            label: '设备编号',
            prop: 'deviceCode',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '设备时间',
            prop: 'equipmentDate',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '设备有效期(天)',
            prop: 'equipmentValidityPeriod',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '设备到期日期',
            prop: 'deviceDueDate',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
          {
            label: '状态',
            prop: 'maintenanceStatusName',
            type: 'select',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: false,
          },
        ],
      },
    };
  },
  mounted() {

  },
  methods: {
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.showMaintain = false;
      this.showType = false;
      this.onLoad(this.page, this.query);
    },
    // 行样式
    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,
        };
      }
    },
    // 多选
    selectionChange(val) {
      this.selectionList = val;
    },
    // 批量删除
    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.id);
          });
          remove(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.equipmentId))).map(wlCode => {
        //   return tmp.find(item => item.equipmentId === wlCode);
        // });
        this.maintainList = this.selectionList;
      } else {
        this.maintainList = [];
      }

      this.showMaintain = true;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    searchReset() {
      this.query = {};
      this.treeDeptId = '';
      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();
    },
    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, equipmentMaintenanceVOList = [] } = outerObj;

          if (equipmentMaintenanceVOList.length > 0) {
            equipmentMaintenanceVOList.forEach(innerObj => {
              innerObj.certificateTypeId = innerObj.id;
              result.push({ ...postHandleVO, ...innerObj });
            });
          } else {
            result.push({ ...postHandleVO, certificateTypeId: '' });
          }
        });
        this.data = result;
        this.loading = false;
        this.page.total = res.data.data.total;
      });
    },
  },
};
</script>

<style>
.el-table__row.expired-row,
.el-table .expired-row,
.avue-crud .el-table .expired-row {
  background-color: #fef0f0 !important; /* 浅红色背景 */
  color: #f56c6c !important; /* 红色文字 */
}

.el-table__row.expired-row td,
.el-table .expired-row td,
.avue-crud .el-table .expired-row td {
  background-color: #fef0f0 !important;
  color: #f56c6c !important;
}
</style>
