<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('research.analyze-situation')">
                <a-select allowClear v-model='formData.analysisState'
                          :placeholder="$t('research.please-select-analyze-situation')">
                  <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" type="primary" @click="handleSubmit">
          {{ $t('global-btn.add') }}
        </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 ref='tableRef'
               size="small"
               bordered
               id="experience-model-table"
               :components='components'
               :columns='sortedColumns.filter(column => column.visible)'
               :dataSource='tableData'
               :rowKey='(record, index) => { return record.failExpId; }'
               :rowSelection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                }"
               :scroll='{ x: scrollWidth, y: tableHeightValue }'
               :pagination='pagination'
               :loading='tableLoading'
               @change='handlePageChange'>
        <template slot='analysisState' slot-scope='text,row'>
          <span>
            {{
              row.analysisState === '03'
                  ? $t('workbench.unanalyzed')
                  : row.analysisState === '04'
                      ? $t('workbench.analysis-has-been')
                      : '-'
            }}
          </span>
        </template>
        <template slot='pqcpCloseDate' slot-scope='text'>
          <span>{{ $api.timeToDate(text) }}</span>
        </template>
        <!-- 序号列 -->
        <template slot='index' slot-scope='text, record, index'>
          <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
        </template>
      </a-table>
    </a-card>
    <!--<view-drawer :showViewDrawer='showViewDrawer' ref='look' :failExpId='failExpId'  @initData="initData" />-->
  </div>
</template>
<script>
import VueDraggableResizable from 'vue-draggable-resizable';
import draggable from 'vuedraggable';

