<template>
  <div ref="measureTrack" class="summary-archive-content">
    <div class="summary-archive-content-card" :style="{ height: chartHeight }">
      <div class="measureTrack-from" 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('measure-track.measure-track.structure')">
                <span style="float:right;margin-top:-30px;">
                  <a-radio-group @change="radioChange" :default-value="1" size="small">
                    <a-radio :value="2" style="font-weight: normal;overflow: hidden">
                      {{ $t('summary-archive.fmea-table.same-level-check') }}
                    </a-radio>
                    <a-radio :value="3" style="font-weight: normal;overflow: hidden">
                      {{ $t('summary-archive.fmea-table.check-with-same-superior') }}
                    </a-radio>
                    <a-radio :value="1" style="font-weight: normal;overflow: hidden">
                      {{ $t('summary-archive.fmea-table.unlimited') }}
                    </a-radio>
                  </a-radio-group>
                </span>
                <a-tree-select ref="leftTree" treeCheckable v-model="searchParams.struIds" treeCheckStrictly
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :placeholder="$t('measure-track.measure-track.please-select-a-structure')" allow-clear
                  :maxTagCount="3" :showArrow="true" :treeExpandedKeys="leftTreeExpandedKeys"
                  :replaceFields="replaceFields" :filterTreeNode="leftFilterTreeNode" :tree-data="leftTreeData"
                  @treeExpand="leftTreeExpand" @select="selectBtn" @change="leftTreeSelectChange">
                  <template slot="treeDataSlot" slot-scope="node">
                    {{ node.name }}
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <!-- 功能 -->
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('global-dict.function')">
                <a-select
                  mode="multiple"
                  :placeholder="$t('global-constant.please-select') + $t('global-dict.function')"
                  allow-clear
                  v-model="searchParams.functionStruIds"
                  :filter-option="filterOption"
                  @change="functionSelectChange">
                  <a-select-option v-for="(value, index) in funData" :key="index" :value="value.struId">
                    {{ value.name }}
                  </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('global-dict.failure')">
                <a-select
                  mode="multiple"
                  :placeholder="$t('global-constant.please-select') + $t('global-dict.failure')"
                  allow-clear
                  v-model="searchParams.failStruIds"
                  :filter-option="filterOption"
                  @change="failSelectChange">
                  <a-select-option v-for="(value, index) in failData" :key="index" :value="value.struId">
                    {{ value.name }}
                  </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('global-dict.measure')">
                <a-select
                  mode="multiple"
                  :placeholder="$t('global-constant.please-select') + $t('global-dict.measure')"
                  allow-clear
                  v-model="searchParams.actionStruIds"
                  :filter-option="filterOption"
                  @change="actionSelectChange">
                  <a-select-option v-for="(value, index) in actionData" :key="index" :value="value.struId">
                    {{ value.name }}
                  </a-select-option>
                </a-select>
              </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('measure-track.measure-track.measure-status')">
                  <a-select :placeholder="$t('measure-track.measure-track.please-select-measure-status')" allow-clear
                            v-model="searchParams.actionState"
                    @change="measureStateChange">
                    <a-select-option v-for="(item, index) in measureStateDict" :key="index" :value="item.value">
                      {{ item.name }}
                    </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('measure-track.measure-track.measure-distribute-status')">
                  <a-select :placeholder="$t('measure-track.measure-track.please-select-measure-distribute-status')"
                            v-model='searchParams.distributeStatus'
                    allow-clear @change="measureDistributeStateChange">
                    <a-select-option v-for="(item, index) in measureDistributeStateDict" :key="index" :value="item.value">
                      {{ item.name }}
                    </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('measure-track.measure-track.status')">
                  <a-select :placeholder="$t('measure-track.measure-track.please-select-status')" allow-clear
                            v-model='searchParams.state'
                    @change="stateChange">
                    <a-select-option v-for="(item, index) in stateDict" :key="index" :value="item.value">
                      {{ item.name }}
                    </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('measure-track.measure-track.measure-type')">
                  <a-select :placeholder="$t('measure-track.measure-track.please-select-measure-type')" allow-clear
                            v-model='searchParams.actionType'
                    @change="measureTypeChange">
                    <a-select-option v-for="(item, index) in measureTypeDict" :key="index" :value="item.value">
                      {{ item.name }}
                    </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('measure-track.measure-track.plan-date')">
                  <a-range-picker class="width100" allow-clear :value="planDate" @change="planDateChange" v-model="planDate"/>
                </a-form-item>
              </a-col>
              <!-- 开始日期 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('measure-track.measure-track.start-date')">
                  <a-range-picker class="width100" :value="startDate" @change="startDateChange" v-model="startDate"/>
                </a-form-item>
              </a-col>
              <!-- 完成日期 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('measure-track.measure-track.complete-date')">
                  <a-range-picker class="width100" :value="completeDate" @change="completeDateChange" v-model="completeDate"/>
                </a-form-item>
              </a-col>
              <!-- 负责人 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('measure-track.measure-track.responsible-person')">
                  <a-input-group compact>
                    <a-select style="width: 85%"
                      :placeholder="$t('measure-track.measure-track.please-select-responsible-person')" v-model="searchParams.userId"
                      :disabled="!!searchParams.userEmptyFlag" allow-clear @change="responsibleChange">
                      <a-select-option v-for="(item, index) in responsibles" :key="index" :value="item.userId">
                        {{ item.userName }}
                      </a-select-option>
                    </a-select>
                    <a-dropdown style="width: 15%;" :trigger="['click']" placement="bottomRight">
                      <a class="ant-dropdown-link">
                        <a-button :disabled="!!searchParams.userId" icon="filter" class="width100" type="primary" />
                      </a>
                      <a-menu slot="overlay">
                        <a-menu-item v-for="(item, index) in responsibleFilterDropDownDict" :key="index"
                          @click="responsibleDropDownFilterClick(item, responsibleFilterDropDownDict)">
                          <a-checkbox :checked="item.checked" />
                          <span class="ml5">
                            {{ item.label }}
                          </span>
                        </a-menu-item>
                      </a-menu>
                    </a-dropdown>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <!-- 第二语言 -->
              <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
                <a-form-item :label="$t('summary-Archive.fmea-table.second-language')">
                  <a-select v-model="searchParams.twoLanguage"
                    :placeholder="$t('summary-Archive.fmea-table.pleae-select-second-language')"
                    :loading="secondLanguageLoading">
                    <a-select-option v-for="(item, index) in secondLanguages" :key="index" :value="item.lkey">
                      {{ $t("global-dict.select-nls." + item.lkey) }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </span>
          </a-row>
        </a-form>
        <!-- 按钮组 -->
        <div class="pt10 pb10">
          <span>
            <!-- 导出 -->
            <a-button class="mr5" @click="excelExport" type="primary">
              {{ $t("global-btn.export") }}
            </a-button>
            <!-- 编辑 -->
            <a-button v-if="this.$api.isLook !== '1'" class="mr5" @click="edit" type="primary">
              {{ $t("global-btn.edit") }}
            </a-button>
            <!-- 分发 -->
            <a-button v-if="this.$api.isLook !== '1'" class="mr5" @click="handOut" type="primary">
              {{ $t("global-btn.hand-out") }}
            </a-button>
            <!-- 取消 -->
            <a-button v-if="this.$api.isLook !== '1'" class="mr5" @click="cancelDistribution" type="primary">
              {{ $t("global-btn.hand-out.cancel") }}
            </a-button>
            <!-- 保存 -->
            <a-button v-if="this.$api.isLook !== '1'" :loading="saveLoading" @click="saveBatch" type="primary">
              {{ $t("global-btn.save") }}
            </a-button>
          </span>
          <span class="fr">
            <!-- 展开折叠 -->
            <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" @click="search" type="primary">
              {{ $t("global-btn.search") }}
            </a-button>
          </span>
        </div>
      </div>
      <!-- 表格 -->
      <a-card id="grid-card">
        <!-- 自定义配置 -->
        <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('global-btn.save')
                  }}
                </a-button>
              </a-menu-item>
            </a-menu>
            <a-button icon="setting" type="link" :title="($t('fmeamanager.setting.col'))"></a-button>
          </a-dropdown>
        </template>
        <a-table
          id="page-table"
          ref="tableRef"
          :data-source="tableData"
          :columns="sortedColumns.filter(column => column.visible)"
          :rowKey="(row, index) => { return index; }" :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            onSelect: onSelect
          }"
          bordered size="small"
          :loading="tableLoading"
          :scroll="{ x: scrollWidth, y: tableHeightValue }"
          @change="tableChange"
          :pagination="pagination"
          :components='components'>
          <!-- 序号 -->
          <template slot="index" slot-scope="text, record, index">
            <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
          </template>
          <!-- 措施状态 -->
          <template slot="measuresState" slot-scope="text, record">
            {{ record.measuresState === "14" ? $t("global-dict.current-measures") :
              $t("global-dict.optimization-measures") }}
          </template>
        </a-table>
      </a-card>
    </div>

    <!--  编辑模态框 Start -->
    <EditModal ref="editModal" :showEditModal="showEditModal" :selectStruIds="selectStruIds"
      @closeEditModal="closeEditModal" @initList="list" />
    <!--  编辑模态框 End -->

    <!--  导出模态框 Start -->
    <ExportModal ref="exportModal" @initData="list"></ExportModal>
    <!--  导出模态框 End -->
  </div>
