<template>
  <div>
    <a-card class="mb-2 mr-2" id="search-card">
      <a-form class="formLabel" layout='vertical'>
        <a-row :gutter='24'>
          <!-- 问题编号 -->
          <a-col :xl='6' :lg='8' :md='12' :sm='24' :xs='24'>
            <a-form-item :label="$t('report.history-problem-issue-code')">
              <a-input allowClear v-model='formData.issueNo' :placeholder="$t('report.history-problem-please-enter-the-issue-code')"/>
            </a-form-item>
          </a-col>
          <!-- 问题标题 -->
          <a-col :xl='6' :lg='8' :md='12' :sm='24' :xs='24'>
            <a-form-item :label="$t('report.history-problem-issue-title')">
              <a-input allowClear v-model='formData.issueTitle' :placeholder="$t('report.history-problem-please-enter-the-issue-title')"/>
            </a-form-item>
          </a-col>
          <!-- 项目名称 -->
          <a-col :xl='6' :lg='8' :md='12' :sm='24' :xs='24'>
            <a-form-item :label="$t('report.history-problem-project-name')">
              <a-select
                  showSearch
                  allowClear
                  v-model='formData.projectId'
                  @search="getProjectInfo"
                  @change="projectChange"
                  :placeholder="$t('report.history-problem-please-select-the-project')">
                <a-select-option v-for='item in projectList' :key='item.projectId' :value='item.projectId'>
                  {{ item.projectName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 产品名称 -->
          <a-col :xl='6' :lg='8' :md='12' :sm='24' :xs='24'>
            <a-form-item :label="$t('report.history-problem-product-name')">
              <a-input allowClear v-model='formData.productName' :placeholder="$t('report.history-problem-please-enter-the-product-name')"/>
            </a-form-item>
          </a-col>
          <span v-if='advanceExpand'>
            <!-- 结构代码 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('research.structure-code')">
                <a-input allowClear v-model='formData.svpps' :placeholder="$t('research.please-enter-structure-code')"/>
              </a-form-item>
            </a-col>
            <!-- 失效零件名称 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-part-name')">
                <a-input allowClear v-model='formData.partName' :placeholder="$t('report.history-problem-please-enter-the-part-name')"/>
              </a-form-item>
            </a-col>
            <!-- 失效零件代码 -->
             <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-part-code')">
                <a-input allowClear v-model='formData.partNumber' :placeholder="$t('report.history-problem-please-enter-the-part-code')"/>
              </a-form-item>
            </a-col>
            <!-- 问题种类 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-type')">
                <a-input allowClear v-model='formData.problemType' :placeholder="$t('report.history-problem-please-enter-issue-type')" />
              </a-form-item>
            </a-col>
            <!-- 发生时间 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-occur-time')">
                <a-range-picker @change='onOccurChange' :value='occurTime' class="range-picker-class"/>
              </a-form-item>
            </a-col>
            <!-- 问题来源 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-source')">
                <a-input allowClear v-model='formData.issueSource' :placeholder="$t('report.history-problem-please-enter-issue-source')"/>
              </a-form-item>
            </a-col>
            <!-- 问题等级 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-level')">
                <a-input allowClear v-model='formData.issueLevel' :placeholder="$t('report.history-problem-please-enter-issue-level')"/>
              </a-form-item>
            </a-col>
            <!-- 失效分类 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-fault-type')">
                <a-input allowClear v-model='formData.failureType' :placeholder="$t('report.history-problem-please-enter-fault-type')"/>
              </a-form-item>
            </a-col>
            <!-- 责任人 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('research.responsible')">
                <a-input allowClear v-model='formData.owner'
                         :placeholder="$t('research.please-enter-responsible')" />
              </a-form-item>
            </a-col>
            <!-- 责任部门 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.history-problem-duty-department')">
                <a-tree-select
                    show-search
                    v-model="formData.departmentId"
                    :tree-data="deptTreeData"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :placeholder="$t('report.history-problem-please-select-duty-department')"
                    treeDataSimpleMode
                    allow-clear
                    treeDefaultExpandAll
                    :filterTreeNode="handleDeptFilterTreeNode"
                    :loadData="handleDeptLoadData"
                />
              </a-form-item>
            </a-col>
            <!-- 关闭时间 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('report.closing-time')">
                <a-range-picker @change='onCloseChange' :value='closeDate' class="range-picker-class" />
              </a-form-item>
            </a-col>
            <!-- 分析情况 -->
            <a-col :xl='advanceExpand ? 6 : 18' :lg='8' :md='12' :sm='24' :xs='24'>
              <a-form-item :label="$t('fmea.experience.and.lesson.export.title.relationState')">
                <a-select allowClear v-model='formData.relationFault'
                          :placeholder="$t('fmea.experience.and.lesson.export.title.please-select-relationState')">
                  <a-select-option v-for='(item, index) in stateList' :key='index' :value='item.value'>
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </span>
          <a-col :xl='24' :lg='24' :md='24' :sm='24' :xs='24'>
            <a-form-item class="fr" :label="'\xa0'">
              <a @click="toggleAdvance" class="mr10">
                {{ advanceExpand ? $t("global.collapse") : $t("global.expand") }}
                <a-icon :type="advanceExpand ? 'up' : 'down'" />
              </a>
              <a-button class='mr10' @click='reset'>
                {{ $t('global-btn.reset') }}
              </a-button>
              <a-button type='primary' @click='handleSearch'>
                {{ $t('global-btn.search') }}
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card class="mb-2 mr-2" id="grid-card">
      <template slot="title">
        <a-button class="mt10 mb10" @click="addPQCP" type="primary">
          {{ $t("global-btn.add") }}
        </a-button>
        <a-button class="mt10 mb10 ml10" type="primary" @click="exportExcel">
          {{ $t("global-btn.export") }}
        </a-button>
      </template>
      <template slot="extra">
        <a-dropdown>
          <a-menu slot="overlay">
            <draggable v-model="sortedColumns" handle=".drag-handle" filter=".cant-handle" :move="onMove"
                       class="m-2 mr-1" tag="div" animation="500">
              <a-menu-item v-for="column in sortedColumns" :key="column.dataIndex" :disabled='true'
                           class="custom-menu-item mb-1" :class="column.cantHandle ? 'cant-handle' : ''">
                <div class="drag-handle" @mousedown="startDrag = true" @mouseup="startDrag = false"
                     @mouseleave="startDrag = false">
                  <i class="icon iconfont iconshangxiayidong-"></i>
                </div>
                <a-checkbox v-model="editColumnVisibilities[column.dataIndex]" :disabled="column.cantHide"
                            @change="handleCheckboxChange(column.dataIndex, $event.target.checked)">
                  {{ column.title }}
                </a-checkbox>
              </a-menu-item>
            </draggable>
            <a-menu-item class="dropdown-footer" :disabled='true'>
              <a-button size="small" class="mr-2" @click='handleCheckBoxReset'>{{
                  $t('global-btn.reset')
                }}
              </a-button>
              <a-button type="primary" size="small" @click="handleSaveTableConfig">{{
                  $t('plan.change-record.save')
                }}
              </a-button>
            </a-menu-item>
          </a-menu>
          <a-button icon="setting" type="link" :title="($t('global-constant.setting.col'))"></a-button>
        </a-dropdown>
      </template>

      <a-table
        id="experience-table"
        ref='tableRef'
        size="small"
        bordered
        :components='components'
        :columns='sortedColumns.filter(column => column.visible)'
        :dataSource='tableData'
        :rowKey='(record, index) => { return index; }'
        :scroll='{ x: scrollWidth, y: tableHeightValue }'
        :pagination='pagination' :loading='tableLoading'
        @change='handlePageChange'>
        <template slot='relationFault' slot-scope='text,row'>
          <span>
             {{
              row.relationFault === 0
                  ? $t('research.not-apply')
                  : row.relationFault === 1
                      ? $t('research.to-be-associated')
                      : row.relationFault === 2
                          ? $t('research.associated')
                          : '-'
            }}
          </span>
        </template>

        <template v-slot:action="text, record">
          <a class="mr-1 operate-btn" :key='record.id' @click='viewCase(record)'>
            <!-- 查看 -->
            <a-tooltip :title="$t('research.association-failure')">
              <i class='iconfont iconchakan'></i>
            </a-tooltip>
          </a>
          <!-- 删除 -->
          <a class="mr-1 operate-btn" @click="delFail(record)">
            <a-tooltip :title="$t('global-btn.delete')">
              <i class="iconfont iconshanchu"></i>
            </a-tooltip>
          </a>
        </template>
        <!-- 序号列 -->
        <template slot='index' slot-scope='text, record, index'>
          <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
        </template>
        <!-- 是否适用 -->
        <template slot="isApply" slot-scope="text, row">
          <a-select v-model="row.isApply"  @change="applyChange(row)">
            <a-select-option :value="1">
              {{ $t("global-dict.apply") }}
            </a-select-option>
            <a-select-option :value="0">
              {{ $t("global-dict.not-apply") }}
            </a-select-option>
          </a-select>
        </template>
        <!-- 不适用原因 -->
        <template slot="notApplyReason" slot-scope="text, row">
          <!-- 适用 -->
          <span v-if="row.isApply === 1 && !row.isEdit">{{ $t('research.no-explanation-needed') }}</span>
          <!-- 不适用 -->
          <span v-show="row.isApply === 0 && !row.isEdit" @click="notApplyClick(row)">
            {{ row.notApplyReason || $t('research.please-describe-not-apply-reason') }}
          </span>
          <!-- 输入框 -->
          <a-input
            :id="row.id"
            v-model="row.notApplyReason"
            v-show="row.isApply === 0 && row.isEdit"
            @blur="notApplyInputBlur(row)"
            :maxLength="500"/>
        </template>
      </a-table>
    </a-card>
    <!-- 导出 -->
    <a-modal
      :title="$t('global-btn.export')"
      :visible='exportVisible'
      :width="400"
      :maskClosable="false"
      @cancel="closeExportModal"
      @ok="exportFile"
      :okText="$t('global-btn.export')">
      <div>
        <h3>{{$t('global-btn.please-select-export-type')}}</h3>
        <a-radio-group v-model="exportType">
          <a-radio value="1" class="mr-4">{{$t('global-btn.export-by-the-selected-columns')}}</a-radio>
          <a-radio value="0">{{$t('global-btn.export-default-table-columns')}}</a-radio>
        </a-radio-group>
      </div>
    </a-modal>
    <!-- 点击，从历史失效案例库添加 -->
    <a-modal v-model="visiblePQCPModel" :width="widthValue" @afterClose="closeModal" :destroyOnClose="true"
             :maskClosable="false" :footer="null" :dialog-style="topValue" :body-style="bodyStyle">
      <template slot="title">
        <span>{{ this.modalTitle }}</span>
        <!-- 全屏 -->
        <a-icon v-if="!fullScreenFlag" type="fullscreen" class="fullScreen" @click="changeFullScreen" />
        <!-- 取消全屏 -->
        <a-icon v-if="fullScreenFlag" type="fullscreen-exit" class="fullScreen" @click="changeFullScreen" />
      </template>
      <HistoryfailAdd @closeModal="closeModal" ref="HistoryfailAdd" />
    </a-modal>
    <!-- 查看关联失效 -->
    <viewAnalyse ref='look' @initData="initData"/>
  </div>
</template>
<script>
import HistoryfailAdd from "./components/HistoryfailAdd";
import VueDraggableResizable from 'vue-draggable-resizable';
import draggable from 'vuedraggable';
import { checkHotTableLength } from "@/utils/validate";
import viewAnalyse from './components/analyse.vue'

export default {
  props: {
    fmeaId: {
      type: String | Number,
      default: ""
    },
  },
  components: {
    VueDraggableResizable,
    HistoryfailAdd,
    viewAnalyse,
    draggable
  },
  data() {
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props;
          // 此处的this.sortedColumns 是定义的table的表头属性变量
          const col = this.sortedColumns.find((col) => {
            const k = col.dataIndex || col.key;
            return k === key;
          });
          if (!col || !col.width) {
            return h('th', { ...restProps }, [...children]);
          }
          const dragProps = {
            key: col.dataIndex || col.key,
            class: 'table-draggable-handle',
            attrs: {
              w: 10,
              x: col.width,
              z: 1,
              axis: 'x',
              draggable: true,
              resizable: false
            },
            on: {
              dragging: (x, y) => {
                col.width = Math.max(x, 100);
              }
            }
          };
          const drag = h('vue-draggable-resizable', { ...dragProps });
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
        }
      }
    };
    return {
      // 导出弹框
      exportVisible: false,
      // 导出类型
      exportType: '1',
      // 表格id
      tableId: '',
      // 表格总宽度
      scrollWidth: 0,
      advanceExpand: false,
      userFetching: false,
      // 复选框控制的状态
      columnVisibilities: {
        serialNumber: true,
        issueNo: true,
        issueTitle: true,
        projectName: true,
        productName: true,
        svpps: true,
        partName: true,
        partNumber: true, // 零件编号
        problemType: true, // 问题种类
        occurTime: true, // 发生时间
        issueSource: true, // 问题来源
        issueLevel: true, // 问题等级
        failureType: true, // 失效类型
        responsible: true, // 责任人
        responsibleDepartment: true, // 部门ID
        closeDate: true, // 关闭时间结束
        isApply: true,
        notApplyReason: true,
        relationFault: true, // 分析情况
        action: true,
      },
      startDrag: false,
      editColumnVisibilities: [],
      sortedColumns: [], // 用于拖拽的列数组
      formData: {
        issueNo: undefined, // 问题编号
        issueTitle: undefined, // 问题标题
        projectId: undefined, // 项目ID
        productName: undefined, // 产品名称
        svpps: undefined, // 结构代码
        partName: undefined, // 零件名称
        partNumber: undefined, // 零件编号
        problemType: undefined, // 问题种类
        startOccurTime: undefined, // 发生时间开始
        endOccurTime: undefined, // 发生时间结束
        issueSource: undefined, // 问题来源
        issueLevel: undefined, // 问题等级
        failureType: undefined, // 失效类型
        owner: undefined, // 责任人
        departmentId: undefined, // 部门ID
        startCloseDate: undefined, // 关闭时间开始
        endCloseDate: undefined, // 关闭时间结束
        relationFault: undefined // 分析情况
      },
      /**全屏标识 */
      fullScreenFlag: false,
      /**弹窗宽度 */
      widthValue: 1000,
      /**弹窗高度位置 */
      topValue: {},
      /**弹窗样式 */
      bodyStyle: {},
      modalTitle: "",
      // 部门数据
      deptTreeData: [],
      // 项目列表
      projectList: [],
      //分析情况
      stateList: [
        {
          name: this.$t('research.not-apply'),
          value: '0',
        },
        {
          name: this.$t('research.to-be-associated'),
          value: '1'
        },
        {
          name: this.$t('research.associated'),
          value: '2'
        }
      ],
      failExpId: 0,
      // 表头
      tableColumns: [
        // 序号
        {
          title: 'fmea.experience.and.lesson.export.title.serialNumber',
          width: 100,
          fixed: 'left',
          align: 'center',
          dataIndex: 'serialNumber',
          visible: true,
          cantHide: true,
          cantHandle: true,
          scopedSlots: {
            customRender: 'index',
          },
          ellipsis: true,
        },
        // 问题编号
        {
          title: 'fmea.experience.and.lesson.export.title.questionNumber',
          dataIndex: 'issueNo',
          visible: true,
          cantHide: true,
          cantHandle: true,
          fixed: 'left',
          align: 'center',
          width: 200,
          ellipsis: true,
        },
        // 问题标题
        {
          title: 'fmea.experience.and.lesson.export.title.questionHeading',
          dataIndex: 'issueTitle',
          align: 'center',
          visible: true,
          width: 300,
          ellipsis: true,
        },
        // 项目名称
        {
          title: 'fmea.experience.and.lesson.export.title.projectName',
          dataIndex: 'projectName',
          width: 150,
          visible: true,
          align: 'center',
          ellipsis: true,
        },
        // 产品名称
        {
          title: 'fmea.experience.and.lesson.export.title.productName',
          dataIndex: 'productName',
          align: 'center',
          visible: true,
          width: 150,
          ellipsis: true,
        },
        // 结构代码
        {
          title: 'fmea.experience.and.lesson.export.title.structuralCode',
          dataIndex: 'svpps',
          align: 'center',
          visible: true,
          width: 150,
          ellipsis: true,
        },
        // 失效零件名称
        {
          title: 'fmea.experience.and.lesson.export.title.failedPartName',
          dataIndex: 'partName',
          align: 'center',
          visible: true,
          width: 150,
          ellipsis: true,
        },
        // 失效零件代码
        {
          title: 'fmea.experience.and.lesson.export.title.failedPartCode',
          dataIndex: 'partNumber',
          align: 'center',
          visible: true,
          width: 150,
          ellipsis: true,
        },
        // 问题种类
        {
          title: 'fmea.experience.and.lesson.export.title.problemType',
          dataIndex: 'problemType',
          align: 'center',
          visible: true,
          width: 150,
          ellipsis: true,
        },
        // 发生时间
        {
          title: 'fmea.experience.and.lesson.export.title.sendingTime',
          dataIndex: 'occurTime',
          align: 'center',
          visible: true,
          width: 150,
          ellipsis: true,
        },
        // 问题来源
        {
          title: 'fmea.experience.and.lesson.export.title.problemSource',
          dataIndex: 'issueSource',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 问题等级
        {
          title: 'fmea.experience.and.lesson.export.title.problemLevel',
          dataIndex: 'issueLevel',
          width: 150,
          visible: true,
          align: 'center',
          ellipsis: true,
        },
        // 失效分类
        {
          title: 'fmea.experience.and.lesson.export.title.failureType',
          dataIndex: 'failureType',
          width: 150,
          align: 'center',
          visible: true,
          ellipsis: true,
        },
        // 责任人
        {
          title: 'fmea.experience.and.lesson.export.title.personInCharge',
          dataIndex: 'responsible',
          width: 150,
          align: 'center',
          visible: true,
          ellipsis: true,
        },
        // 责任部门
        {
          title: 'fmea.experience.and.lesson.export.title.responsibleDepartment',
          dataIndex: 'responsibleDepartment',
          width: 150,
          align: 'center',
          visible: true,
          ellipsis: true,
        },
        // 关闭时间
        {
          title: 'fmea.experience.and.lesson.export.title.closingTime',
          dataIndex: 'closeDate',
          width: 150,
          align: 'center',
          visible: true,
          ellipsis: true,
        },
        // 是否适用
        {
          title: "fmea.experience.and.lesson.export.title.isApply",
          width: 150,
          align: "center",
          visible: true,
          dataIndex: "isApply",
          scopedSlots: {
            customRender: "isApply"
          },
          ellipsis: true
        },
        // 不适用原因
        {
          title: "fmea.experience.and.lesson.export.title.reasonNotApplicable",
          width: 200,
          align: "center",
          visible: true,
          dataIndex: "notApplyReason",
          scopedSlots: {
            customRender: "notApplyReason"
          },
          ellipsis: true
        },
        // 关联状态
        {
          title: 'fmea.experience.and.lesson.export.title.relationState',
          dataIndex: 'relationFault',
          width: 150,
          align: 'center',
          visible: true,
          scopedSlots: {
            customRender: 'relationFault',
          },
          ellipsis: true,
        },
        // 操作
        {
          title: 'research.operate',
          dataIndex: 'action',
          visible: true,
          cantHide: true,
          cantHandle: true,
          fixed: 'right',
          align: 'center',
          width: 100,
          scopedSlots: {
            customRender: 'action',
          },
          ellipsis: true,
        },
      ],
      /** 表格Loading */
      tableLoading: false,
      tableData: [],
      // 发生时间
      occurTime: [null, null],
      // 关闭时间
      closeDate: [null, null],
      // 查看弹窗标识
      showViewDrawer: false,
      currentCase: null,
      // 添加弹窗
      visiblePQCPModel: false,
      // 分页
      pagination: {
        // defaultPageSize: 10,
        current: 1,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total => this.$t('functional-analysis.a-total-of-data', {total: `${total}`}), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100', '200'], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        total: 0, //总条数
        showQuickJumper: true,
      },
      pageNo: 1,
      pageSize: 10,
      departmentName: '',
      owner: '',
      // 按钮权限显示
      searchBtnFlag: false,
      queryBtnFlag: false,
      verifyBtnFlag: false,
      tempFormData: {},
      tableHeight: 0,
      tableHeightValue: 0
    };
  },
  watch: {
    sortedColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格滚动区域的总宽度
          let scrollX = $('.ant-table-fixed').width();
          // 获取表格的总宽度
          let tableWidth = $('.ant-table-body').width();
          // a-table的scrollX宽度需要减去固定列宽度
          this.scrollWidth = scrollX - 260;
          if (scrollX <= tableWidth) {
            this.cancelFixedColmuns();
          } else {
            this.reloadFixedColmuns([0, 1], [this.sortedColumns.length - 1]);
          }
        });
      },
      deep: true,
      immediate: true
    },
    advanceExpand: {
      handler() {
        this.$nextTick(() => {
          this.handleResize();
        });
      }
    }
  },
  methods: {
    addPQCP() {
      this.visiblePQCPModel = true;
      this.modalTitle = this.$t(
          "workbench.add-historical-lessons"
      );
    },
    /**
     * 初始化加载已保存的表格列顺序及显隐
     */
    async initTableColumns() {
      // 获取用户信息，如果当前组件的userInfo为空，则从localStorage中获取
      let userInfo = JSON.parse(localStorage.getItem("userInfo"));
      // 获取页面中所有的表格容器
      let tableWrappers = document.querySelectorAll('.ant-table-wrapper');
      // 提取表格容器的id，并转换为数组
      let tableIds = Array.from(tableWrappers).map(item => item.id);
      try {
        // 调用接口获取表格列数据
        let res = await this.$api.getTableColumnsData({
          userId: userInfo.userId,
          pagePath: this.$route.path,
          pageName: this.$route.name,
          tableIds: tableIds
        });
        // 如果接口返回成功
        if (res.flag) {
          // 如果返回的数据中包含当前表格的配置映射，并且映射中有数据
          if (res.data.currentTableConfigMap && Object.keys(res.data.currentTableConfigMap).length > 0) {
            // 获取当前表格的配置信息
            let tableConfig = res.data.currentTableConfigMap['experience-table'];
            // 如果表格配置存在
            if (tableConfig) {
              // 解析表格列数据 将从数据库中获取的表格title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns
              let oldColumns = JSON.parse(tableConfig.tableColumns);
              oldColumns.forEach((column) => {
                // 处理表格列的title
                column.title = this.$t(column.title);
              });
              this.sortedColumns = [...oldColumns];
              // 解析表格列显示状态
              this.editColumnVisibilities = JSON.parse(tableConfig.tableVisibilities);
            } else {
              // 如果没有表格配置，则使用默认的表格列和显示状态
              // 处理表格列的title 将默认表格配置数据中的title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns 避免污染tableColumns默认数据
              let newTableColumns = [];
              this.tableColumns.forEach((column) => {
                let newColumn = { ...column };
                newColumn.title = this.$t(column.title);
                newTableColumns.push(newColumn);
              });
              this.sortedColumns = [...newTableColumns];
              this.editColumnVisibilities = { ...this.columnVisibilities };
            }
          } else {
            // 如果没有表格配置，则使用默认的表格列和显示状态
            // 处理表格列的title 将默认表格配置数据中的title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns 避免污染tableColumns默认数据
            let newTableColumns = [];
            this.tableColumns.forEach((column) => {
              let newColumn = { ...column };
              newColumn.title = this.$t(column.title);
              newTableColumns.push(newColumn);
            });
            this.sortedColumns = [...newTableColumns];
            this.editColumnVisibilities = { ...this.columnVisibilities };
          }
          // 如果接口返回失败
        } else {
          console.error('Failed to retrieve table column data.');
        }
      } catch (error) {
        // 捕获异常，并输出错误信息
        console.error('Error occurred while fetching table columns:', error);
      }
    },
    /**
     * 移动事件处理函数
     *
     * @param event 事件对象
     * @returns 如果当前元素不包含禁止移动属性则返回true，否则返回false
     */
    onMove(event) {
      // 禁止移动到包含禁止移动元素的行
      return !event.relatedContext.element.cantHandle;
    },
    /**
     * 保存表格配置信息
     */
    handleSaveTableConfig() {
      // 创建一个对象用于保存需要保存的配置数据
      // 将sortedColumns中的title替换为tableColumns中的title
      let newSortedColumns = [];
      this.sortedColumns.forEach(column => {
        let newColumn = { ...column };
        if (this.tableColumns.find(item => item.dataIndex === column.dataIndex)) {
          let item = this.tableColumns.find(item => item.dataIndex === column.dataIndex);
          newColumn.title = item.title;
        }
        newSortedColumns.push(newColumn);
      });
      let data = {
        pagePath: this.$route.path,
        pageName: this.$route.name,
        // 表格列信息，转为JSON字符串
        tableColumns: JSON.stringify(newSortedColumns),
        // 表格列可见性信息，转为JSON字符串
        tableVisibilities: JSON.stringify(this.editColumnVisibilities),
        // 表格id
        tableId: 'experience-table'
      };
      // 调用API保存表格配置
      this.$api.saveTableConfig(data).then(res => {
        // 如果返回结果中的flag为true，表示保存成功
        if (res.flag) {
          // 显示成功提示信息
          this.$message.success(res.message, 1);
          // 重新初始化数据
          this.initData();
        } else {
          // 显示错误提示信息
          this.$message.error(res.message, 1);
        }
      }).finally(() => {
        // 重新初始化数据
        this.initData();
      });
    },
    /**
     * 处理表格列显隐复选框变化事件
     *
     * @param key 列的唯一标识符
     * @param checked 列的显示状态，true表示显示，false表示隐藏
     */
    handleCheckboxChange(key, checked) {
      // 更新全局的columnVisibilities对象
      this.$set(this.editColumnVisibilities, key, checked);
      // 更新列配置中的visible属性（如果需要的话）
      this.sortedColumns.forEach(column => {
        if (column.dataIndex === key) {
          column.visible = checked;
        }
      });
    },
    /**
     * 重置表格列显示隐藏
     */
    handleCheckBoxReset() {
      this.editColumnVisibilities = { ...this.columnVisibilities };
      // 重置时，将默认表格配置数据中的title通过$t方法翻译后存储到新的数组中 再将其赋值给sortedColumns 避免污染tableColumns默认数据
      let resetColumns = [];
      this.tableColumns.forEach(column => {
        let newColumn = { ...column };
        newColumn.title = this.$t(column.title);
        resetColumns.push(newColumn);
      });
      this.sortedColumns = [...resetColumns];
      this.sortedColumns.forEach(column => {
        this.$set(column, 'visible', true);
      });
    },
    /**
     * 取消固定列
     *
     * @returns 无返回值
     */
    cancelFixedColmuns() {
      // 遍历已排序的列
      this.sortedColumns.forEach((column) => {
        // 如果列的固定属性为true
        if (column.fixed) {
          // 将列的固定属性设置为false
          column.fixed = false;
        }
      });
    },
    /**
     * 重新设置固定列的固定状态
     *
     * @param fixedLeftColumns 左侧固定列名数组
     * @param fixedRightColumns 右侧固定列名数组
     */
    reloadFixedColmuns(fixedLeftColumns, fixedRightColumns) {
      fixedLeftColumns.forEach((column) => {
        if (this.sortedColumns[column]) {
          this.sortedColumns[column].fixed = 'left';
        }
      });
      fixedRightColumns.forEach((column) => {
        if (this.sortedColumns[column]) {
          this.sortedColumns[column].fixed = 'right';
        }
      });
    },
    /**
     * 处理窗口大小调整事件
     *
     * @returns 无返回值
     */
    handleResize() {
      // 获取窗口宽度
      const width = window.innerWidth;
      // 获取窗口高度
      const height = Math.max(window.innerHeight, 0);
      // 获取用户信息容器的高度
      let searchCardHeight = $("#search-card").height();
      // 系统内菜单栏、标签栏的高度恒定为64 + 40 = 104，其他页边距需根据每个页面布局自行计算
      $("#grid-card").height(height - 104 - searchCardHeight - 40);
      this.tableHeightValue = height - 104 - searchCardHeight - 240;
      this.scrollWidth = this.$refs.tableRef?.$el.offsetWidth;
      // 获取表格滚动区域的总宽度
      let scrollX = $('.ant-table-fixed').width() - 260;
      // 获取表格的总宽度
      let tableWidth = $('.ant-table-body').width();
      // 超过2K屏时取消固定列
      if (width > 2560 || scrollX <= tableWidth) {
        this.cancelFixedColmuns();
      } else {
				this.reloadFixedColmuns([0, 1], [this.sortedColumns.length - 1]);
      }
    },
    // 部门筛选
    handleDeptFilterTreeNode(inputValue, treeNode) {
      return treeNode.data.props.title.includes(inputValue);
    },
    // 部门异步加载
    handleDeptLoadData(treeNode) {
      // 返回一个Promise对象
      return new Promise(resolve => {
        // 获取当前节点的id
        let id = treeNode ? treeNode.dataRef.id : 0;
        // 如果id为0，表示加载根节点数据，清空部门树数据
        if (id === 0) {
          this.deptTreeData = [];
        }
        // 调用API获取部门树数据
        this.$api.getSysOrgTreeByOrgId(id).then(res => {
          // 如果API请求成功
          if (res.flag) {
            // 将返回的数据转换为树形结构，并拼接到deptTreeData中
            this.deptTreeData = this.deptTreeData.concat((res.data || []).map(org => {
              return {
                // 设置节点的id
                id: org.orgId,
                // 设置节点的父节点id
                pId: id,
                // 设置节点的值
                value: org.orgId,
                // 设置节点的标题
                title: org.orgName,
                // 判断节点是否为叶子节点（是否有子节点）
                isLeaf: !org?.children
              };
            }));
          }
          // 异步操作完成，调用resolve函数
          resolve();
        });
      });
    },
    // 获取项目信息
    getProjectInfo(projectName) {
      let data = {
        projectName: projectName
      };
      // 调用 API 获取 FMEA 项目编号列表
      this.$api.getFMEAProjectNoList(data).then(res => {
        // 判断 API 返回的标志位是否为 false
        if (!res.flag) {
          // 如果标志位为 false，则显示错误通知
          this.$notification.error({ message: res.message });
        }
        // 将 API 返回的数据赋值给 projectList，如果返回的数据为空则赋值为空数组
        this.projectList = res.data || [];
      });
    },
    // 项目变更函数
    projectChange(value) {
      this.formData.projectId = value;
    },
    // 发生时间
    onOccurChange(date, dateString) {
      // 设置发生时间
      this.occurTime = date;
      // 设置表单数据的起始发生时间为日期字符串的第一个元素
      this.formData.startOccurTime = dateString[0];
      // 设置表单数据的结束发生时间为日期字符串的第二个元素
      this.formData.endOccurTime = dateString[1];
    },
    // 关闭时间
    onCloseChange(date, dateString) {
      // 设置关闭日期
      this.closeDate = date;
      // 设置表单数据的起始关闭日期为日期字符串的第一个元素
      this.formData.startCloseDate = dateString[0];
      // 设置表单数据的结束关闭日期为日期字符串的第二个元素
      this.formData.endCloseDate = dateString[1];
    },

    // 搜索表单
    handleSearch() {
      this.pageNo = 1;
      this.pagination.current = 1;
      this.tempFormData = { ...this.formData };
      this.initData();
    },

    // 重置
    reset() {
      this.pageNo = 1;
      this.pagination.current = 1;
      this.formData = {
        issueNo: undefined, // 问题编号
        issueTitle: undefined, // 问题标题
        projectId: undefined, // 项目ID
        productName: undefined, // 产品名称
        svpps: undefined, // 结构代码
        partName: undefined, // 零件名称
        partNumber: undefined, // 零件编号
        problemType: undefined, // 问题种类
        startOccurTime: undefined, // 发生时间开始
        endOccurTime: undefined, // 发生时间结束
        issueSource: undefined, // 问题来源
        issueLevel: undefined, // 问题等级
        failureType: undefined, // 失效类型
        owner: undefined, // 责任人
        departmentId: undefined, // 部门ID
        startCloseDate: undefined, // 关闭时间开始
        endCloseDate: undefined, // 关闭时间结束
        relationFault: undefined // 分析情况
      },
      this.occurTime = [null, null];
      this.closeDate = [null, null];
      this.tempFormData = {};
      this.initData();
      this.handleDeptLoadData();
    },

    // 列表渲染
    initData() {
      let _this = this;
      _this.tableLoading = true;
      let data = {
        fmeaId: _this.fmeaId,
        pageNo: _this.pageNo,
        pageSize: _this.pageSize,
        issueNo: _this.formData.issueNo, // 问题编号
        issueTitle: _this.formData.issueTitle, // 问题标题
        projectId: _this.formData.projectId, // 项目ID
        productName: _this.formData.productName, // 产品名称
        svpps: _this.formData.svpps, // 结构代码
        partName: _this.formData.partName, // 零件名称
        partNumber: _this.formData.partNumber, // 零件编号
        problemType: _this.formData.problemType, // 问题种类
        occurTimeStart: _this.formData.startOccurTime, // 发生时间开始
        occurTimeEnd: _this.formData.endOccurTime, // 发生时间结束
        issueSource: _this.formData.issueSource, // 问题来源
        issueLevel: _this.formData.issueLevel, // 问题等级
        failureType: _this.formData.failureType, // 失效类型
        owner: _this.formData.owner, // 责任人
        ownerOrgId: _this.formData.departmentId, // 部门ID
        closeTimeStart: _this.formData.startCloseDate, // 关闭时间开始
        closeTimeEnd: _this.formData.endCloseDate, // 关闭时间结束
        relationFault: _this.formData.relationFault // 关联状态
      };
      _this.$api.getResearch(data).then(res => {
        if (res.flag) {
          // 如果返回的数据中flag为true，则执行以下操作
          _this.tableData = res.data.data;
          // 将返回的数据中的data赋值给_this.tableData
          _this.pagination.total = res.data.total;
          // 将返回的数据中的total赋值给_this.pagination.total
        } else {
          // 如果返回的数据中flag为false，则执行以下操作
          _this.tableData = [];
          // 将_this.tableData设置为空数组
          _this.pagination.total = 0;
          // 将_this.pagination.total设置为0
          _this.$notification.error({ message: res.message });
          // 弹出错误通知，显示返回的错误信息
        }
      }).finally(() => {
        // 不论成功或失败，最终都执行以下操作
        _this.tableLoading = false;
        // 将_this.tableLoading设置为false，表示表格加载完成
      });
    },

    // 表格 - 点击分页中数字触发的方法
    handlePageChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.pageNo = pagination.current;
      this.pageSize = pagination.pageSize;
      Object.assign(this.formData, { pageNo: pagination.current, pageSize: pagination.pageSize });
      this.formData = { ...this.tempFormData };
      this.initData();
    },
    // 折叠/展开
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
    },
    //调研分页列表删除
    delFail(record) {
      var _that = this;
      _that.$api
      .delResearch({ id: record.id, fmeaId: _that.$store.getters.fmeaId })
      .then(response => {
        if (response.flag) {
          _that.$message.success(response.message);
          _that.initData();
        } else {
          _that.$message.error(response.message);
        }
      });
    },
    // 查看-关联失效
    viewCase(record) {
      this.$refs.look.showViewDrawer = true;
      this.$refs.look.getResearch(record.id, record.fmeaId);
      this.$refs.look.initSourceData(record.id, record.fmeaId);
      // this.$refs.look.initTableColumns();
    },

    // 获取按钮权限
    initBtnRole() {
      let m = localStorage.getItem('menuRoleList') || '[]';
      let menuList = JSON.parse(m);
      let perId = null;
      menuList.map(item => {
        if (item.code.indexOf('library-historyCase-list') != -1) {
          perId = item.id;
        }
      });
      let data = {
        perId: perId,
      };
      this.$api.initBtnRole(data).then(res => {
        res.data.map(item => {
          if (item.resCode == 'library:historyCase:list:search') {
            this.searchBtnFlag = true;
          } else if (item.resCode == 'library:historyCase:list:view') {
            this.queryBtnFlag = true;
          } else if (item.resCode == 'library:historyCase:list:check') {
            this.verifyBtnFlag = true;
          }
        });
      });
    },
    closeModal() {
      this.visiblePQCPModel = false;
      this.initData();
    },
    // 切换全屏
    changeFullScreen() {
      this.fullScreenFlag = !this.fullScreenFlag;
      if (this.fullScreenFlag) {
        this.topValue = { top: 0 };
        this.bodyStyle = { height: '100vh' };
        this.widthValue = '100vw';
      } else {
        this.topValue = {};
        this.bodyStyle = {};
        this.widthValue = 1000;
      }
    },
    // 是否适用 改变事件
    applyChange(row) {
      //下拉框改变时
      if (row.isApply === 0 && row.relationFault === 2) {
        this.$confirm({
          title: this.$t("global-message.warn"),
          content: this.$t("global-message.warn.change-clean-data"),
          icon: "question-circle",
          okText: this.$t("global-btn.ok"),
          cancelText: this.$t("global-btn.cancel"),
          onOk() {
            this.updateResearch(row);
          },
          onCancel() {
            row.isApply = 1;
          }
        });
      } else {
        this.updateResearch(row);
      }
    },
    /**
     * 不适用原因点击
     * @param record
     */
     notApplyClick(record) {
      record.isEdit = true;
    },
    /**
     * 不适用原因失去焦点
     * @param record
     */
    notApplyInputBlur(record) {
      record.isEdit = false;
      this.updateResearch(record);
    },
    // 更新
    updateResearch(row) {
      this.$api.updateResearch({
        id: row.id,
        isApply: row.isApply,
        historyFailId: row.historyFailId,
        notApplyReason: row.isApply === 0 ? row.notApplyReason : '',
        fmeaId: this.$store.getters.fmeaId
      }).then(res => {
        if (res.flag) {
          row.isEdit = false;
          this.$message.success(res.message);
          this.initData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 导出弹窗关闭
    closeExportModal() {
      this.exportVisible = false;
      this.exportType = '1';
    },
    // 导出弹窗
    async exportExcel() {
      // 查询表格列配置信息
      let tableConfigData = {
        userId: this.$route.query.userId,
        pagePath: this.$route.path,
        pageName: this.$route.name,
      };
      await this.$api.getTableColumnsData(tableConfigData).then(res => {
        if (res.flag) {
          if (res.data.currentTableConfigMap && Object.keys(res.data.currentTableConfigMap).length > 0) {
            // 获取当前表格的配置信息
            let tableConfig = res.data.currentTableConfigMap['experience-table'];
            if (tableConfig) {
              this.tableId = tableConfig.id;
            }
          }
        }
      });
      this.exportVisible = true;
    },
    // 导出文件
    exportFile() {
      let tableId = this.tableId || ''; // 表格id
      let exportType = this.exportType; // 导出类型
      // 查询条件
      let fmeaId = this.fmeaId;
      let issueNo = this.formData.issueNo || ''; // 问题编号
      let issueTitle = this.formData.issueTitle || ''; // 问题标题
      let projectId = this.formData.projectId || ''; // 项目ID
      let productName = this.formData.productName || ''; // 产品名称
      let svpps = this.formData.svpps || ''; // 结构代码
      let partName = this.formData.partName || ''; // 零件名称
      let partNumber = this.formData.partNumber || ''; // 零件编号
      let problemType = this.formData.problemType || ''; // 问题种类
      let startOccurTime = this.formData.startOccurTime || ''; // 发生时间开始
      let endOccurTime = this.formData.endOccurTime || ''; // 发生时间结束
      let issueSource = this.formData.issueSource || ''; // 问题来源
      let issueLevel = this.formData.issueLevel || ''; // 问题等级
      let failureType = this.formData.failureType || ''; // 失效类型
      let owner = this.formData.owner || ''; // 责任人
      let departmentId = this.formData.departmentId || ''; // 部门ID
      let startCloseDate = this.formData.startCloseDate || ''; // 关闭时间开始
      let endCloseDate = this.formData.endCloseDate || ''; // 关闭时间结束
      let relationFault = this.formData.relationFault || ''; // 分析情况

      let url = this.$api.baseUrl + "/DFMEA/mfmea/research/experienceExportExcel?";
      url += "fmeaId=" + fmeaId + "&issueNo=" + issueNo + "&issueTitle=" + issueTitle + "&projectId=" + projectId +
          "&productName=" + productName + "&svpps=" + svpps + "&partName=" + partName +
          "&partNumber=" + partNumber + "&problemType=" + problemType + "&occurTimeStart=" + startOccurTime +
          "&occurTimeEnd=" + endOccurTime + "&issueSource=" + issueSource + "&issueLevel=" + issueLevel +
          "&failureType=" + failureType + "&owner=" + owner + "&ownerOrgId=" + departmentId +
          "&closeTimeStart=" + startCloseDate + "&closeTimeEnd=" + endCloseDate + "&relationFault=" + relationFault +
          "&tableId=" + tableId + "&exportType=" + exportType;
      window.open(url);
      this.closeExportModal();
    }
  },
  created() {
    var _this = this; //回车执行查询事件
    document.onkeydown = function (e) {
      //按下回车提交
      let key = window.event.keyCode;
      //事件中keycode=13为回车事件
      if (key == 13) {
        _this.handleSearch();
      }
    };
  },
  mounted() {
    this.initData();
    this.handleDeptLoadData();
    this.getProjectInfo();
    this.initTableColumns();
    this.handleResize();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
  },
  //剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style lang="less" scoped>

/deep/ .ant-table-title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 700;
}

.fullScreen {
  cursor: pointer;
  position: absolute;
  right: 60px;
  color: gray;
  margin-top: 3px;
}

.range-picker-class {
  width: 100%;
}

.ant-dropdown-menu {
  padding: 4px 15px;
  width: 200px
}

.dropdown-footer {
  padding-left: 60px;
}

/deep/ .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  overflow: hidden!important;
  margin-bottom: 0!important;
  padding-right: 8px;
  background: rgb(250, 250, 250);
}
</style>