export default {
  components: {
    VueDraggableResizable,
    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, 200);
              }
            }
          };
          const drag = h('vue-draggable-resizable', { ...dragProps });
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
        }
      }
    };
    return {
      // 表格总宽度
      scrollWidth: 0,
      advanceExpand: false,
      userFetching: false,
      startDrag: false,
      editColumnVisibilities: [],
      sortedColumns: [], // 用于拖拽的列数组
      // 复选框控制的状态
      columnVisibilities: {
        index: 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, // 失效类型
        owner: true, // 责任人
        departmentName: true, // 部门ID
        pqcpCloseDate: true, // 关闭时间结束
        analysisState: true, // 分析情况
      },
      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, // 关闭时间结束
        analysisState: undefined // 分析情况
      },
      // 部门数据
      deptTreeData: [],
      // 项目列表
      projectList: [],
      //分析情况
      stateList: [
        {
          name: this.$t('workbench.unanalyzed'),
          value: '03',
        },
        {
          name: this.$t('workbench.analysis-has-been'),
          value: '04',
        }
      ],
      failExpId: 0,
      // 表头
      tableColumns: [
        // 序号
        {
          title: this.$t('research.serial-number'),
          width: 100,
          align: 'center',
          dataIndex: 'index',
          fixed: 'left',
          cantHandle: true,
          cantHide: true,
          scopedSlots: {
            customRender: 'index',
          },
          ellipsis: true,
          visible: true,
        },
        // 问题编号
        {
          title: this.$t('report.history-problem-issue-code'),
          dataIndex: 'issueNo',
          visible: true,
          // fixed: 'left',
          // cantHide: true,
          // cantHandle: true,
          align: 'center',
          width: 200,
          ellipsis: true,
        },
        // 问题标题
        {
          title: this.$t('report.history-problem-issue-title'),
          dataIndex: 'issueTitle',
          visible: true,
          align: 'center',
          width: 300,
          ellipsis: true,
        },
        // 项目名称
        {
          title: this.$t('report.history-problem-project-name'),
          dataIndex: 'projectName',
          visible: true,
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        // 产品名称
        {
          title: this.$t('report.history-problem-product-name'),
          dataIndex: 'productName',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 结构代码
        {
          title: this.$t('report.history-problem-svpps'),
          dataIndex: 'svpps',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 失效零件名称
        {
          title: this.$t('report.history-problem-part-name'),
          dataIndex: 'partName',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 失效零件代码
        {
          title: this.$t('report.history-problem-part-code'),
          dataIndex: 'partNumber',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 问题种类
        {
          title: this.$t('report.history-problem-issue-type'),
          dataIndex: 'problemType',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 发生时间
        {
          title: this.$t('report.history-problem-occur-time'),
          dataIndex: 'occurTime',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 问题来源
        {
          title: this.$t('report.history-problem-issue-source'),
          dataIndex: 'issueSource',
          visible: true,
          align: 'center',
          width: 150,
          ellipsis: true,
        },
        // 问题等级
        {
          title: this.$t('report.history-problem-issue-level'),
          dataIndex: 'issueLevel',
          visible: true,
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        // 失效分类
        {
          title: this.$t('report.history-problem-fault-type'),
          dataIndex: 'failureType',
          visible: true,
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        // 责任人
        {
          title: this.$t('report.history-problem-duty-person'),
          dataIndex: 'owner',
          visible: true,
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        // 责任部门
        {
          title: this.$t('report.history-problem-duty-department'),
          dataIndex: 'departmentName',
          visible: true,
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        // 关闭时间
        {
          title: this.$t('report.closing-time'),
          dataIndex: 'pqcpCloseDate',
          visible: true,
          width: 150,
          align: 'center',
          ellipsis: true,
        },
        // 分析情况
        {
          title: this.$t('research.analyze-situation'),
          dataIndex: 'analysisState',
          visible: true,
          width: 150,
          align: 'center',
          scopedSlots: {
            customRender: 'analysisState',
          },
          ellipsis: true,
        },
      ],
      /** 表格Loading */
      tableLoading: false,
      tableData: [],
      // 发生时间
      occurTime: [null, null],
      // 关闭时间
      closeDate: [null, null],
      // 查看弹窗标识
      showViewDrawer: false,
      currentCase: null,
      // 分页
      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,
      selectedRowKeys: [], //table勾选的项
      addData: [], //需要添加的项
      delData: [], //需要删除的项
    };
  },
  watch: {
    sortedColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格滚动区域的总宽度
          let scrollX = $('.ant-table-fixed').width() - 500;
          // 获取表格的总宽度
          let tableWidth = $('.ant-table-body').width();
          // a-table的scrollX宽度需要减去固定列宽度
          this.scrollWidth = scrollX;
          if (scrollX <= tableWidth) {
            this.cancelFixedColmuns();
          } else {
            this.reloadFixedColmuns([0]);
          }
        });
      },
      deep: true,
      immediate: true
    },
    advanceExpand: {
      handler() {
        this.$nextTick(() => {
          this.handleResize();
        });
      }
    },
  },
  methods: {
    /**
     * 初始化加载已保存的表格列顺序及显隐
     */
    async initTableColumns() {
      // 获取用户信息，如果当前组件的userInfo为空，则从localStorage中获取
      let userInfo = this.$route.query.userId;
      // 获取页面中所有的表格容器
      // 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,
          pagePath: this.$route.path,
          pageName: this.$route.name,
          tableIds: ['experience-model-table']
        });
        // 如果接口返回成功
        if (res.flag) {
          // 如果返回的数据中包含当前表格的配置映射，并且映射中有数据
          if (res.data.currentTableConfigMap && Object.keys(res.data.currentTableConfigMap).length > 0) {
            // 获取当前表格的配置信息
            let tableConfig = res.data.currentTableConfigMap['experience-model-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-model-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) {
      fixedLeftColumns.forEach((column) => {
        if (this.sortedColumns[column]) {
          this.sortedColumns[column].fixed = 'left';
        }
      });
    },
    /**
     * 处理窗口大小调整事件
     *
     * @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 - 222;
      this.scrollWidth = this.$refs.tableRef?.$el.offsetWidth;
      // 获取表格滚动区域的总宽度
      let scrollX = $('.ant-table-fixed').width() - 500;
      // 获取表格的总宽度
      let tableWidth = $('.ant-table-body').width();
      // 超过2K屏时取消固定列
      if (width > 2560 || scrollX <= tableWidth) {
        this.cancelFixedColmuns();
      } else {
        this.reloadFixedColmuns([0], []);
      }
    },
    // 部门筛选
    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
      };
      this.$api.getFMEAProjectNoList(data).then(res => {
        if (!res.flag) {
          this.$notification.error({ message: res.message });
        }
        res.data.forEach(item => {
          if(item.projectName !== "") {
            this.projectList.push(item);
          }
        })
      });
    },
    // 项目变更函数
    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, // 关闭时间结束
        analysisState: undefined // 分析情况
      },
          this.occurTime = [null, null];
      this.closeDate = [null, null];
      this.tempFormData = {};
      this.initData();
      this.handleDeptLoadData();
    },

    // 列表渲染
    initData() {
      let _this = this;
      _this.tableLoading = true;
      let data = {
        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, // 问题种类
        startOccurTime: _this.formData.startOccurTime, // 发生时间开始
        endOccurTime: _this.formData.endOccurTime, // 发生时间结束
        issueSource: _this.formData.issueSource, // 问题来源
        issueLevel: _this.formData.issueLevel, // 问题等级
        failureType: _this.formData.failureType, // 失效类型
        owner: _this.formData.owner, // 责任人
        departmentId: _this.formData.departmentId, // 部门ID
        startCloseDate: _this.formData.startCloseDate, // 关闭时间开始
        endCloseDate: _this.formData.endCloseDate, // 关闭时间结束
        analysisState: _this.formData.analysisState // 分析情况
      };
      _this.$api.historyfailList(data).then(res => {
        if (res.flag) {
          _this.tableData = res.data.data;
          _this.pagination.total = res.data.total;
          this.setDefaultSelection();
        } else {
          _this.tableData = [];
          _this.pagination.total = 0;
          _this.$notification.error({ message: res.message });
        }
      }).finally(() => {
        _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;
    },
    // 勾选框change
    onSelectChange(selectedRowKeys) {
      // 找出需要删除的行键（即之前选中但现在未选中的）
      let def = this.selectedRowKeys.filter(key => !selectedRowKeys.includes(key));
      if(def.length > 0){
        for (let i = 0; i < def.length; i++) {
          this.delData.push(def[i]);
        }
      }

      // 找出需要添加的行键（即新选中的，但之前未选中的）
      let sele = selectedRowKeys.filter(key => !this.selectedRowKeys.includes(key));
      if(sele.length > 0){
        for (let i = 0; i < sele.length; i++) {
          this.addData.push(sele[i]);
        }
      }
      this.selectedRowKeys = selectedRowKeys;
    },
    // 获取已勾选的历史失效案例库
    setDefaultSelection() {
      // 初始化selectedRowKeys
      var _that = this;
      // 调用API接口获取已勾选的历史失效案例库
      _that.$api.existResearch({fmeaId: _that.$store.getters.fmeaId})
        .then(res => {
          // 如果返回结果标志为true
          if (res.flag) {
            // 将返回的数据赋值给selectedRowKeys
            this.selectedRowKeys = res.data;
          } else {
            // 如果返回结果标志为false，显示错误信息
            _that.$message.error(res.message);
          }
        });
    },
    // 添加--按钮
    handleSubmit() {
      // 校验
      if (this.addData.length === 0 && this.delData.length === 0) {
        this.$message.warning(this.$t('global-message.warn.unchanged'), 1);
        return;
      }
      this.btnDisabled = true;
      var data = {
        fmeaId: this.$store.getters.fmeaId,
        addHistoryFails: this.addData,
        delHistoryFails: this.delData,
      };
      this.$api.addResearch(data).then((response) => {
        if (response.flag) {
          this.$message.success(response.message);
          this.delData = [];
          this.addData = [];
        } else {
          this.$message.error(response.message);
        }
        this.btnDisabled = false;
        this.$emit("closeModal");
      });
    },
  },
  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.handleResize();
    this.initTableColumns();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
  },
  //剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>
<style lang="less" scoped>

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

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

.dropdown-footer {
  padding-left: 60px;
}
</style>