</template>

<script>
import EditModal from "./components/EditModal";
import moment from "moment";
import { arrayToTree } from "@/utils/tree";
import { dateFormat } from "@/utils/date";
import VueDraggableResizable from 'vue-draggable-resizable';
import draggable from 'vuedraggable';
import ExportModal from './components/ExportModal';
import {CONTEXTMENU_ITEMS_HIDE_COLUMN} from "../../../utils/ModulePatch/handsontable-pro/dist-bak/handsontable";

/**
 * 合并单元格
 *
 * @param data 表格数据
 * @param row 当前行数据
 * @param index 当前行索引
 * @returns 单元格的跨行数量
 */
const mergeCells = (data, row, index) => {
  let rowSpan = 1;
  let flag = false;
  let currentMeagrId = undefined;
  let lastMeagrId = undefined;
  let nextMeagrId = undefined;

  // 如果没有合并id，则返回行跨度为1
  if (!row.mergeId) {
    return rowSpan;
  }

  // 如果数据只有一条，则返回行跨度为1
  if (data.length == 1) {
    return rowSpan;
  }

  // 当index为0时表示是第一个,不需要考虑上面的合并id
  if (index == 0) {
    // 当前行的合并id
    let currentMeagrId = data[index].mergeId;
    // 下一行的合并id
    let nextMeagrId = data[index + 1].mergeId;

    // 如果当前行和下一行的合并id相同
    if (currentMeagrId == nextMeagrId) {
      // 遍历后面的行，如果合并id相同，则行跨度加1
      for (let j = index + 1; j < data.length; j++) {
        if (data[j].mergeId != undefined && data[j].mergeId == currentMeagrId) {
          rowSpan++;
        }
      }
      // 返回行跨度
      return rowSpan;
    } else {
      // 返回行跨度为1
      return 1;
    }
  } else if (index == data.length - 1) {
    // 当前行的合并id
    currentMeagrId = data[index].mergeId;
    // 上一行的合并id
    lastMeagrId = data[index - 1].mergeId;

    // 如果当前行和上一行的合并id不同
    if (currentMeagrId != lastMeagrId) {
      // 返回行跨度为1
      return 1;
    } else {
      // 返回行跨度为0，表示该行应该被合并到上一行
      return 0;
    }
  } else {
    // 当前行的合并id
    currentMeagrId = data[index].mergeId;
    // 下一行的合并id
    nextMeagrId = data[index + 1].mergeId;
    // 上一行的合并id
    lastMeagrId = data[index - 1].mergeId;

    // 如果当前行和上一行的合并id相同
    if (currentMeagrId == lastMeagrId) {
      // 返回行跨度为0，表示该行应该被合并到上一行
      return 0;
    } else if (currentMeagrId == nextMeagrId && currentMeagrId != lastMeagrId) {
      // 遍历后面的行，如果合并id相同，则行跨度加1
      for (let j = index + 1; j < data.length; j++) {
        if (data[j].mergeId != undefined && data[j].mergeId == currentMeagrId) {
          rowSpan++;
        }
      }
      // 返回行跨度
      return rowSpan;
    }
  }
};


