<template>
  <div>
    <a-collapse :defaultActiveKey="'1'">
      <a-collapse-panel :header="$t('plan.correlate-pfmea')" key="1">
        <a-card class="mb_8" id="search-card">
          <a-form layout="vertical">
            <a-row :gutter="24">
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('plan.correlate-pfmea.pfmea-number')">
                  <a-input
                    allowClear
                    :placeholder="
                      $t('plan.correlate-pfmea.please-enter-pfmea-number')
                    "
                    v-model="queryParam.dfmeaCode"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item
                  :label="$t('plan.correlate-pfmea.operation/process-name')"
                >
                  <a-input
                    allowClear
                    :placeholder="
                      $t(
                        'plan.correlate-pfmea.please-enter-operation/process-name'
                      )
                    "
                    v-model="queryParam.name"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('plan.correlate-pfmea.version')">
                  <a-input
                    allowClear
                    :placeholder="
                      $t('plan.correlate-pfmea.please-enter-version')
                    "
                    v-model="queryParam.versionDesc"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('plan.correlate-pfmea.owner')">
                  <a-input
                    allowClear
                    :placeholder="
                      $t('plan.correlate-pfmea.please-enter-owner-name')
                    "
                    v-model="queryParam.user"
                  />
                </a-form-item>
              </a-col>
              <span v-show="advanceExpand">
                <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                  <a-form-item :label="$t('plan.correlate-pfmea.process-code')">
                    <a-input
                      allowClear
                      :placeholder="
                        $t('plan.correlate-pfmea.please-enter-process-code')
                      "
                      v-model="queryParam.svpps"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                  <a-form-item
                    :label="
                      $t('plan.basic-information.planning-completion-time')
                    "
                  >
                    <a-range-picker
                      :value="tg1Date"
                      @change="tg1Change"
                      style="width:100%"
                    />
                  </a-form-item>
                </a-col>
              </span>
              <a-col
                :xl="advanceExpand ? 12 : 24"
                :lg="advanceExpand ? 24 : 16"
                :md="24"
                :sm="24"
                :xs="24"
              >
                <a-form-item class="tr" :label="'\xa0'">
                  <a @click="toggleAdvance">
                    {{
                      advanceExpand
                        ? $t("global.collapse")
                        : $t("global.expand")
                    }}
                    <a-icon :type="advanceExpand ? 'up' : 'down'" />
                  </a>
                  <a-button class="ml10" @click="reset">
                    {{ $t("global-btn.reset") }}
                  </a-button>
                  <a-button class="ml10" type="primary" @click="search">
                    {{ $t("global-btn.search") }}
                  </a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <a-card id="grid-card">
          <template slot="title">
            <a-button :disabled="!$api.btnPms" type="primary" @click="quotePFMEA">
              {{ $t("global-btn.correlate-pfmea") }}
            </a-button>
            <a-button class="ml10" :disabled="!$api.btnPms" type="primary" @click="shareDFMEA">
              {{ $t("global-btn.share-dfmea") }}
            </a-button>
            <a-button class="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="quote-pfmea-table"
            ref='tableRef'
            size="small"
            bordered
            :components='components'
            :columns='sortedColumns.filter(column => column.visible)'
            :pagination="pagination"
            :rowKey="
              (record, index) => {
                return index;
              }
            "
            :dataSource="quoteMasterData"
            @change="handleOuterTableChange"
            :loading="loading"
            :scroll='{ x: scrollWidth, y: tableHeightValue }'
          >
            <template slot="sortNumber" slot-scope="text, row, index"
              >{{ (pagination.pageNo - 1) * pagination.pageSize + 1 + index }}
            </template>
            <template slot="action" slot-scope="text, record">
              <a class="operation-btn" @click="look(record)">
                <!-- 删除 -->
                <a-tooltip :title="$t('global-btn.look')">
                  <i class="iconfont iconchakan"></i>
                </a-tooltip>
              </a>
            </template>
            <!-- 序号列 -->
            <template slot="index" slot-scope="text, record, index">
              <span>{{
                (pagination.current - 1) * pagination.pageSize + index + 1
              }}</span>
            </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-collapse-panel>
    </a-collapse>
    <!-- PFMEA列表 -->
    <PFMEAList
      ref="PFMEAList"
      @closePFMEAListModal="closePFMEAListModal"
      :showPFMEAList="showPFMEAList"
    />
    <!-- PFMEA列表 -->
    <shareDFMEA
      ref="shareDFMEA"
      @closeShareDFMEAModal="closeShareDFMEAModal"
      :showShareDFMEA="showShareDFMEA"
    />
    <!-- PFMEA列表 -->
    <CompareDFMEA
      ref="CompareDFMEA"
      @closeCompareDFMEAModal="closeCompareDFMEAModal"
      :showCompareDFMEA="showCompareDFMEA"
    />
  </div>
