<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>
    </avue-crud>

    <el-dialog append-to-body title="批量发证" v-model="ccieDialog" width="80%">
      <div style="display: flex; margin-bottom: 10px">
        <el-button plain type="danger" @click="remove">删除选择行</el-button>
        <el-select style="width: 240px; margin: 0 10px" v-model="selectValue" placeholder="请选择">
          <el-option
            v-for="item in ccieOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-date-picker v-model="dateNum" type="date" placeholder="选择日期" />
        <el-button type="primary" style="margin: 0 10px">批量设置</el-button>
        <el-button type="primary">保存</el-button>
      </div>
      <el-table :data="selectionArr">
        <el-table-column type="selection"></el-table-column>
        <el-table-column align="center" label="上岗证日期" prop="wlTime"></el-table-column>
        <el-table-column align="center" label="适航日期" prop="seaTime"></el-table-column>
        <el-table-column align="center" label="宇航日期" prop="astrTime"></el-table-column>
        <el-table-column align="center" label="设备日期" prop="deviceTime"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog append-to-body title="设置有效期" v-model="indateDialog" width="80%">
      <div style="display: flex; margin-bottom: 10px">
        <el-button plain type="danger" @click="remove">删除选择行</el-button>
        <el-select style="width: 240px; margin: 0 10px" v-model="selectValue" placeholder="请选择">
          <el-option
            v-for="item in inDateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-date-picker v-model="dateNum" type="date" placeholder="选择日期" />
        <el-button type="primary" style="margin: 0 10px">批量设置</el-button>
        <el-button type="primary">保存</el-button>
      </div>
      <el-table :data="inDateArr">
        <el-table-column type="selection"></el-table-column>
        <el-table-column align="center" label="上岗证日期" prop="wlTime"></el-table-column>
        <el-table-column
          align="center"
          label="上岗证有效期(年)"
          prop="wlLifespan"
        ></el-table-column>
        <el-table-column align="center" label="适航日期" prop="seaTime"></el-table-column>
        <el-table-column align="center" label="适航有效期(年)" prop="seaLifespan"></el-table-column>
        <el-table-column align="center" label="宇航日期" prop="astrTime"></el-table-column>
        <el-table-column
          align="center"
          label="宇航有效期(年)"
          prop="astrLifespan"
        ></el-table-column>
        <el-table-column align="center" label="设备日期" prop="deviceTime"></el-table-column>
        <el-table-column align="center" label="设备有效期(年)" prop="deviceTime"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog append-to-body title="设置上岗证编号" v-model="setDialog">
      <el-form :model="setForm" :rules="setRules">
        <el-form-item label="编号">
          <el-input placeholder="请输入编号" v-model="setForm.wlCode"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setDialog = false">取 消</el-button>
          <el-button type="primary" @click="setDialog = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog append-to-body title="设备维护" v-model="deviceDialog" width="80%">
      <div style="display: flex; margin-bottom: 10px; align-items: center">
        <div>设备时间：</div>
        <el-date-picker v-model="deviceTime" type="date" placeholder="选择日期" />
        <div style="margin-left: 10px">设备有效期：</div>
        <el-input-number v-model="deviceLifespan" controls-position="right"></el-input-number>
        <el-button type="primary" style="margin: 0 10px" @click="handleSet">批量设置</el-button>
        <el-button type="primary" @click="saveDevice">保存</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="insertDevice()">插入一行</el-button>
        <el-button plain type="danger" @click="remove">删除选择行</el-button>
      </div>
      <el-table :data="deviceData">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="设备编号" prop="deviceCode">
          <template #default="scope">
            <el-select
              v-model="scope.row.deviceCode"
              @change="val => changeDevice(val, scope.$index)"
            >
              <el-option
                v-for="item in deviceList"
                :label="item.value"
                :key="item.value"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="设备名称" prop="deviceName"></el-table-column>
        <el-table-column label="设备时间" prop="deviceTime">
          <template #default="scope">
            <el-date-picker
              style="width: 100%"
              v-model="scope.row.deviceTime"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="设备有效期" prop="deviceLifespan">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.deviceLifespan"
              controls-position="right"
            ></el-input-number>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 证书维护 -->
    <maintain-dialog
      :show-maintain="showMaintain"
      @closeDialog="closeDialog"
      :maintain-list="maintainList"
    ></maintain-dialog>
    <!-- 证书类型维护 -->
    <credential-dialog :show-type="showType" @closeDialog="closeDialog"></credential-dialog>

    <!-- 导入 -->
    <basic-import
      v-if="isShowImport"
      title="导入"
      :isShow="isShowImport"
      templateUrl="/blade-desk/certificateMaintenance/downloadExcelTemplate"
      templateName="上岗台账导入模板.xls"
      importUrl="/blade-desk/certificateMaintenance/importExcel"
      @closeDialog="closeDialog"
    ></basic-import>
  </basic-container>