export default {
  name: "MeasureTrack",
  components: {
    EditModal,
    VueDraggableResizable,
    draggable,
    ExportModal
  },
  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, 35);
              }
            }
          };
          const drag = h('vue-draggable-resizable', { ...dragProps });
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
        }
      }
    };
    return {
      desplayNlsTwoLanguage: undefined, // 默认的第二语言
      deepCurrent: '', // 当前选中的层级
      checkIdShow: false, // 同级勾选是否启动
      sameSuperCheckFlag: false, // 同父级勾选是否启动
      checkedEvet: false, // 判断是勾选还是删除
      currentChecked: [], // 完全受控数据
      struNodeList: [], // 节点下拉选原始数据
      /** 日期处理类库 */
      moment,
      // 表格总宽度
      scrollWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      /** 措施类型字典Dict */
      measureTypeDict: [
        { name: this.$t("global-dict.prevent"), value: "09" },
        { name: this.$t("global-dict.detect"), value: "10" }
      ],
      /** 措施状态字典Dict */
      measureStateDict: [
        { name: this.$t("global-dict.current-measures"), value: "14" },
        { name: this.$t("global-dict.optimization-measures"), value: "07" }
      ],
      /** 措施分发状态字典Dict */
      measureDistributeStateDict: [
        { name: this.$t("global-dict.undistributed"), value: "0" },
        { name: this.$t("global-dict.distributed"), value: "1" }
      ],
      /** 状态字典Dict */
      stateDict: [
        { name: this.$t("global-dict.un-processed"), value: "01" },
        { name: this.$t("global-dict.to-be-decided"), value: "02" },
        { name: this.$t("global-dict.to-be-implemented"), value: "03" },
        { name: this.$t("global-dict.in-working"), value: "10" },
        { name: this.$t("global-dict.complete"), value: "20" },
        { name: this.$t("global-dict.abandon"), value: "04" },
        { name: this.$t("global-dict.finish"), value: "05" }
      ],
      /** 负责人筛选下拉Dict */
      responsibleFilterDropDownDict: [
        {
          label: this.$t("global-dict.responsible-person-is-empty"),
          value: "0",
          checked: false
        },
        {
          label: this.$t("global-dict.responsible-person-is-not-empty"),
          value: "1",
          checked: false
        }
      ],
      /** 负责人 */
      responsibles: [],
      /** 表格数据 */
      tableData: [],
      /** 初始表格数据 */
      initTableData: [],
      /** 表格列头 */
      tableColumns: [
        // 序号
        {
          title: "measure-track.measure-track.serial-number",
          width: 50,
          dataIndex: "index",
          visible: true,
          cantHide: true,
          cantHandle: true,
          align: "center",
          scopedSlots: { customRender: "index" },
          ellipsis: true
        },
        // 措施状态
        {
          title: "measure-track.measure-track.measure-status",
          width: 150,
          align: "center",
          visible: true,
          dataIndex: "measuresState",
          scopedSlots: { customRender: "measuresState" },
          ellipsis: true
        },
        // 措施类型
        {
          title: "measure-track.measure-track.measure-type",
          width: 150,
          visible: true,
          align: "center",
          dataIndex: "actionType",
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: value == '09' ? this.$t("global-dict.prevent") : this.$t("global-dict.detect"),
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
        },
        // 措施是否分发
        {
          title: "measure-track.measure-track.handOut",
          width: 150,
          visible: true,
          align: "center",
          dataIndex: "distributeStatus",
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: row.distributeStatus == "0" ? this.$t("global-dict.undistributed") : this.$t("global-dict.distributed"),
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
        },
        // 措施
        {
          title: "measure-track.measure-track.measure",
          width: 250,
          visible: true,
          align: "center",
          dataIndex: "actionName",
          ellipsis: true,
          scopedSlots: { customRender: 'actionName' },
          customRender: (text, record, index) => {
            let secondName = record.secondActionName;
            if (secondName == null || secondName === record.actionName) {
              secondName = "";
            }
            let child = this.$createElement('div', {
              domProps: {
                innerHTML: record.actionName + '<br>' + secondName
              }
            })
            const obj = {
              children: child,
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, record, index);
            return obj;
          }
        },
        // 失效
        {
          title: "measure-track.measure-track.failure",
          width: 250,
          visible: true,
          align: "center",
          dataIndex: "fault",
          ellipsis: true,
          scopedSlots: { customRender: 'faultName' },
          customRender: (text, record) => {
            let secondName = record.secondFaultName;
            if (secondName == null || secondName === record.fault) {
              secondName = "";
            }
            let child = this.$createElement('div', {
              domProps: {
                innerHTML: record.fault + '<br>' + secondName
              }
            })
            return {
              children: child
            }
          }
        },
        // 功能
        {
          title: "measure-track.measure-track.function",
          width: 250,
          visible: true,
          align: "center",
          dataIndex: "function",
          ellipsis: true,
          scopedSlots: { customRender: 'functionName' },
          customRender: (text, record) => {
            // 要求规格
            let requireSpecs = record.requireSpecs == null ? "" : '&nbsp;' + record.requireSpecs;
            // 要求名称
            let requireName = record.require == null ? "" : '&nbsp;' + "（" + record.require + requireSpecs + "）";
            // 第二语言要求名称
            let secondRequireName = record.secondRequireName == null ? "" : '&nbsp;' + "（" + record.secondRequireName + requireSpecs + "）";
            // 产品特性规格
            let productSpecs = record.productSpecs == null ? "" : '&nbsp;' + record.productSpecs;
            // 第二语言功能名称
            let secondFucntionName = record.secondFunctionName;
            // 判断第二语言与当前语言是否相同。相同不显示第二语言；不相同显示第二语言
            if (secondFucntionName == null || secondFucntionName === record.function) {
              secondFucntionName = "";
            } else {
              secondFucntionName = record.secondFunctionName + productSpecs + secondRequireName;
            }
            let child = this.$createElement('div', {
              domProps: {
                innerHTML: record.function + productSpecs + requireName + '<br>' + secondFucntionName
              }
            })
            return {
              children: child
            }
          }
        },
        // 结构
        {
          title: "measure-track.measure-track.structure",
          width: 250,
          visible: true,
          align: "center",
          dataIndex: "stru",
          ellipsis: true,
          scopedSlots: { customRender: 'structName' },
          customRender: (text, record) => {
            let secondName = record.secondStruName;
            if (secondName == null || secondName === record.stru) {
              secondName = "";
            }
            let child = this.$createElement('div', {
              domProps: {
                innerHTML: record.stru + '<br>' + secondName
              }
            })
            return {
              children: child
            }
          }
        },
        // 上级结构
        {
          title: "measure-track.measure-track.superior-structure",
          width: 250,
          visible: true,
          align: "center",
          dataIndex: "parentStruName",
          ellipsis: true,
          customRender: (text, record) => {
            return record.parentStruName !== null ? record.parentStruName : "--";
          }
        },
        // 规划日期
        {
          title: "measure-track.measure-track.plan-date",
          width: 150,
          visible: true,
          align: "center",
          dataIndex: "planDate",
          customRender: (value, row, index) => {
            const obj = {
              children: (
                <a-date-picker
                  style="width: 100%"
                  value={row.planDate ? moment(row.planDate).format('YYYY-MM-DD') : null}
                  disabled={row.distributeStatus == 1}
                  onChange={(value) => this.tableDataChange(value, row, 'planDate')}>
                </a-date-picker>
              ),
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
          ellipsis: true
        },
        // 负责人
        {
          title: "measure-track.measure-track.responsible-person",
          width: 150,
          visible: true,
          align: "center",
          dataIndex: "responsible",
          ellipsis: true,
          customRender: (value, row, index) => {
            let _that = this;
            let option = _that.responsibles.map((item) => (
              <a-select-option key={item.userId} value={item.userName}>
                {item.userName}
              </a-select-option>
            ))
            const obj = {
              children: (
                <a-select
                  style="width: 100%"
                  allowClear
                  value={row.responsible}
                  disabled={row.distributeStatus == 1}
                  onChange={(value) => this.tableDataChange(value, row, 'responsible')}>
                  {option}
                </a-select>
              ),
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
        },
        // 状态
        {
          title: "measure-track.measure-track.status",
          width: 150,
          visible: true,
          align: "center",
          dataIndex: "state",
          ellipsis: true,
          customRender: (value, row, index) => {
            let _that = this;
            let option = _that.stateDict.map((item) => (
              <a-select-option key={item.value} value={item.value}>
                {item.name}
              </a-select-option>
            ))
            const obj = {
              children: (
                <a-select
                  style="width: 100%"
                  allowClear
                  value={row.state}
                  disabled={row.distributeStatus == 1}
                  onChange={(value) => this.tableDataChange(value, row, 'state')}>
                  {option}
                </a-select>
              ),
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
        },
        // 开始日期
        {
          title: "measure-track.measure-track.start-date",
          width: 150,
          visible: true,
          align: "center",
          dataIndex: "startDate",
          customRender: (value, row, index) => {
            const obj = {
              children: (
                <a-date-picker
                  style="width: 100%"
                  value={value ? moment(value).format('YYYY-MM-DD') : null}
                  disabled={row.distributeStatus == 1}
                  onChange={(value) => this.tableDataChange(value, row, 'startDate')}>
                </a-date-picker>
              ),
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
          ellipsis: true
        },
        // 完成日期
        {
          title: "measure-track.measure-track.complete-date",
          width: 150,
          visible: true,
          align: "center",
          dataIndex: "completeDate",
          customRender: (value, row, index) => {
            const obj = {
              children: (
                <a-date-picker
                  style="width: 100%"
                  value={value ? moment(value).format('YYYY-MM-DD') : null}
                  disabled={row.distributeStatus == 1}
                  onChange={(value) => this.tableDataChange(value, row, 'completeDate')}
                  >
                </a-date-picker>
              ),
              attrs: {},
            };
            // 这里设置的是表格体的合并
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
          ellipsis: true
        },
        // S1
        {
          title: "measure-track.measure-track.s1",
          width: 50,
          visible: true,
          align: "center",
          dataIndex: "s1",
          sorter: (a, b) => a.s1 - b.s1,
          ellipsis: true
        },
        // O1
        {
          title: "measure-track.measure-track.o1",
          width: 50,
          visible: true,
          align: "center",
          dataIndex: "o1",
          sorter: (a, b) => a.o1 - b.o1,
          ellipsis: true
        },
        // D1
        {
          title: "measure-track.measure-track.d1",
          width: 50,
          visible: true,
          align: "center",
          dataIndex: "d1",
          sorter: (a, b) => a.d1 - b.d1,
          ellipsis: true
        },
        // RPN1
        {
          title: "measure-track.measure-track.rpn1",
          width: 80,
          visible: true,
          align: "center",
          dataIndex: "rpn1",
          sorter: (a, b) => a.rpn1 - b.rpn1,
          ellipsis: true
        },
        // AP1
        {
          title: "measure-track.measure-track.ap1",
          width: 60,
          visible: true,
          align: "center",
          dataIndex: "ap1",
          customCell: (record, index) => {
            let style = {};
            switch (record.ap1) {
              case "H":
                style = { "background-color": "#fec7cd" };
                break;
              case "M":
                style = { "background-color": "#ffeb9c" };
                break;
              case "L":
                style = { "background-color": "#c6efcd" };
                break;
            }
            return { style: style };
          },
          /** 按照字母 [空值、L、M、H] 排序 */
          sorter: (a, b) => {
            a = a.ap1 ? this.getAPSortRule(a.ap1) : 0;
            b = b.ap1 ? this.getAPSortRule(b.ap1) : 0;
            return a - b;
          },
          ellipsis: true
        },
        // S2
        {
          title: "measure-track.measure-track.s2",
          width: 50,
          visible: true,
          align: "center",
          dataIndex: "s2",
          sorter: (a, b) => a.s2 - b.s2,
          ellipsis: true
        },
        // O2
        {
          title: "measure-track.measure-track.o2",
          width: 50,
          visible: true,
          align: "center",
          dataIndex: "o2",
          sorter: (a, b) => a.o2 - b.o2,
          ellipsis: true
        },
        // D2
        {
          title: "measure-track.measure-track.d2",
          width: 50,
          visible: true,
          align: "center",
          dataIndex: "d2",
          sorter: (a, b) => a.d2 - b.d2,
          ellipsis: true
        },
        // RPN2
        {
          title: "measure-track.measure-track.rpn2",
          width: 80,
          visible: true,
          align: "center",
          dataIndex: "rpn2",
          sorter: (a, b) => a.rpn2 - b.rpn2,
          ellipsis: true
        },
        // AP2
        {
          title: "measure-track.measure-track.ap2",
          width: 60,
          visible: true,
          align: "center",
          dataIndex: "ap2",
          customCell: (record, index) => {
            let style = {};
            switch (record.ap2) {
              case "H":
                style = { "background-color": "#fec7cd" };
                break;
              case "M":
                style = { "background-color": "#ffeb9c" };
                break;
              case "L":
                style = { "background-color": "#c6efcd" };
                break;
            }
            return { style: style };
          },
          /** 按照字母 [空值、L、M、H] 排序 */
          sorter: (a, b) => {
            a = a.ap2 ? this.getAPSortRule(a.ap2) : 0;
            b = b.ap2 ? this.getAPSortRule(b.ap2) : 0;
            return a - b;
          },
          ellipsis: true
        },
        // 采取基于证据的措施
        {
          title: "measure-track.take-evidence-based-measures",
          width: 200,
          visible: true,
          align: "center",
          dataIndex: "description",
          ellipsis: true,
          customRender: (value, row, index) => {
            const obj = {
              children: (
                <a-input
                  style="width: 100%"
                  maxLength={500}
                  value={row.description ? row.description : null}
                  disabled={row.distributeStatus == 1}
                  onChange={(value) => this.tableDataChange(value, row, 'description')}>
                </a-input>
              ),
              attrs: {},
            };
            obj.attrs.rowSpan = mergeCells(this.tableData, row, index);
            return obj;
          },
        }
      ],
      // 复选框控制的状态
      columnVisibilities: {
        index: true,
        measuresState: true,
        actionType: true,
        distributeStatus: true,
        actionName: true,
        fault: true,
        function: true,
        stru: true,
        parentStruName: true,
        planDate: true,
        responsible: true,
        state: true,
        startDate: true,
        completeDate: true,
        s1: true,
        o1: true,
        d1: true,
        rpn1: true,
        ap1: true,
        s2: true,
        o2: true,
        d2: true,
        rpn2: true,
        ap2: true,
        description: true
        // 对应更多列...
      },
      startDrag: false,
      editColumnVisibilities: [],
      sortedColumns: [], // 用于拖拽的列数组
      /** 表格分页 */
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页条数
        showTotal: total =>
          this.$t("global-constant.table.show-total", [total]), // 用于显示数据总量和当前数据顺序
        showSizeChanger: true, // 是否可以改变 pageSize
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 指定每页可以显示多少条
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // pageSize 变化的回调
        total: 0 // 总条数
      },
      /** 指定选中项的：key数组 */
      selectedRowKeys: [],
      /** 指定选中项的：数组数据 */
      selectedRows: [],
      /** 表格Loading */
      tableLoading: false,
      /** 保存Loading */
      saveLoading: false,
      /** 顶部表格列数据 */
      topTableColumns: [],
      /** 左侧表格列数据 */
      leftTableColumn: {},
      /** 表格数据 */
      funNet: [],
      /** 左侧树数据 */
      leftTreeData: [],
      /** 左侧树选中ID */
      leftTreeSelectIds: [],
      /** 功能数据字典 */
      funData: [],
      /** 失效数据字典 */
      failData: [],
      /** 措施数据字典 */
      actionData: [],
      /** 替换 treeNode 中 title,key,children,value 字段为 treeData 中对应的字段 */
      replaceFields: {
        children: "children",
        label: "name",
        key: "id",
        value: "id"
      },
      /** 左侧(受控)展开指定的树节点 */
      leftTreeExpandedKeys: [],
      /** 右侧(受控)展开指定的树节点 */
      rightTreeExpandedKeys: [],
      /** 规划日期 */
      planDate: undefined,
      /** 开始日期 */
      startDate: undefined,
      /** 完成日期 */
      completeDate: undefined,
      /** 检索条件 */
      searchParams: {
        /** FMEA标识 */
        fmeaId: this.$store.getters.rfmeaId,
        /** 结构字符串 */
        struIds: undefined,
        /** 功能标识 */
        functionStruIds: [],
        /** 失效标识 */
        failStruIds: [],
        /** 措施标识 */
        actionStruIds: [],
        /** 查询节点标志 0：功能 1：失效 2：措施 */
        struFlag: undefined,
        /** 下级字符串 */
        childStruIds: undefined,
        /** 措施类型 */
        actionType: undefined,
        /** 状态 */
        state: undefined,
        /** 措施状态 */
        actionState: undefined,
        /** 规划日期 */
        planSDate: undefined,
        planEDate: undefined,
        /** 开始日期 */
        startSDate: undefined,
        endEDate: undefined,
        /** 完成日期 */
        completeSDate: undefined,
        completeEDate: undefined,
        /** 负责人 */
        userId: undefined,
        /** 0：负责人为空 1：负责人不为空 */
        userEmptyFlag: undefined,
        /** 0 未分发 1 已分发 */
        distributeStatus: undefined,
        /** 分页 */
        pageCurrent: 1,
        pageSize: 10,
        /** 第二语言 */
        twoLanguage: undefined,
      },
      /** 编辑：模态框 */
      showEditModal: false,
      /** 复选框选中的节点ID数组 */
      selectStruIds: [],
      /** 批量修改表格数据 */
      batchUpdateTableData: [],
      advanceExpand: false,
      /** 第二语言 */
      secondLanguages: [],
      /** 第二语言Loading */
      secondLanguageLoading: false,
      // 全部的数据
      allTableData: [],
      /** 表格高度 */
      tableHeightValue: window.innerHeight - 420,
      chartHeight: null,
      pageTableId: undefined
    };
  },
  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], []);
          }
        });
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    window.addEventListener("resize", this.watchMeasureTrackResize);
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.watchMeasureTrackResize);
    });
    this.getLeftSelectTree();
    this.getResponsible();
    this.list();
    this.getLanguageList();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
    window.onresize = () => {
      this.tableHeightValue = window.innerHeight - 420;
    };
    this.initTableColumns();
    this.handleResize();
  },
  methods: {
    /**
     * 初始化加载已保存的表格列顺序及显隐
     */
    async initTableColumns() {
      // 获取用户信息，如果当前组件的userInfo为空，则从localStorage中获取
      let userInfo = JSON.parse(localStorage.getItem('userInfo'));
      try {
        // 调用接口获取表格列数据
        let res = await this.$api.getTableColumnsData({
          userId: userInfo.userId,
          pagePath: '/dfmea/measureTrack',
          pageName: 'dfmea:measureTrack'
        });
        // 如果接口返回成功
        if (res.flag) {
          // 如果返回的数据中包含当前表格的配置映射，并且映射中有数据
          if (res.data.currentTableConfigMap && Object.keys(res.data.currentTableConfigMap).length > 0) {
            // 获取当前表格的配置信息
            let tableConfig = res.data.currentTableConfigMap['page-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.copyCustomRender(this.sortedColumns);
              // 解析表格列显示状态
              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.copyCustomRender(this.sortedColumns);
              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.copyCustomRender(this.sortedColumns);
            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 columns 列配置数组
     * @returns 无返回值
     */
    copyCustomRender(columns) {
      if (columns && columns.length > 0) {
        // 遍历传入的列数组
        columns.forEach(column => {
          // 在当前组件的tableColumns数组中查找与传入列dataIndex相同的项
          let oldColumns = this.tableColumns.find(item => item.dataIndex === column.dataIndex);
          if (oldColumns) {
            // 如果找到了相同的项，则复制其自定义渲染函数到传入列的customRender属性中
            column.customRender = oldColumns.customRender;
          }
        });
      }
    },
    /**
     * 移动事件处理函数
     *
     * @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: '/dfmea/measureTrack',
        // 页面名称
        pageName: 'dfmea:measureTrack',
        // 表格列信息，转为JSON字符串
        tableColumns: JSON.stringify(newSortedColumns),
        // 表格列可见性信息，转为JSON字符串
        tableVisibilities: JSON.stringify(this.editColumnVisibilities),
        // 表格id
        tableId: 'page-table'
      };
      // 调用API保存表格配置
      this.$api.saveTableConfig(data).then(res => {
        // 如果返回结果中的flag为true，表示保存成功
        if (res.flag) {
          // 显示成功提示信息
          this.$message.success(res.message, 1);
          // 重新初始化数据
          this.list();
        } else {
          // 显示错误提示信息
          this.$message.error(res.message, 1);
        }
      }).finally(() => {
        // 重新初始化数据
        this.list();
      });
    },
    /**
     * 处理表格列显隐复选框变化事件
     *
     * @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 + 45 = 109，其他页边距需根据每个页面布局自行计算
			this.chartHeight = height -125;
      $("#grid-card").height(this.chartHeight - searchCardHeight - 40);
      this.tableHeightValue = this.chartHeight - searchCardHeight - 222;
      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], []);
      }
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal() {
      this.columnsWidth = this.tableColumns.reduce((sum, column) => sum + column.width, 0);
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed() {
      if (this.columnsWidth <= this.tableWidth) {
        // 遍历 Columns 数组，将有 fixed 属性的元素的 fixed 值设置为 false（当有固定列时，列宽总和小于表格总宽度时会串行）
        this.tableColumns.forEach((column) => {
          if (column.fixed) {
            column.fixed = false;
          }
        });
        // 获取除最后一列以外其他列的宽度总和
        let otherColumnsWidth = this.tableColumns.slice(0, -1).reduce((total, column) => {
          return total + column.width;
        }, 0);
        // 将最后一列的宽度设置为剩余宽度，避免页面表头与内容显示串行
        this.tableColumns[this.tableColumns.length - 1].width = this.tableWidth - otherColumnsWidth;
      } else {
        // 恢复最后一列原始宽度
        this.tableColumns[this.tableColumns.length - 1].width = 150;
      }
    },
    // 收起/展开
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
      this.$nextTick(()=>{
        this.handleResize();
      })
    },
    /**
     * 监听窗口大小调整
     */
    watchMeasureTrackResize() {
    },
    /**
     * 刷新左侧树
     */
    initLeftTree() {
      this.$emit("initLeftTree");
    },
    /**
     * 刷新右侧树
     */
    initRightTree() {
      this.$emit("initRightTree");
    },
    /**
     * 关闭模态框
     */
    closeModal() {
      this.$emit("closeModal");
    },
    /**
     * 左侧输入项筛选
     * @param inputValue
     * @param treeNode
     */
    leftFilterTreeNode(inputValue, treeNode) {
      return treeNode.data.props.name.includes(inputValue);
    },
    /**
     * 取得AP排序规则
     */
    getAPSortRule(val) {
      switch (val) {
        case "L":
          return 1;
        case "M":
          return 2;
        case "H":
          return 3;
      }
    },
    /**
     * Excel导出
     */
    async excelExport() {
      // 查询表格列配置信息
      let userInfo = JSON.parse(localStorage.getItem('userInfo'));
      let tableConfigData = {
        userId: userInfo.userId,
        pagePath: '/dfmea/measureTrack',
        pageName: 'dfmea:measureTrack'
      };
      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['page-table'];
            if (tableConfig) {
              this.pageTableId = tableConfig.id;
            }
          }
        }
      });

      let struIds = '';
      if (this.searchParams.struIds && this.searchParams.struIds.length > 0) {
        this.searchParams.struIds.forEach(item => {
          struIds += item.value + ","
        })
        struIds = struIds.slice(0, -1);
      }

      this.$refs.exportModal.formData = {
        struIds: struIds || "",
        struFlag: this.searchParams.struFlag || "",
        childStruIds: this.searchParams.childStruIds || "",
        actionType: this.searchParams.actionType || "",
        state: this.searchParams.state || "",
        actionState: this.searchParams.actionState || "",
        planSDate: this.searchParams.planSDate || "",
        planEDate: this.searchParams.planEDate || "",
        startSDate: this.searchParams.startSDate || "",
        endEDate: this.searchParams.endEDate || "",
        completeSDate: this.searchParams.completeSDate || "",
        completeEDate: this.searchParams.completeEDate || "",
        userId: this.searchParams.userId || "",
        userEmptyFlag: this.searchParams.userEmptyFlag || "",
        twoLanguage: this.searchParams.twoLanguage || "",
        distributeStatus: this.searchParams.distributeStatus || ""
      };

      this.$refs.exportModal.tableId = this.pageTableId;
      this.$refs.exportModal.visible = true;
    },
    /**
     * 编辑
     */
    edit() {
      let _that = this;
      if (_that.selectedRows.length === 0) {
        /** 请至少选择一条数据！*/
        _that.$message.warning(
          this.$t("global-message.warn.please-select-a-piece-of-data"),
          1
        );
        return;
      }
      let isEdit = true;
      _that.selectedRows.find(item => {
        if (item.distributeStatus == 1) {
          isEdit = false;
        }
      })
      if (isEdit) {
        _that.showEditModal = true;
        _that.selectStruIds = _that.selectedRows.map(item => item.struId);
      } else {
        _that.$message.warning(this.$t('global-message.warn.is.handling'), 1)
      }
    },
    /**
     * 分发任务
     */
    handOut() {
      let _that = this;
      //用于确定数据是否都未分发
      let isDistributed = true;
      if (_that.selectedRows.length === 0) {
        /** 请至少选择一条数据！*/
        _that.$message.warning(this.$t("global-message.warn.please-select-a-piece-of-data"), 1);
        return;
      }
      _that.selectedRows.find(item => {
        if (item.distributeStatus == 1) {
          isDistributed = false;
        }
      });
      // 校验负责人和计划日期是否为空
      if (_that.batchUpdateTableData && _that.batchUpdateTableData.length > 0) {
        _that.saveBatchAndHandOut(isDistributed);
      } else {
        _that.onHandOut(isDistributed);
      }
    },
    /**
     * 分发任务
     */
    onHandOut(isDistributed) {
      let _that = this;
      if (isDistributed) {
        let struIdList = [];
        let allStruIdList = [];
        let finalStruIdList = [];
        //获取合并数据的第一个
        _that.allTableData.forEach(f => {
          if (!allStruIdList.some(item => item.mergeId == f.mergeId) || f.mergeId == null) {
            allStruIdList.push(f);
          }
        })
        //获取需要合并的数据
        _that.selectedRows.forEach(f => {
          if (!struIdList.some(item => item.mergeId == f.mergeId) || f.mergeId == null) {
            struIdList.push(f);
          }
        })
        struIdList.forEach(item => {
          allStruIdList.forEach(f => {
            if (item.mergeId == f.mergeId && item.mergeId != null) {
              finalStruIdList.push(f);
            }
          })
          if (item.getMergeId == null) {
            finalStruIdList.push(item);
          }
        })
        let data = {
          fmeaId: _that.$store.getters.rfmeaId,
          struIds: Array.from(new Set(finalStruIdList.map(item => item.struId))),
          masterFlag: this.$route.query.from !== 'dfmea'
        };
        this.$api.handOutTasks(data).then(res => {
          if (res.flag) {
            _that.$message.success(res.message, 1);
            this.list();
          } else {
            let errResult = res.message
            if (errResult === "M200010") {
              _that.$message.warning(_that.$t("global-btn.hand-out.no-responsible-person"), 1);
            } else if (errResult === "M200014") {
              _that.$message.warning(_that.$t("global-btn.hand-out.plan-time-earlier-current-date"), 1);
            } else if (errResult === "M200015") {
              _that.$message.warning(_that.$t("global-btn.hand-out.no-plan-date"), 1);
            } else {
              _that.$message.error(res.message, 1);
            }
          }
        });
      } else {
        /** 措施分发失败，存在措施已分发*/
        _that.$message.warning(
          this.$t("measure-track.measure-track.be-distributed"),
          1
        );
      }
    },
    /**
     * 批量保存并自动分发
     */
    saveBatchAndHandOut(isDistributed) {
      let _that = this;
      // 校验
      if (!_that.validateBatchUpdateTableData(true)) return;
      // 处理数据
      let data = _that.handleSaveBatchData();
      _that.saveLoading = true;
      _that.$api.saveBatchMeasureTrack({ editSaveInputs: data }).then(res => {
        if (res.flag) {
          if (isDistributed && _that.selectedRows.length > 0) {
            let struIdList = [];
            let allStruIdList = [];
            let finalStruIdList = [];
            //获取合并数据的第一个
            _that.allTableData.forEach(f => {
              if (!allStruIdList.some(item => item.mergeId == f.mergeId) || f.mergeId == null) {
                allStruIdList.push(f);
              }
            })
            //获取需要合并的数据
            _that.selectedRows.forEach(f => {
              if (!struIdList.some(item => item.mergeId == f.mergeId) || f.mergeId == null) {
                struIdList.push(f);
              }
            })
            struIdList.forEach(item => {
              allStruIdList.forEach(f => {
                if (item.mergeId == f.mergeId && item.mergeId != null) {
                  finalStruIdList.push(f);
                }
              })
              if (item.getMergeId == null) {
                finalStruIdList.push(item);
              }
            })
            let hanOutData = {
              fmeaId: _that.$store.getters.rfmeaId,
              struIds: Array.from(new Set(finalStruIdList.map(item => item.struId))),
              masterFlag: this.$route.query.from !== 'dfmea'
            };
            _that.$api.handOutTasks(hanOutData).then(res => {
              if (res.flag) {
                _that.$message.success(res.message, 1);
                _that.list();
              } else {
                let errResult = res.message
                if (errResult === "M200010") {
                  _that.$message.warning(_that.$t("global-btn.hand-out.no-responsible-person"), 1);
                } else if (errResult === "M200014") {
                  _that.$message.warning(_that.$t("global-btn.hand-out.plan-time-earlier-current-date"), 1);
                } else if (errResult === "M200015") {
                  _that.$message.warning(_that.$t("global-btn.hand-out.no-plan-date"), 1);
                }else {
                  _that.$message.error(res.message, 1);
                }
              }
            });
          }
          _that.cleanBatchUpdateTableData();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false;
      });
    },
    /**
     * 取消分发任务
     */
    cancelDistribution() {
      let _that = this;
      //用于确定数据是否都已分发
      let isDistributed = true;
      if (_that.selectedRows.length === 0) {
        /** 请至少选择一条数据！*/
        _that.$message.warning(this.$t("global-message.warn.please-select-a-piece-of-data"), 1);
        return;
      }
      let struIdList = [];
      let allStruIdList = [];
      let finalStruIdList = [];
      //获取合并数据的第一个
      _that.allTableData.forEach(f => {
        if (!allStruIdList.some(item => item.mergeId == f.mergeId) || f.mergeId != null) {
          allStruIdList.push(f);
        }
      })
      //获取需要合并的数据
      _that.selectedRows.forEach(f => {
        if (!struIdList.some(item => item.mergeId == f.mergeId) || f.mergeId == null) {
          struIdList.push(f);
        }
      })
      struIdList.forEach(item => {
        allStruIdList.forEach(f => {
          if (item.mergeId == f.mergeId && item.mergeId != null) {
            finalStruIdList.push(f);
          }
        })
        if (item.mergeId == null) {
          finalStruIdList.push(item);
        }
      })
      finalStruIdList.find(item => {
        if (item.distributeStatus == 0) {
          isDistributed = false;
        }
      });
      if (isDistributed) {
        let data = {
          struIds: Array.from(new Set(finalStruIdList.map(item => item.struId))),
        };
        this.$api.cancelDistribution(data).then(res => {
          if (res.flag) {
            _that.$message.success(res.message, 1);
            this.list();
          } else {
            let errResult = res.message;
            if (errResult === "M200012") {
              _that.$message.warning(_that.$t("global-btn.hand-out.is-under-approval"), 1);
            } else if (errResult === "M200013") {
              _that.$message.warning(_that.$t("global-btn.hand-out.have-been-executed"), 1);
            } else {
              _that.$message.error(res.message, 1);
            }
          }
        });
      } else {
        /** 措施分发失败，存在措施未分发*/
        _that.$message.warning(
          this.$t("measure-track.measure-track.not-be-distributed"),
          1
        );
      }
    },
    /**
     * 校验批量修改表格数据
     * @param messageFlag 消息是否弹出
     */
    validateBatchUpdateTableData(messageFlag = false) {
      let _that = this;
      let flag = true;
      // 比对表格数据，是否修改，删除与初始表格数据一致的
      for (let i = 0, len = _that.initTableData.length; i < len; i++) {
        let initData = _that.initTableData[i];
        for (let j = _that.batchUpdateTableData.length - 1; j >= 0; j--) {
          let updateData = _that.batchUpdateTableData[j];
          if (
            initData.struId === updateData.struId &&
            dateFormat(initData.planDate) === dateFormat(updateData.planDate) &&
            initData.responsible === updateData.responsible &&
            initData.state === updateData.state &&
            initData.startDate === updateData.startDate &&
            initData.completeDate === updateData.completeDate &&
            initData.description === updateData.description
          ) {
            _that.batchUpdateTableData.splice(j, 1);
            break;
          }
        }
      }
      if (this.batchUpdateTableData.length === 0) {
        /** 表格数据未修改！*/
        if (messageFlag)
          this.$message.warning(
            this.$t("global-message.warn.table-data-not-modified")
          );
        return false;
      }
      return flag;
    },
    /**
     * 刷新表格初始数据
     */
    refreshTableData() {
      this.tableData = JSON.parse(JSON.stringify(this.initTableData));
    },
    /**
     * 清除批量修改表格数据
     */
    cleanBatchUpdateTableData() {
      this.batchUpdateTableData = [];
    },
    /**
     * 处理批量保存数据
     */
    handleSaveBatchData() {
      return this.batchUpdateTableData.map(item => {
        return {
          fmeaId: this.$store.getters.rfmeaId,
          struIds: item.struId,
          state: !['10', '20'].includes(item.state)? item.state: undefined,
          lifeState: ['10', '20'].includes(item.state)? item.state: undefined,
          planDate: Date.parse(item.planDate),
          startDate: item.startDate,
          endDate: item.completeDate,
          description: item.description,
          responsible: item.responsible
            ? this.responsibles.filter(
              res => res.userName === item.responsible
            )[0].userId
            : ""
        };
      });
    },
    /**
     * 批量保存
     */
    saveBatch() {
      let _that = this;
      // 校验
      if (!_that.validateBatchUpdateTableData(true)) return;
      // 处理数据
      let data = _that.handleSaveBatchData();
      _that.saveLoading = true;
      _that.$api.saveBatchMeasureTrack({ editSaveInputs: data }).then(res => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          this.cleanBatchUpdateTableData();
          this.list();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.saveLoading = false;
      });
    },
    /**
     * 搜索
     */
    search() {
      this.pagination.current = 1;
      this.list();
    },
    /**
     * 获取负责人
     */
    getResponsible() {
      let _that = this;
      _that.$api.getTeamMember({ lfmeaId: _that.$store.getters.fmeaId }).then(res => {
        if (res.flag) {
          _that.responsibles = res.data.userList;
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      });
    },
    /**
     * 获取左侧下拉Tree
     */
    getLeftSelectTree() {
      let _that = this;
      _that.$api.getLeftTree({ fmeaId: _that.$store.getters.rfmeaId }).then(res => {
        if (res.flag) {
          _that.struNodeList = res.data.mfmeaStruTreeModels;
          let targetNode = res.data.mfmeaStruTreeModels.filter(item => {
            return item.pid === "00000000000000000000000000000000";
          })[0];
          // 数组转Tree
          let treeData = arrayToTree(targetNode, res.data.mfmeaStruTreeModels);
          _that.addScopedSlots(treeData);
          _that.defaultExpandedAllLTreeKeys(treeData);
          _that.leftTreeData = treeData;
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      });
    },
    /**
     * 获取功能选择数据
     *
     * @param leftIds 左侧ID数组
     * @returns 无返回值
     */
    getFunctionSelectData(leftIds) {
      let _that = this;
      let struTypeCode = ['02', '04', '05'];
      _that.$api
        .getDictByStruTypeCode({
          fmeaId: _that.$store.getters.rfmeaId,
          struIds: leftIds,
          struTypeCode: struTypeCode
        })
        .then(res => {
          if (res.flag) {
            // 功能数据字典
            _that.funData = res.data || [];
          }
        })
        .catch(error => {
          _that.$message.error(error.response.data.message, 1);
        });
    },
    /**
     * 获取失效选择数据
     *
     * @param functionIds functionID数组
     * @returns 无返回值
     */
    getFailSelectData(functionIds) {
      let _that = this;
      let struTypeCode = ['06'];
      _that.$api
        .getDictByStruTypeCode({
          fmeaId: _that.$store.getters.rfmeaId,
          struIds: functionIds,
          struTypeCode: struTypeCode
        })
        .then(res => {
          if (res.flag) {
            // 失效数据字典
            _that.failData = res.data || [];
          }
        })
        .catch(error => {
          _that.$message.error(error.response.data.message, 1);
        });
    },
    /**
     * 获取措施选择数据
     *
     * @param failIds failID数组
     * @returns 无返回值
     */
    getActionSelectData(failIds) {
      let _that = this;
      let struTypeCode = ['09', '10'];
      _that.$api
        .getDictByStruTypeCode({
          fmeaId: _that.$store.getters.rfmeaId,
          struIds: failIds,
          struTypeCode: struTypeCode
        })
        .then(res => {
          if (res.flag) {
            // 失效数据字典
            _that.actionData = res.data || [];
          }
        })
        .catch(error => {
          _that.$message.error(error.response.data.message, 1);
        });
    },
    /**
     * 添加插槽
     */
    addScopedSlots(nodes) {
      for (let i = 0, len = nodes.length; i < len; i++) {
        // 通过vue 自带的$set 给每条数据加上一个名为scopedSlots，值为{title: 'node'}，的插槽
        this.$set(nodes[i], "scopedSlots", {
          title: "treeDataSlot",
          checkable: "checkable"
        });
        if (nodes[i].children && nodes[i].children.length > 0) {
          this.addScopedSlots(nodes[i].children);
        }
      }
      return nodes;
    },
    /**
     * 默认展开左侧树全部节点
     * @param treeData tree绑定数据
     */
    defaultExpandedAllLTreeKeys(treeData) {
      let _that = this;
      for (let i = 0, len = treeData.length; i < len; i++) {
        _that.leftTreeExpandedKeys.push(treeData[i].id);
        if (treeData[i].children && treeData[i].children.length > 0) {
          _that.defaultExpandedAllLTreeKeys(treeData[i].children);
        }
      }
    },
    /**
     * 默认展开右侧树全部节点
     * @param treeData tree绑定数据
     */
    defaultExpandedAllRTreeKeys(treeData) {
      let _that = this;
      for (let i = 0, len = treeData.length; i < len; i++) {
        _that.rightTreeExpandedKeys.push(treeData[i].id);
        if (treeData[i].children && treeData[i].children.length > 0) {
          _that.defaultExpandedAllRTreeKeys(treeData[i].children);
        }
      }
    },
    /**
     * 左侧树图标展开/收起节点时触发
     * @param expandedKeys
     * @param e
     */
    leftTreeExpand(expandedKeys, e) {
      this.leftTreeExpandedKeys = expandedKeys;
    },
    /**
     * 右侧树图标展开/收起节点时触发
     * @param expandedKeys
     * @param e
     */
    rightTreeExpand(expandedKeys, e) {
      this.rightTreeExpandedKeys = expandedKeys;
    },
    // 重置
    reset() {
      this.searchParams.struIds = [];
      this.searchParams.functionStruIds = [];
      this.searchParams.failStruIds = [];
      this.searchParams.actionStruIds = [];
      this.searchParams.struFlag = undefined;
      this.searchParams.childStruIds = [];
      this.searchParams.distributeStatus = undefined;
      this.planDate = undefined;
      this.startDate = undefined;
      this.completeDate = undefined;
      this.searchParams.actionType = undefined;
      this.searchParams.state = undefined;
      this.searchParams.actionState = undefined;
      this.searchParams.planSDate = undefined;
      this.searchParams.planEDate = undefined;
      this.searchParams.startSDate = undefined;
      this.searchParams.endEDate = undefined;
      this.searchParams.completeSDate = undefined;
      this.searchParams.completeEDate = undefined;
      this.searchParams.userId = undefined;
      this.searchParams.userEmptyFlag = undefined;
      this.searchParams.distributeStatus = undefined;
      this.searchParams.twoLanguage = this.desplayNlsTwoLanguage;
      this.funData = [];
      this.failData = [];
      this.actionData = [];

      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.list();
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.tableLoading = true;
      let struIds = '';
      if (this.searchParams.struIds && this.searchParams.struIds.length > 0) {
        this.searchParams.struIds.forEach(item => {
          // struIds.push(item.value);
          struIds += item.value + ","
        })
        struIds = struIds.slice(0, -1);
      }
      let data = {
        struIds: struIds || undefined,
        struFlag: _that.searchParams.struFlag,
        childStruIds: _that.searchParams.childStruIds,
        twoLanguage: _that.searchParams.twoLanguage,
        pageCurrent: _that.pagination.current,
        pageSize: _that.pagination.pageSize,
        fmeaId: this.$store.getters.rfmeaId,
        actionType: _that.searchParams.actionType,
        state: _that.searchParams.state,
        actionState: _that.searchParams.actionState,
        planSDate: _that.searchParams.planSDate,
        planEDate: _that.searchParams.planEDate,
        startSDate: _that.searchParams.startSDate,
        endEDate: _that.searchParams.endEDate,
        completeSDate: _that.searchParams.completeSDate,
        completeEDate: _that.searchParams.completeEDate,
        userId: _that.searchParams.userId,
        userEmptyFlag: _that.searchParams.userEmptyFlag,
        distributeStatus: _that.searchParams.distributeStatus,
      }
      _that.$api
        .getMeasureTrack(data)
        .then(res => {
          if (res.flag) {
            _that.searchParams.twoLanguage = res.data.display_nls;
            _that.desplayNlsTwoLanguage = res.data.display_nls;
            _that.tableData = res.data.mfmeaActionTrackDtos;
            _that.initTableData = JSON.parse(
              JSON.stringify(res.data.mfmeaActionTrackDtos)
            );
            _that.selectedRows = [];
            _that.selectedRowKeys = [];
            _that.pagination.current = res.data.pagination.pageCurrent;
            _that.pagination.pageSize = res.data.pagination.pageSize;
            _that.pagination.total = res.data.pagination.rowTotal;
            _that.allTableData = res.data.allMfmeaActionTrackDtos;
          } else {
            _that.$message.error(res.message, 1);
          }
        })
        .catch(error => {
          _that.$message.error(error.response.data.message, 1);
        })
        .finally(() => {
          _that.secondLanguageLoading = false;
          _that.tableLoading = false;
        });
    },
    /**
     * 单选框改变事件
     */
    radioChange(e) {
      let redioFlag = e.target.value;
      if (redioFlag === 1) {
        this.checkIdShow = false;
        this.sameSuperCheckFlag = false;
      } else if (redioFlag === 2) {
        this.checkIdShow = true;
        this.sameSuperCheckFlag = false;
      } else if (redioFlag === 3) {
        this.checkIdShow = false;
        this.sameSuperCheckFlag = true;
      }
    },
    /**
     * tree 完全受控  选中
     * @param even
     * @param evenT
     * @param evenTR
     */
    selectBtn(even, evenT, evenTR) {
      this.checkedEvet = true; //判断是勾选添加还是删除
      this.currentChecked = evenTR.checkedNodes;
      let i = evenTR.checkedNodes.length - 1;
      this.deepCurrent = evenTR.checkedNodes[i].data.props.deep; // 设置当前选择节点的深度
      this.currentPid = evenTR.checkedNodes[i].data.props.pid; // 设置当前选择节点的父级ID
    },
    /**
     * 左侧树选中事件
     * @param value
     * @param label
     * @param extra
     */
    leftTreeSelectChange(value, label, extra) {
      let _that = this;
      this.searchParams.struIds = value;
      let checkList = [];
      let checkIds = [];
      _that.funData = [];
      _that.failData = [];
      _that.actionData = [];
      _that.searchParams.functionStruIds = [];
      _that.searchParams.failStruIds = [];
      _that.searchParams.actionStruIds = [];
      _that.searchParams.struFlag = undefined;
      if (this.sameSuperCheckFlag == true) {
        //当同父级勾选按钮打开，并且是勾选添加时
        if (this.checkedEvet == true) {
          this.struNodeList.forEach(item => {
            if (item.deep == this.deepCurrent && item.pid == this.currentPid) checkList.push(item);
          });
          checkList.forEach(item => {
            let ids = {
              lable: item.name,
              value: item.id,
            }
            checkIds.push(ids);
          });
          let result = checkIds.concat(this.searchParams.struIds);
          let arrayResult = result.filter((currentValue, currentIndex, selfArr) => {
            return selfArr.findIndex(item => item.value === currentValue.value) === currentIndex;
          });
          this.searchParams.struIds = arrayResult;
          // 暂存选中数据，取消勾选时使用
          this.currentChecked = arrayResult;
          // 查询对应功能
          let struIds = [];
          for (let i = 0; i < arrayResult.length; i++) {
            struIds.push(arrayResult[i].value);
          }
          _that.getFunctionSelectData(struIds);
        } else {
          //当同父级勾选按钮打开，并且是勾选取消时
          // 对比数组，找到当前勾选的层级
          let arr1 = this.currentChecked.filter(item => {
            return !this.searchParams.struIds.find(prop => {
              return prop.value == item.value
            })
          });
          let currentUnCheckedNode = this.struNodeList.filter(item => {
            return item.id === arr1[0].value;
          })
          this.deepCurrent = currentUnCheckedNode[0] ? currentUnCheckedNode[0].deep : undefined;
          this.currentPid = currentUnCheckedNode[0] ? (currentUnCheckedNode[0].pid ? currentUnCheckedNode[0].pid : undefined) : undefined;
          //根据当前勾选的层级，找到所有相同的层级
          this.struNodeList.forEach(item => {
            if (item.deep == this.deepCurrent && item.pid == this.currentPid) checkList.push(item);
          });
          checkList.forEach(item => {
            let ids = {
              lable: item.name,
              value: item.id,
            }
            checkIds.push(ids);
          });
          //把找到相同数据的层级从勾选的数据中删除
          const result = this.searchParams.struIds.filter((itemA) => {
            return !checkIds.some((itemB) => itemA.value == itemB.value);
          })
          this.searchParams.struIds = result;
          this.currentChecked = result;
          // 取消时下级下拉选恢复根节点查询
          _that.leftTreeSelectIds = [];
          let targetNode = _that.leftTreeData.filter(item => {
            return item.pid === "00000000000000000000000000000000";
          })[0];
          let struIds = [];
          struIds.push(targetNode.id);
          _that.getFunctionSelectData(struIds);
        }
      } else if (this.checkIdShow == true) {
        //当同级勾选按钮打开，并且是勾选添加时
        if (this.checkedEvet == true) {
          this.struNodeList.forEach(item => {
            if (item.deep == this.deepCurrent) checkList.push(item);
          });
          checkList.forEach(item => {
            let ids = {
              lable: item.name,
              value: item.id,
            }
            checkIds.push(ids);
          });
          let result = checkIds.concat(this.searchParams.struIds);
          let arrayResult = result.filter((currentValue, currentIndex, selfArr) => {
            return selfArr.findIndex(item => item.value === currentValue.value) === currentIndex;
          });
          this.searchParams.struIds = arrayResult;
          // 暂存选中数据，取消勾选时使用
          this.currentChecked = arrayResult;
          // 查询对应功能
          let struIds = [];
          for (let i = 0; i < arrayResult.length; i++) {
            struIds.push(arrayResult[i].value);
          }
          _that.getFunctionSelectData(struIds);
        } else {
          //当同级勾选按钮打开，并且是勾选取消时
          // 对比数组，找到当前勾选的层级
          let arr1 = this.currentChecked.filter(item => {
            return !this.searchParams.struIds.find(prop => {
              return prop.value == item.value
            })
          });
          let currentUnCheckedNode = this.struNodeList.filter(item => {
            return item.id === arr1[0].value;
          })
          this.deepCurrent = currentUnCheckedNode[0] ? currentUnCheckedNode[0].deep : undefined;
          this.currentPid = currentUnCheckedNode[0] ? (currentUnCheckedNode[0].pid ? currentUnCheckedNode[0].pid : undefined) : undefined;
          //根据当前勾选的层级，找到所有相同的层级
          this.struNodeList.forEach(item => {
            if (item.deep == this.deepCurrent) checkList.push(item);
          });
          checkList.forEach(item => {
            let ids = {
              lable: item.name,
              value: item.id,
            }
            checkIds.push(ids);
          });
          //把找到相同数据的层级从勾选的数据中删除
          const result = this.searchParams.struIds.filter((itemA) => {
            return !checkIds.some((itemB) => itemA.value == itemB.value);
          })
          this.searchParams.struIds = result;
          this.currentChecked = result;
          // 取消时下级下拉选恢复根节点查询
          _that.leftTreeSelectIds = [];
          let targetNode = _that.leftTreeData.filter(item => {
            return item.pid === "00000000000000000000000000000000";
          })[0];
          let struIds = [];
          struIds.push(targetNode.id);
          _that.getFunctionSelectData(struIds);
        }
      } else {
        let struIds = [];
        if (value.length > 0) {
          for (let i = 0; i < value.length; i++) {
            struIds.push(value[i].value);
          }
          this.searchParams.struIds = value;
          // 查询对应功能
          _that.getFunctionSelectData(struIds);
        }
      }
      this.checkedEvet = false;
    },
    /**
     * 功能选中事件
     * @param value
     * @param option
     */
    functionSelectChange(value, option) {
      this.searchParams.functionStruIds = value;
      this.searchParams.childStruIds = value.join(",");
      this.searchParams.struFlag = '0';
      this.searchParams.failStruIds = [];
      this.searchParams.actionStruIds = [];
      // 清空数据字典
      this.failData = [];
      this.actionData = [];
      // 获取失效数据字典
      if (value) {
        this.getFailSelectData(value);
      } else {
        this.searchParams.childStruIds = [];
      }
    },
    /**
     * 失效选中事件
     *
     * @param value 当前选中的值
     * @param option 当前选中的选项对象
     * @returns 无返回值
     */
    failSelectChange(value, option) {
      this.searchParams.failStruIds = value;
      this.searchParams.childStruIds = value.join(",");
      this.searchParams.struFlag = '1';
      this.searchParams.actionStruIds = [];
      // 清空数据字典
      this.actionData = [];
      // 获取措施数据字典
      if (value) {
        this.getActionSelectData(value);
      } else {
        this.searchParams.childStruIds = this.searchParams.functionStruIds.join(",");
      }
    },
    /**
     * 措施选中事件
     *
     * @param value 当前选中的值
     * @param option 当前选中的选项对象
     * @returns 无返回值
     */
    actionSelectChange(value, option) {
      this.searchParams.actionStruIds = value;
      this.searchParams.childStruIds = value.join(",");
      this.searchParams.struFlag = '2';
      if (!value) {
        this.searchParams.childStruIds = this.searchParams.failStruIds.join(",");
      }
    },
    /**
     * 措施类型下拉事件时
     * @param val
     */
    measureTypeChange(val) {
      this.searchParams.actionType = val;
    },
    /**
     * 负责人下拉事件时
     * @param val
     */
    responsibleChange(val) {
      this.searchParams.userId = val;
    },
    /**
     * 负责人下拉筛选点击
     * @param obj
     * @param arr
     */
    responsibleDropDownFilterClick(obj, arr) {
      obj.checked = !obj.checked;
      // 复选框实现单选效果
      if (obj.checked) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].value !== obj.value) arr[i].checked = false;
        }
      }
      this.searchParams.userEmptyFlag = obj.checked ? obj.value : undefined;
    },
    /**
     * 状态下拉事件时
     * @param val
     */
    stateChange(val) {
      this.searchParams.state = val;
    },
    /**
     * 措施分发状态下拉事件时
     * @param val
     */
    measureDistributeStateChange(val) {
      this.searchParams.distributeStatus = val;
    },
    /**
     * 措施状态下拉事件时
     * @param val
     */
    measureStateChange(val) {
      this.searchParams.actionState = val;
    },
    /**
     * 规划日期选择事件时
     * @param date
     * @param dateString
     */
    planDateChange(date, dateString) {
      this.planDate = date;
      this.searchParams.planSDate = dateString[0] || undefined;
      this.searchParams.planEDate = dateString[1] || undefined;
    },
    /**
     * 开始日期选择事件时
     * @param date
     * @param dateString
     */
    startDateChange(date, dateString) {
      this.startDate = date;
      this.searchParams.startSDate = dateString[0] || undefined;
      this.searchParams.startEDate = dateString[1] || undefined;
    },
    /**
     * 完成日期选择事件时
     * @param date
     * @param dateString
     */
    completeDateChange(date, dateString) {
      this.completeDate = date;
      this.searchParams.completeSDate = dateString[0] || undefined;
      this.searchParams.completeEDate = dateString[1] || undefined;
    },
    /**
     * 表格点击分页中数字触发的方法
     * @param pagination 分页
     * @param filters 过滤
     * @param sorter 排序
     * @param currentDataSource 当前数据源
     */
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      let _that = this;
      // 触犯分页时
      if (
        pagination.current !== _that.searchParams.pageCurrent ||
        pagination.pageSize !== _that.searchParams.pageSize
      ) {
        // 是否存在表格数据修改
        if (_that.validateBatchUpdateTableData()) {
          _that.$confirm({
            title: this.$t("global-message.warn"),
            /** 当前页面数据存在修改，是否确认离开？*/
            content: this.$t("global-message.warn.current-page-data-hash-modified.whether-to-leave"),
            okText: this.$t("global-btn.ok"),
            cancelText: this.$t("global-btn.cancel"),
            onCancel() { },
            onOk() {
              // 清除批量修改表格数据
              _that.cleanBatchUpdateTableData();
              // 处理分页
              _that.handlePagination(pagination);
            }
          });
        } else {
          // 处理分页
          _that.handlePagination(pagination);
        }
      }
    },
    /**
     * 处理分页
     */
    handlePagination(pagination) {
      let _that = this;
      _that.pagination.current = pagination.current;
      _that.pagination.pageSize = pagination.pageSize;
      _that.searchParams.pageCurrent = pagination.current;
      _that.searchParams.pageSize = pagination.pageSize;
      _that.list();
    },
    /**
     * 规划日期选择事件时
     * @param value 值
     * @param row 表格行数据
     * @param k 对象属性
     */
    tableDataChange(value, row, k) {
      if (k === 'description') {
        row[k] = value.target.value;
      } else {
        row[k] = value;
      }
      if (this.batchUpdateTableData && this.batchUpdateTableData.length > 0) {
        for (let i = this.batchUpdateTableData.length - 1; i >= 0; i--) {
          if (row.struId === this.batchUpdateTableData[i].struId)
            this.batchUpdateTableData.splice(i, 1);
        }
      }
      this.batchUpdateTableData.push({
        struId: row.struId,
        planDate: row.planDate,
        responsible: row.responsible,
        state: row.state,
        startDate: row.startDate,
        completeDate: row.completeDate,
        description: row.description
      });
    },
    /**
     * 关闭编辑模态框
     */
    closeEditModal() {
      this.showEditModal = false;
    },
    /**
     * 复选框改变事件
     */
    onSelectChange(selectedRowKeys, row) {
      this.selectedRows = row;
      this.selectedRowKeys = selectedRowKeys;
    },

    /**
     * 用户手动选择/取消选择某列的回调
     */
    onSelect(record, selected, selectedRows, nativeEvent) {
      let mergeId = undefined;
      mergeId = record.mergeId;
      let id = record.struId;
      this.selectedRows = Array.from(new Set(this.selectedRows))
      this.selectedRowKeys = Array.from(new Set(this.selectedRowKeys))
      //判断是选中还是取消选中
      if (mergeId != undefined && mergeId != null) {
        if (selected) {
          for (let i = 0; i < this.tableData.length; i++) {
            if (mergeId == this.tableData[i].mergeId && id != this.tableData[i].struId) {
              this.selectedRows.push(this.tableData[i]);
              this.selectedRowKeys.push(i)
            }
          }
        } else {
          //去除选中的数据
          for (let i = 0; i < this.selectedRows.length; i++) {
            if (mergeId == this.selectedRows[i].mergeId) {
              this.selectedRows.splice(i, 1);
              i--;
            }
          }
          //去除选中的状态
          for (let i = 0; i < this.tableData.length; i++) {
            if (mergeId == this.tableData[i].mergeId) {
              for (let j = 0; j < this.selectedRowKeys.length; j++) {
                if (this.selectedRowKeys[j] == i) {
                  this.selectedRowKeys.splice(j, 1);
                }
              }
            }
          }
        }
      }
      this.selectedRows = Array.from(new Set(this.selectedRows))
      this.selectedRowKeys = Array.from(new Set(this.selectedRowKeys))
    },

    /**
     * 行点击事件
     */
    customRow(record, index) {
      let _that = this;
      return {
        on: {
          // 鼠标单击行
          click: () => {
            if (_that.selectedRowKeys.indexOf(index) !== -1) {
              _that.selectedRows.splice(
                _that.selectedRowKeys.indexOf(index),
                1
              );
              _that.selectedRowKeys.splice(
                _that.selectedRowKeys.indexOf(index),
                1
              );
            } else {
              _that.selectedRowKeys.push(index);
              _that.selectedRows.push(record);
            }
          }
        }
      };
    },
    /**
     * 获取第二语言
     */
    getLanguageList() {
      let _that = this;
      _that.secondLanguages = true;
      let data = {};
      Object.assign(data, { fmeaId: _that.$store.getters.rfmeaId });
      data.mfmeaFmeaTableDisplayCtrl = {
        effectDisplayOption: _that.effectDisplayOption
          ? _that.effectDisplayOption
          : "3",
        causeDisplayOption: _that.causeDisplayOption
          ? _that.causeDisplayOption
          : "1"
      };
      _that.$api.getFmeaTable(data).then(res => {
        if (res.flag) {
          _that.searchParams.twoLanguage = res.data.display_nls;
          _that.secondLanguages = res.data.rfmcurrentNls || [];
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch(error => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.secondLanguageLoading = false;
      });
    },
    /**
     * 过滤选项函数
     *
     * @param input 输入的字符串
     * @param option 选项对象
     * @returns 返回一个布尔值，表示选项是否匹配输入的字符串
     */
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
  },
  // 剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style lang="scss">
.ant-select-tree li {
  margin: 2px 0 !important;
}
</style>

<style lang="less" scoped>
/deep/ .ant-select-selection {
  border-top-width: 1px;
}

.function-color {
  color: rgb(66, 167, 94);
}

.productFeature-color {
  color: #5b9bd5;
}

.require-color {
  color: #5b9bd5;
}

.fault-color {
  color: #c84d3c;
}

.scroll {
  overflow-y: auto;
  height: calc(80vh);
}

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

/deep/ .ant-table-small.ant-table-bordered .ant-table-tbody > tr > td:last-child {
  border-right: 1px solid #e8e8e8;
}
</style>