</template>
<script>
import PFMEAList from "./PFMEAList";
import shareDFMEA from "./shareDFMEA";
import CompareDFMEA from "./CompareDFMEA";
import VueDraggableResizable from 'vue-draggable-resizable';
import draggable from 'vuedraggable';

export default {
  name: "QuotePFMEA",
  components: {
    VueDraggableResizable,
    draggable,
    PFMEAList,
    shareDFMEA,
    CompareDFMEA
  },
  props: {
    from: {
      type: String,
      default: "dfmea"
    },
    fmeaId: {
      type: String | Number,
      default: ""
    },
    masterFmeaId: {
      type: String | Number,
      default: ""
    },
    fmeaType: {
      type: String | Number,
      default: "1"
    }
  },
  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: '',
      // 当前页
      pageNo: 1,
      // 每页显示的数据条数
      pageSize: 10,
      // 沿用MasterFMEA
      loading: false,
      pagination: {
        current: 1,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total =>
          this.$t("global-constant.table.show-total", [total]), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        // onChange: (page, pageSize) => self.changePage(page, pageSize), //点击页码事件
        total: 0 //总条数
      },
      // 复选框控制的状态
      columnVisibilities: {
        serialNumber: true,
        dfmeaCode: true,
        partName: true,
        dfmeaOwnerName: true,
        departmentName: true,
        svpps: true,
        version: true,
        fmeaBusiType: true,
        partTg2Time: true,
        action: true
      },
      scrollWidth: 0,
      startDrag: false,
      editColumnVisibilities: [],
      sortedColumns: [], // 用于拖拽的列数组
      // 表头
      tableColumns: [
        {
          title: "fmea.relevance.pfmea.export.title.serialNumber",
          width: 70,
          align: "center",
          dataIndex: "serialNumber",
          scopedSlots: {
            customRender: "index"
          },
          visible: true,
          cantHide: true,
          cantHandle: true,
          fixed: 'left',
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.pfmeaCode",
          width: 300,
          align: "center",
          dataIndex: "dfmeaCode",
          scopedSlots: {
            customRender: "action3"
          },
          visible: true,
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.processName",
          width: 200,
          align: "center",
          dataIndex: "partName",
          visible: true,
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.owner",
          width: 110,
          align: "center",
          dataIndex: "dfmeaOwnerName",
          visible: true,
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.section",
          width: 120,
          align: "center",
          dataIndex: "departmentName",
          visible: true,
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.processCoding",
          width: 150,
          align: "center",
          dataIndex: "svpps",
          visible: true,
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.edition",
          width: 100,
          align: "center",
          dataIndex: "version",
          scopedSlots: {
            customRender: "version"
          },
          visible: true,
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.fmeaType",
          width: 100,
          align: "center",
          dataIndex: "fmeaBusiType",
          visible: true,
          ellipsis: true
        },
        {
          title: "fmea.relevance.pfmea.export.title.plannedCompletionTime",
          width: 200,
          align: "center",
          dataIndex: "partTg2Time",
          visible: true,
          ellipsis: true
        },
        {
          title: "plan.correlate-pfmea.operate",
          width: 100,
          dataIndex: "action",
          align: "center",
          fixed: 'right',
          scopedSlots: {
            customRender: "action"
          },
          visible: true,
          cantHide: true,
          cantHandle: true
        }
      ],
      tableHeight: 0,
      tableHeightValue: 0,
      quoteMasterData: [],
      // 项目DFMEA管理
      loadingSync: false,
      paginationSync: {
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total =>
          this.$t("global-constant.table.show-total", [total]), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        // onChange: (page, pageSize) => self.changePage(page, pageSize), //点击页码事件
        total: 0 //总条数
      },
      PFMEAList: [],

      labelCol: {
        // 24格栅格系统，label所占为 a
        xl: 10, // ≥1600px 响应式栅格
        lg: 8, // ≥992px 响应式栅格
        md: 6, // ≥768px 响应式栅格
        sm: 6,
        xs: 6
      },
      wrapperCol: {
        // 24格栅格系统，label后面内容所占为 24-a
        xl: 14,
        lg: 16,
        md: 18,
        sm: 18,
        xs: 18
      },
      // 查询参数
      queryParam: {
        dfmeaCode: undefined,
        name: undefined,
        versionDesc: undefined,
        user: undefined,
        svpps: undefined,
        status: undefined
      },
      /** PFMEA列表模态框开关 */
      showPFMEAList: false,
      /** DFMEA分享模态框开关 */
      showShareDFMEA: false,
      /** DFMEA对比模态框开关 */
      showCompareDFMEA: false,
      tg1Date: [],
      advanceExpand: false
    };
  },
  watch: {
    sortedColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格滚动区域的总宽度
          let scrollX = $('.ant-table-fixed').width();
          // 获取表格的总宽度
          let tableWidth = $('.ant-table-body').width();
          // a-table的scrollX宽度需要减去固定列宽度
          this.scrollWidth = scrollX - 170;
          if (scrollX <= tableWidth) {
            this.cancelFixedColmuns();
          } else {
            this.reloadFixedColmuns([0], [this.sortedColumns.length - 1]);
          }
        });
      },
      deep: true,
      immediate: true
    },
    advanceExpand: {
      handler() {
        this.$nextTick(() => {
          this.handleResize();
        });
      }
    }
  },
  methods: {
    /**
     * 初始化加载已保存的表格列顺序及显隐
     */
     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['quote-pfmea-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: 'quote-pfmea-table'
      };
      // 调用API保存表格配置
      this.$api.saveTableConfig(data).then(res => {
        // 如果返回结果中的flag为true，表示保存成功
        if (res.flag) {
          // 显示成功提示信息
          this.$message.success(res.message, 1);
          // 重新初始化数据
          this.search();
        } else {
          // 显示错误提示信息
          this.$message.error(res.message, 1);
        }
      }).finally(() => {
        // 重新初始化数据
        this.search();
      });
    },
    /**
     * 处理表格列显隐复选框变化事件
     *
     * @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 - 222;
      this.scrollWidth = this.$refs.tableRef?.$el.offsetWidth;
      // 获取表格滚动区域的总宽度
      let scrollX = $('.ant-table-fixed').width() - 170;
      // 获取表格的总宽度
      let tableWidth = $('.ant-table-body').width();
      // 超过2K屏时取消固定列
      if (width > 2560 || scrollX <= tableWidth) {
        this.cancelFixedColmuns();
      } else {
        this.reloadFixedColmuns([0], [this.sortedColumns.length - 1]);
      }
    },
    // 收起/展开
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
    },
    getQuotePFMEAPageList() {
      let _this = this;
      _this.tableLoading = true;
      let data = {
        dfmeaCode: _this.tempFormData.dfmeaCode,
        dfmeaOwnerName: _this.tempFormData.user,
        fmeaBusiType: _this.tempFormData.fmeaType,
        svpps: _this.tempFormData.svpps,
        pageNo: _this.pageNo,
        pageSize: _this.pageSize,
        partName: _this.tempFormData.name,
        partTg2TimeEnd: _this.tempFormData.tg1_end,
        partTg2TimeStart: _this.tempFormData.tg1_start,
        fmeaId: _this.fmeaId,
        versionDesc: _this.tempFormData.versionDesc,
        category: _this.$route.query.from === 'master' ? 2 : 1
      };
      this.$api
        .getQuotePFMEAPageList(data)
        .then(res => {
          if (!res.flag) {
            this.$notification.error({ message: res.message });
          }
          _this.quoteMasterData = res.data.data || [];
          _this.pagination.total = res.data.total || 0;
        })
        .finally(() => {
          _this.tableLoading = false;
        });
    },
    // 工艺数模时间
    tg1Change(date, dateString) {
      this.tg1Date = date;
      this.queryParam.tg1_start = dateString[0] || undefined;
      this.queryParam.tg1_end = dateString[1] || undefined;
    },
    // 重置
    reset() {
      this.queryParam.dfmeaCode = undefined;
      this.queryParam.name = undefined;
      this.queryParam.versionDesc = undefined;
      this.queryParam.user = undefined;
      this.queryParam.svpps = undefined;
      this.queryParam.tg1_start = undefined;
      this.queryParam.tg1_end = undefined;
      this.tg1Date = [];
      this.queryParam.status = undefined;
      this.pageNo = 1;
      this.pageSize = 10;
      this.tempFormData = {};
      this.pagination.current = 1;
      this.pagination.pageNo = 1;
      this.pagination.pageSize = 10;
      this.getQuotePFMEAPageList();
    },
    // 搜索
    search() {
      this.pageNo = 1;
      this.pageSize = this.pagination.pageSize;
      this.pagination.current = 1;
      this.tempFormData = { ...this.queryParam };
      this.getQuotePFMEAPageList();
    },
    // 项目DFMEA分页列表 - 点击分页中数字触发的方法
    handleOuterTableChange(pagination) {
      this.pageNo = pagination.current;
      this.pageSize = pagination.pageSize;
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getQuotePFMEAPageList();
    },
    // 开关关联PFMEA列表
    quotePFMEA() {
      this.$refs.PFMEAList.getAllProjectPFMEAPageList();
      this.showPFMEAList = true;
    },
    // 分享DFMEA
    shareDFMEA() {
      this.$refs.shareDFMEA.getQuotePFMEAList();
      this.showShareDFMEA = true;
    },
    // 查看分享的详细页面
    look(record) {
      this.$refs.CompareDFMEA.queryParam.rfmeaId = record.rfmeaId;
      this.$refs.CompareDFMEA.init();
      this.showCompareDFMEA = true;
    },
    /**
     * 关闭：PFMEAList模态框
     */
    closePFMEAListModal() {
      this.showPFMEAList = false;
      this.search();
    },
    /**
     * 关闭：PFMEAList模态框
     */
    closeShareDFMEAModal() {
      this.showShareDFMEA = false;
    },
    /**
     * 关闭：CompareDFMEA模态框
     */
    closeCompareDFMEAModal() {
      this.showCompareDFMEA = false;
    },
    // 导出弹窗关闭
    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['quote-pfmea-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 category = this.$route.query.from === 'master' ? 2 : 1;
      let dfmeaCode = this.queryParam.dfmeaCode || '';
      let partName = this.queryParam.name || '';
      let versionDesc = this.queryParam.versionDesc || '';
      let dfmeaOwnerName = this.queryParam.user || '';
      let svpps = this.queryParam.svpps || '';
      let fmeaBusiType = this.tempFormData.fmeaType || '';
      let partTg2TimeEnd = this.queryParam.tg1_start || '';
      let partTg2TimeStart = this.queryParam.tg1_end || '';

      let url = this.$api.baseUrl + "/DFMEA/projectPFMEA/relevancePfmeaExportExcel?";
      url += "fmeaId=" + fmeaId + "&category=" + category + "&dfmeaCode=" + dfmeaCode + "&fmeaBusiType=" + fmeaBusiType +
      "&partName=" + partName + "&versionDesc=" + versionDesc + "&dfmeaOwnerName=" + dfmeaOwnerName + "&svpps=" + svpps +
      "&partTg2TimeStart=" + partTg2TimeStart + "&partTg2TimeEnd=" + partTg2TimeEnd + "&tableId=" + tableId + "&exportType=" + exportType;
      window.open(url);
      this.closeExportModal();
    }
  },
  mounted() {
    this.search();
    this.initTableColumns();
    this.handleResize();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
  },
  //剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>
<style scoped>

</style>

<style lang="less" scoped>
.operation-btn {
  color: #1890FF;
}

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