</template>

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

export default {
  components: {
    maintainDialog,
    credentialDialog,
    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: [],
      deviceList: [
        { label: '设备名称一', value: '1' },
        { label: '设备名称二', value: '2' },
        { label: '设备名称三', value: '3' },
        { label: '设备名称四', value: '4' },
      ],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      ccieOptions: [
        {
          value: 1,
          label: '上岗证日期',
        },
        {
          value: 2,
          label: '适航日期',
        },
        {
          value: 3,
          label: '宇航日期',
        },
        {
          value: 4,
          label: '设备日期',
        },
      ],
      inDateOptions: [
        {
          value: 1,
          label: '上岗证有效期',
        },
        {
          value: 2,
          label: '适航有效期',
        },
        {
          value: 3,
          label: '宇航有效期',
        },
        {
          value: 4,
          label: '设备有效期',
        },
      ],
      selectionList: [],
      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: [] },
      ],
      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,
        searchLabelWidth: 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: 'center',
        gridBtn: false,
        searchMenuPosition: 'right',
        searchShowBtn: false,

        column: [
          {
            label: '姓名',
            prop: 'name',
            span: 24,
            width: 150,
            labelWidth: 140,
            overflow: true,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入姓名',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '所属班组',
            prop: 'deptName',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
          },
          {
            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: 'wlType',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
            type: 'select',
            dicData: [
              {
                label: '一级',
                value: '1',
              },
              {
                label: '二级',
                value: '2',
              },
              {
                label: '三级',
                value: '3',
              },
            ],
          },
          {
            label: '证书编号',
            prop: 'wlCode',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
          },
          {
            label: '从事本岗位或工种时间',
            prop: 'toNewJobDueDate',
            span: 24,
            width: 200,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入从事本岗位或工种时间',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '上岗证日期',
            prop: 'wlTime',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入上岗证日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '上岗证有效期(年)',
            prop: 'wlLifespan',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入上岗证有效期(年)',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '到期日期',
            prop: 'wlDueDate',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入到期日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '适航日期',
            prop: 'seaTime',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入适航日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '适航有效期(年)',
            prop: 'seaLifespan',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入适航有效期(年)',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '适航到期日期',
            prop: 'seaDueDate',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入到期日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '宇航日期',
            prop: 'astrTime',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入宇航日期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '宇航有效期',
            prop: 'astrLifespan',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入宇航有效期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '宇航到期日期',
            prop: 'astrdueDate',
            span: 24,
            width: 150,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: '请输入到期日期',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '状态',
            prop: 'wlStatusTitle',
            type: 'select',
            span: 24,
            width: 150,
            overflow: true,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入状态',
                trigger: 'blur',
              },
            ],
            dicData: [
              {
                value: 1,
                label: '正常',
              },
              {
                value: 2,
                label: '过期',
              },
              {
                value: 3,
                label: '离职',
              },
            ],
          },
        ],
      },
    };
  },
  mounted() {
    this.rowSort();
    this.rowCalc();
  },
  methods: {
    rowClassName: ({ row, rowIndex }) => {
      console.log('rowClassName执行了', rowIndex); // 先确认是否打印
      // 检查各种证书是否过期
      const now = new Date();
      let isExpired = false;

      // 检查上岗证是否过期
      if (row.wlDueDate) {
        const wlDueDate = new Date(row.wlDueDate);
        if (wlDueDate < now) {
          isExpired = true;
          console.log(`行 ${rowIndex}: 上岗证已过期`, row.wlDueDate);
        }
      }

      // 检查适航证是否过期
      if (row.seaDueDate) {
        const seaDueDate = new Date(row.seaDueDate);
        if (seaDueDate < now) {
          isExpired = true;
          console.log(`行 ${rowIndex}: 适航证已过期`, row.seaDueDate);
        }
      }

      // 检查宇航证是否过期
      if (row.astrdueDate) {
        const astrDueDate = new Date(row.astrdueDate);
        console.log('astrDueDate', astrDueDate);
        console.log('now', new Date(row.astrdueDate));
        if (astrDueDate < now) {
          isExpired = true;
          console.log(`行 ${rowIndex}: 宇航证已过期`, row.astrdueDate);
        }
      }

      // 检查设备证是否过期
      if (row.deviceDueDate) {
        const deviceDueDate = new Date(row.deviceDueDate);
        if (deviceDueDate < now) {
          isExpired = true;
          console.log(`行 ${rowIndex}: 设备证已过期`, row.deviceDueDate);
        }
      }
      // 如果状态本身就是过期，或者任何证书已过期，则应用过期样式
      if (isExpired || row.wlStatusTitle === '过期') {
        console.log(1);
        console.log(`行 ${rowIndex}: 应用过期样式`, row.userName, row.wlStatusTitle);
        return 'expired-row';
      }
      return '';
    },
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true;
    },
    changeDevice(val, index) {
      let tmp = this.deviceList.find(item => item.value == val);
      this.deviceData[index].deviceName = tmp.label;
    },
    rowCalc() {
      this.spanArr.forEach((ele, index) => {
        let parent;
        if (index !== 0) parent = this.spanArr[ele.parent || index - 1].span;
        ele.span = this.rowSpan(ele.prop, parent);
      });
    },
    rowSort(list) {
      let propList = this.spanArr.map(ele => ele.prop);
      this.spanArr.forEach((ele, index) => {
        let key = ele.prop;
        this.data = this.data.sort((a, b) => {
          let flag = true;
          for (let i = 0; i < index; i++) {
            let prop = this.spanArr[i].prop;
            flag = flag && a[prop] == b[prop];
          }
          if (flag) {
            if (a[key] < b[key]) {
              return 1;
            } else if (a[key] > b[key]) {
              return -1;
            }
            return 0;
          }
          return 0;
        });
      });
    },
    // 关闭弹窗
    closeDialog() {
      this.showMaintain = false;
      this.showType = false;
      this.onLoad(this.query);
    },
    handleSet() {
      if (this.deviceTime !== '') {
        this.deviceData.map(item => {
          item.deviceTime = this.deviceTime;
        });
      }
      if (this.deviceLifespan !== '') {
        this.deviceData.map(item => {
          item.deviceLifespan = this.deviceLifespan;
        });
      }
    },
    saveDevice() {
      this.deviceDialog = false;
    },

    rowSpan(key, parent) {
      let list = [];
      let position = 0;
      this.data.forEach((item, index) => {
        if (index === 0) {
          list.push(1);
          let position = 0;
        } else {
          if (this.data[index][key] === this.data[index - 1][key]) {
            if (parent && parent[index] !== 0) {
              list.push(1);
              position = index;
            } else {
              list[position] += 1;
              list.push(0);
            }
          } else {
            list.push(1);
            position = index;
          }
        }
      });
      return list;
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      for (let i = 0; i < this.spanArr.length; i++) {
        const ele = this.spanArr[i];
        if (column.property == ele.prop) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col,
          };
        } else if (columnIndex == 0) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col,
          };
        } else if (columnIndex == 25) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col,
          };
        }
      }
    },
    setCode() {
      this.setDialog = true;
    },
    insertDevice() {
      const record = { _select: false };
      this.deviceData.push(record);
    },
    setDevice(row) {
      let tmpArr = this.data.filter(item => item.userName == row.userName);
      this.deviceData = [];
      if (tmpArr.length > 0) {
        tmpArr.map(item => {
          item._select = false;
        });
      }
      this.deviceData = tmpArr;
      this.deviceDialog = true;
    },
    // 批量发证
    handleCertificate() {
      this.ccieDialog = true;
    },
    // 有效期
    handleIndate() {
      this.indateDialog = true;
    },
    // 多选
    selectionChange(val) {
      this.selectionList = val;
    },
    // 批量删除
    handleDeletes() {
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据');
      } else {
      }
    },
    handleMaintain() {
      if (this.selectionList.length == 0) {
        this.$message.error('请先选择数据');
      } else {
        let tmp = this.data.filter(item1 =>
          this.selectionList.some(item2 => item2.userName === item1.userName)
        );
        let tmp1 = Array.from(new Set(tmp.map(item => item.wlCode))).map(wlCode => {
          return tmp.find(item => item.wlCode === wlCode);
        });
        this.maintainList = tmp1;
        this.showMaintain = true;
      }
    },
    handleType() {
      this.showType = true;
    },
    // 导入
    handleImport() {},
    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);
    },
    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, certificateMaintenanceVOList = [] } = outerObj;
          certificateMaintenanceVOList.forEach(innerObj => {
            result.push({ ...postHandleVO, ...innerObj });
          });
        });
        this.data = result;
console.log(9999,this.data)
        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>
