<template>
  <div ref="scrollableContainer" style="background-color:#f0f2f5;padding:12px;overflow-y: auto;height: 90vh;" class="risk-container">
    <a-spin :spinning="loading">
      <a-row :gutter="24">
        <a-col :xl="5" :lg="5" :md="12" :sm="24" :xs="24">
          <a-card class="card-margin"
                  :title="$t('functional-analysis.top-btn.before-improvement') + ' - ' + $t('functional-analysis.top-btn.sxo-matrix')">
            <div id="before-so-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
        <a-col :xl="5" :lg="5" :md="12" :sm="24" :xs="24">
          <a-card class="card-margin"
                  :title="$t('functional-analysis.top-btn.before-improvement') + ' - ' + $t('functional-analysis.top-btn.sxd-matrix')">
            <div id="before-sd-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
        <a-col :xl="5" :lg="5" :md="12" :sm="24" :xs="24">
          <a-card class="card-margin"
                  :title="$t('functional-analysis.top-btn.before-improvement') + ' - ' + $t('functional-analysis.top-btn.dxo-matrix')">
            <div id="before-do-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
        <a-col :xl="9" :lg="9" :md="12" :sm="24" :xs="24">
          <a-card
              :title="$t('functional-analysis.top-btn.before-improvement') + ' - ' + $t('functional-analysis.top-btn.rmr-matrix')">
            <div id="before-rmr-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :xl="5" :lg="5" :md="12" :sm="24" :xs="24">
          <a-card class="card-margin"
                  :title="$t('functional-analysis.top-btn.after-improvement') + ' - ' + $t('functional-analysis.top-btn.sxo-matrix')">
            <div id="after-so-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
        <a-col :xl="5" :lg="5" :md="12" :sm="24" :xs="24">
          <a-card class="card-margin"
                  :title="$t('functional-analysis.top-btn.after-improvement') + ' - ' + $t('functional-analysis.top-btn.sxd-matrix')">
            <div id="after-sd-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
        <a-col :xl="5" :lg="5" :md="12" :sm="24" :xs="24">
          <a-card class="card-margin"
                  :title="$t('functional-analysis.top-btn.after-improvement') + ' - ' + $t('functional-analysis.top-btn.dxo-matrix')">
            <div id="after-do-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
        <a-col :xl="9" :lg="9" :md="12" :sm="24" :xs="24">
          <a-card
              :title="$t('functional-analysis.top-btn.after-improvement') + ' - ' + $t('functional-analysis.top-btn.rmr-matrix')">
            <div id="after-rmr-matrix-chart" :style="{ height: chartHeight }"></div>
          </a-card>
        </a-col>
      </a-row>
      <a-card :style="{ height: tableHeight }">
        <a-form layout="inline">
          <a-row :gutter="24" class="ml5 mt5 mb5">
          <!-- 下拉选择 Start -->
          <a-form-item :label="$t('risk-analysis.top.filter')">
            <a-select
              v-model="typeValue"
              class="w80 ml10"
              @change="typeSelectChange">
              <a-select-option
                v-for="item in typeDict"
                :key="item.value"
                :value="item.name">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <!-- 符号-->
            <a-select
              v-model="symbolValue"
              :disabled="typeValue === 'AP' || typeValue === '措施状态' || typeValue === 'SXO' || typeValue === 'SXD' || typeValue === 'OXD' || typeValue === 'RMR'"
              class="w60 ml10">
              <a-select-option
                v-for="item in symbolDict"
                :key="item.value"
                :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <!--sod-->
            <a-select
              v-model="numberValue"
              v-show="typeValue === 'S' || typeValue === 'O' || typeValue === 'D'"
              class="w60 ml10">
              <a-select-option
                v-for="item in numberDict"
                :key="item.value"
                :value="item.value">
                {{ item.value }}
              </a-select-option>
            </a-select>
            <!-- AP -->
            <a-select
              v-model="apValue"
              v-show="typeValue === 'AP'"
              class="w60 ml10">
              <a-select-option
                v-for="item in apDict"
                :key="item.value"
                :value="item.name">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <!-- rpn -->
            <a-input
              v-model="rpnInputValue"
              v-show="typeValue === 'RPN'"
              @change="watchRpn"
              class="w60 ml10">
            </a-input>
            <a-select
              v-model="selectedColor"
              v-show="typeValue === 'SXO' || typeValue === 'SXD' || typeValue === 'OXD' || typeValue === 'RMR'"
              class="w80 ml10">
              <a-select-option value=3>
                <span style="backgroundColor: #c84d3c ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
              </a-select-option>
              <a-select-option value=2>
                <span style="backgroundColor: #ff8c00 ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
              </a-select-option>
              <a-select-option value=1>
                <span style="backgroundColor: #42a75e ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
              </a-select-option>
            </a-select>
            <a-select
              v-model="measureState"
              v-show="typeValue === '措施状态'"
              class="w100 ml10">
              <a-select-option
                v-for="item in actionState"
                :key="item.value"
                :value="item.value">
                {{ item.name}}
              </a-select-option>
            </a-select>
          </a-form-item>
          <!-- 搜索框-->
          <a-form-item :label="$t('risk-analysis.top.search')">
            <a-input v-model="nameInputValue" allowClear class="ml10"/>
          </a-form-item>
          <span class="ml10">
            <a-button v-prevent-re-click @click="reset" class="mr10">
              {{ $t('global-btn.reset') }}
            </a-button>
            <!-- 查询-->
            <a-button v-prevent-re-click type="primary" @click="getSearch" :disabled="isSearchDisabled">
              {{ $t('global-btn.search') }}
            </a-button>
          </span>
          <!-- 导出-->
          <span class="fr mr5">
            <a-button class="mr10" @click="excelExport" type="primary">
              {{ $t("global-btn.export") }}
            </a-button>
          </span>
            <div ref="riskMatrix" class="page">
              <div class="riskMatrix-from">
                <!--表格-->
                <a-table
                    ref='tableRef'
                    :components='components'
                    class="mt10"
                    bordered
                    size="small"
                    :rowKey="(record,index) =>{return index}"
                    :columns="tableColumns"
                    :dataSource="tableData"
                    :scroll="{ x: tableWidth, y: tableHeightValue }"
                    :pagination="pagination"
                    @change="handlePagination">
                  <!--序号-->
                  <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, index">
                    {{ record.measureType === "14" ? $t("global-dict.current-measures") : $t("global-dict.optimization-measures") }}
                  </template>
                  <!--失效跳转-->
                  <template slot='faultStru' slot-scope='text, record'>
                    <span class="fmea-code" :key="record.index" @click="toLink(record)">
                      {{ text }}
                    </span>
                  </template>
                  <!--预防措施-->
                  <template slot="preventAction" slot-scope="text">
                    <span v-for="(item, index) in text" :key="index">{{ item }}<br/></span>
                  </template>
                  <!--探测措施-->
                  <template slot="probeAction" slot-scope="text">
                    <span v-for="(item, index) in text" :key= "index">{{ item }}<br/></span>
                  </template>
                </a-table>
              </div>
            </div>
        </a-row>
      </a-form>
      </a-card>
    </a-spin>
  </div>
</template>
<script>

import * as echarts from 'echarts';
import utils from '@/utils/urlParamUtil';
import { getTableHeight } from "@/utils";
import VueDraggableResizable from 'vue-draggable-resizable';
export default {
  name: "RiskMatrix",
  components: {
    VueDraggableResizable
  },
  data() {
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props;
          // 此处的this.tableColumns 是定义的table的表头属性变量
          const col = this.tableColumns.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 {
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      /** 表格高度 */
      tableHeight: window.innerHeight - 350 + 'px',
      tableHeightValue: window.innerHeight - 550,
      loading: false,
      beforeSoMatrixChart: undefined,
      beforeSdMatrixChart: undefined,
      beforeDodMatrixChart: undefined,
      afterSoMatrixChart: undefined,
      afterSdMatrixChart: undefined,
      afterDodMatrixChart: undefined,
      beforeRmrMatrixChart: undefined,
      afterRmrMatrixChart: undefined,
      chartHeight: (window.innerHeight - 500) / 2 + 'px',
      tableColumns: [
        {
          title: () => this.$t('summary-Archive.function-list.serial-number'),
          width: 100,
          align: "center",
          scopedSlots: { customRender: "index" },
          ellipsis: true
        },
        // 结构
        {
          title: () => this.$t('global-constant.contextmenu.equipment'),
          width: 200,
          align: "center",
          dataIndex: "struName",
          ellipsis: true,
        },
        // 功能
        {
          title: () => this.$t('global-constant.contextmenu.function'),
          width: 250,
          align: "center",
          dataIndex: "functionName",
          ellipsis: true
        },
        // 失效
        {
          title: () => this.$t('global-constant.contextmenu.failure'),
          width: 250,
          align: "center",
          dataIndex: "faultName",
          scopedSlots: {
            customRender: 'faultStru',
          },
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-btn.S'),
          width: 80,
          align: "center",
          dataIndex: "maxS",
          sorter: (a, b) => a.maxS - b.maxS,
          ellipsis: true
        },
        // 措施状态
        {
          title: () => this.$t('measure-track.measure-track.measure-status'),
          width: 150,
          align: "center",
          dataIndex: 'measureType',
          scopedSlots: { customRender: "measuresState" },
          ellipsis: true
        },
        // 预防措施
        {
          title: () => this.$t('functional-analysis.top-btn.recycle-bin.preventive-measures'),
          width: 350,
          align: "center",
          dataIndex: 'preventActionList',
          scopedSlots: { customRender: 'preventAction' },
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-btn.O'),
          width: 80,
          align: "center",
          dataIndex: "occurrence",
          sorter: (a, b) => a.occurrence - b.occurrence,
          ellipsis: true
        },
        // 探测措施
        {
          title: () => this.$t('functional-analysis.top-btn.recycle-bin.detection-measures'),
          width: 350,
          align: "center",
          dataIndex: "probeActionList",
          scopedSlots: { customRender: 'probeAction' },
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-btn.D'),
          width: 80,
          align: "center",
          dataIndex: "detection",
          sorter: (a, b) => a.detection - b.detection,
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-btn.AP'),
          width: 80,
          align: "center",
          dataIndex: "apValue",
          ellipsis: true,
          /** 按照字母 [空值、L、M、H] 排序 */
          sorter: (a, b) => {
            a = a.apValue ? this.getAPSortRule(a.apValue) : 0;
            b = b.apValue ? this.getAPSortRule(b.apValue) : 0;
            return a - b;
          },
        },
        {
          title: () => this.$t('functional-analysis.top-btn.RPN'),
          width: 80,
          align: "center",
          dataIndex: "rpnValue",
          sorter: (a, b) => a.rpnValue - b.rpnValue,
          ellipsis: true
        },
        {
          title: () => this.$t('functional-analysis.top-btn.SXO'),
          width: 80,
          align: "center",
          dataIndex: "so",
          sorter: (a, b) => a.soColor - b.soColor,
          customCell: (record, index) => {
            let style = {};
            switch (record.soColor) {
              case 1:
                style = {'background-color': '#42a75e','color': '#42a75e'};
                break;
              case 2:
                style = {'background-color': '#ff8c00','color': '#ff8c00'};
                break;
              case 3:
                style = {'background-color': '#c84d3c','color': '#c84d3c'};
                break;
            }
            return {style: style};
          }
        },
        {
          title: () => this.$t('functional-analysis.top-btn.SXD'),
          width: 80,
          align: "center",
          dataIndex: "sd",
          sorter: (a, b) => a.sdColor - b.sdColor,
          customCell: (record, index) => {
            let style = {};
            switch (record.sdColor) {
              case 1:
                style = {'background-color': '#42a75e','color': '#42a75e'};
                break;
              case 2:
                style = {'background-color': '#ff8c00','color': '#ff8c00'};
                break;
              case 3:
                style = {'background-color': '#c84d3c','color': '#c84d3c'};
                break;
            }
            return {style: style};
          }
        },
        {
          title: () => this.$t('functional-analysis.top-btn.DXO'),
          width: 80,
          align: "center",
          dataIndex: "do",
          sorter: (a, b) => a.doColor - b.doColor,
          customCell: (record, index) => {
            let style = {};
            switch (record.doColor) {
              case 1:
                style = {'background-color': '#42a75e','color': '#42a75e'};
                break;
              case 2:
                style = {'background-color': '#ff8c00','color': '#ff8c00'};
                break;
              case 3:
                style = {'background-color': '#c84d3c','color': '#c84d3c'};
                break;
            }
            return {style: style};
          },
        },
        {
          title: () => this.$t('functional-analysis.top-btn.RMR'),
          width: 80,
          align: "center",
          dataIndex: "rmr",
          sorter: (a, b) => a.rmrColor - b.rmrColor,
          customCell: (record, index) => {
            let style = {};
            switch (record.rmrColor) {
              case 1:
                style = {'background-color': '#42a75e','color': '#42a75e'};
                break;
              case 2:
                style = {'background-color': '#ff8c00','color': '#ff8c00'};
                break;
              case 3:
                style = {'background-color': '#c84d3c','color': '#c84d3c'};
                break;
            }
            return {style: style};
          }
        },
      ],
      tableData:[],
      /** 类型字典 */
      typeDict: [
        {name: "AP", value: 1},
        {name: "S", value: 2},
        {name: "O", value: 3},
        {name: "D", value: 4},
        {name: "RPN", value: 5},
        {name: "SXO", value: 6},
        {name: "SXD", value: 7},
        {name: "RMR", value: 8},
        {name: "措施状态", value: 9}
      ],
      /** 符号字典 */
      symbolDict: [
        {value: '2', name: "="},
        {value: '1', name: ">"},
        {value: '3', name: "<"}
      ],
      /** 数字字典 */
      numberDict: [
        {value: 10},
        {value: 9},
        {value: 8},
        {value: 7},
        {value: 6},
        {value: 5},
        {value: 4},
        {value: 3},
        {value: 2},
        {value: 1}
      ],
      /** AP字典 */
      apDict: [
        {value: 1, name: "H"},
        {value: 2, name: "M"},
        {value: 3, name: "L"}
      ],
      actionState: [
        { value: '14', name: '当前措施' },
        { value: '07', name: '优化措施' }
      ],
      /** 关键字搜索 */
      nameInputValue: "",
      /** 筛选类型 */
      typeValue: "",
      /** 判断类型 */
      symbolValue: "",
      /** 选择的数值 */
      numberValue: "",
      /** ap选择的值 */
      apValue: "",
      /** rpn输入框值 */
      rpnInputValue: "",
      /** 措施状态 */
      measureState: "",
      selectedColor:"",
      /** 查询禁用 */
      isSearchDisabled: false,
      // 点击事件传值
      s: 0,
      o: 0 ,
      d: 0 ,
      rmr: 0,
      do: 0,
      so: 0,
      sd: 0,
      beforeIndex: null,
      checkFlag: 1, // 0:rmr点击事件 1:sod矩阵点击事件 2:搜索框查询条件
      /** 表格分页 */
      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 // 总条数
      },
    };
  },
  mounted() {
    this.initChartsData();
    this.search();
    window.onresize = () => {
      this.chartHeight = (window.innerHeight - 500) / 2 + 'px'
      this.tableHeightValue = window.innerHeight - 550;
      this.tableHeight = window.innerHeight - 350 + 'px';
      this.beforeSoMatrixChart.resize();
      this.beforeSdMatrixChart.resize();
      this.beforeDodMatrixChart.resize();
      this.afterSoMatrixChart.resize();
      this.afterSdMatrixChart.resize();
      this.afterDodMatrixChart.resize();
      this.beforeRmrMatrixChart.resize();
      this.afterRmrMatrixChart.resize();
    }
    window.addEventListener("resize", this.watchFeatureResize);
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.watchFeatureResize);
    });
    this.getTableHeight();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
  },
  watch: {
    // 监控rpn值的变化并根据情况更新按钮状态
    inputValue(newVal) {
      this.isSearchDisabled = !this.watchRpn(newVal);
    },
    tableColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
        });
      },
      deep: true,
      immediate: true
    },
    tableWidth: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
        });
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 获取表格的总宽度
    handleResize() {
      this.tableWidth = this.$refs.tableRef.$el.offsetWidth;
    },
    // 计算表格各列宽度总和
    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].fixed='right';
        // // 恢复最后一列原始宽度
        this.tableColumns[this.tableColumns.length - 1].width = 80;
      }
    },
    /**
     * 取得表格高度
     */
    getTableHeight() {
      this.$nextTick(() => {
        let dom = this.$refs.riskMatrix;
        // 表单高度：from+操作按钮
        let measureTrackFormH = dom.querySelector(".riskMatrix-from")
            .offsetHeight;
        let tableHeight = getTableHeight(dom, measureTrackFormH);
        this.tableHeight = tableHeight;
      });
    },
    /**
     * 监听窗口大小调整
     */
    watchFeatureResize() {
      this.getTableHeight();
    },
    /**
     * 取得AP排序规则
     */
    getAPSortRule(val) {
      switch (val) {
        case "L":
          return 1;
        case "M":
          return 2;
        case "H":
          return 3;
      }
    },
    /**
     * 类型下拉选择改变事件
     */
    typeSelectChange(v) {
      // 点击事件传值置空
      this.s = null;
      this.o = null;
      this.d = null;
      this.so = null;
      this.sd = null;
      this.do = null;
      this.beforeIndex = null;
      // 符号默认等号
      this.symbolValue = "2";
      if (v === "AP") {
        this.apValue = "H";
      } else if (v === "RPN") {
        this.rpnInputValue = "";
      } else if (v === "措施状态") {
        this.measureState = "07"
      } else {
        this.numberValue = 10;
      }
    },
    /**
     * 监听Rpn值
     */
    watchRpn(e) {
      let reg = /^(1000|[1-9]\d{0,2})$/g; // 1-1000正整数
      if (e.target.value.replace(reg, '')) {
        this.$message.warning(this.$t('global-message.warn.rpn.positive-integer'), 1);
        this.isSearchDisabled = true;
        return false;
      }
      this.isSearchDisabled = false;
    },
    handlePagination(pagination) {
      let _that = this;
      _that.pagination.current = pagination.current;
      _that.pagination.pageSize = pagination.pageSize;
      // 点击事件分页
      if (_that.checkFlag === 0 || _that.checkFlag === 1){
        _that.checkSearch();
      }
      // 搜索框查询分页
      if (_that.checkFlag === 2){
        _that.search();
      }
    },
    /**
     * 重置
     */
    reset() {
      this.typeValue = "";
      this.symbolValue = "";
      this.numberValue = undefined;
      this.apValue = "";
      this.rpnInputValue = "";
      this.nameInputValue = "";
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.s = null;
      this.s = null;
      this.o = null;
      this.d = null;
      this.rmr = null;
      this.do = null;
      this.so = null;
      this.sd = null;
      this.beforeIndex = null;
      this.isSearchDisabled = false;
      this.search();
    },
    /**
     * 导出
     */
    excelExport(){
      let _that = this;
      let rfmeaId = this.$store.getters.rfmeaId;
      let maxS = 0;
      let occurrence = 0;
      let detection = 0;
      let soColor = 0;
      let sdColor = 0;
      let doColor = 0;
      let rmrColor = 0;

      // 搜索框sod值
      if (_that.typeValue === 'S' && _that.checkFlag === 2) {
        maxS =  _that.numberValue;
      }
      if (_that.typeValue === 'O' && _that.checkFlag === 2) {
        occurrence =  _that.numberValue;
      }
      if (_that.typeValue === 'D' && _that.checkFlag === 2) {
        detection =  _that.numberValue;
      }

      if( _that.typeValue === 'RMR' && _that.checkFlag === 2){
        rmrColor = _that.selectedColor;
      } else if(_that.checkFlag === 0) {
        this.s = null;
        this.o = null;
        this.d = null;
        soColor = this.so;
        sdColor = this.sd;
        doColor = this.do;
        rmrColor = this.rmr;
        _that.symbolValue = '2';
      }

      if (_that.typeValue === 'SXO' && _that.checkFlag === 2) {
        soColor = _that.selectedColor;
      } else if(_that.checkFlag === 1) {
        maxS = _that.s;
        occurrence = _that.o;
        _that.symbolValue = '2';
      }
      if (_that.typeValue === 'SXD' && _that.checkFlag === 2) {
        sdColor = _that.selectedColor;
      } else if(_that.checkFlag === 1) {
        maxS = _that.s;
        detection = _that.d;
        _that.symbolValue = '2';
      }
      if (_that.typeValue === 'OXD' && _that.checkFlag === 2) {
        doColor = _that.selectedColor;
      } else if(_that.checkFlag === 1) {
        detection = _that.d;
        occurrence = _that.o;
        _that.symbolValue = '2';
      }


      let url =
        this.$api.baseUrl +
        "/DFMEA/rdfmStatisticalAnalysis/RiskReportForm/export?fmeaId=" + rfmeaId
      + "&apValue=" + (_that.typeValue === "AP" ? _that.apValue : '')
      + "&maxS=" + (maxS || '')
      + "&occurrence=" + (occurrence || '')
      + "&detection=" + (detection || '')
      + "&measureType=" + (_that.typeValue === '措施状态' ? _that.measureState : '')
      + "&symbol=" + (_that.symbolValue || '')
      + "&rpnValue=" + (_that.rpnInputValue || '')
      + "&soColor=" + (soColor || '')
      + "&sdColor=" + (sdColor || '')
      + "&doColor=" + (doColor || '')
      + "&rmrColor=" + (rmrColor || '')
      + "&name=" + (_that.nameInputValue || '')
      + "&beforeOrAfter=" + _that.beforeIndex
      window.open(url);
    },

    //点击事件查询
    checkSearch(){
      let _that = this;
      let data = {};
      if (_that.checkFlag === 0){
        data = {
          fmeaId: this.$store.getters.rfmeaId,
          rmrColor: this.rmr || '',
          symbol: "2",
          soColor: this.so,
          sdColor: this.sd,
          doColor: this.do,
          beforeOrAfter: _that.beforeIndex,
          name: ''
        }
      }
      if (_that.checkFlag === 1){
        data = {
          fmeaId: this.$store.getters.rfmeaId,
          maxS: this.s || '',
          occurrence: this.o || '',
          detection: this.d || '',
          symbol: "2",
          beforeOrAfter: _that.beforeIndex,
          name: ''
        }
      }
      this.$api.getRiskTable(data).then(res =>{
        if (res.flag) {
          _that.tableData = res.data.riskReportFormModelList;
          // 点击图表中的数字，滚动条直接滚动到最底部
          let container = this.$refs.scrollableContainer;
          container.scrollTop = container.scrollHeight; // 滚动到最底部
        }
      }).catch(error => {
          _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
          _that.loading = false;
      });
    },
    // 查询按钮绑定功能
    getSearch() {
      this.pagination.current = 1;
      this.search();
    },
    // 初始化查询表单
    search() {
      let _that = this;
      _that.loading = true;
      _that.checkFlag = 2;
        let data = {
          fmeaId: _that.$store.getters.rfmeaId,
          apValue: _that.typeValue === "AP" ? _that.apValue : '',
          maxS: _that.typeValue === 'S' ? _that.numberValue : '',
          occurrence: _that.typeValue === 'O' ? _that.numberValue : '',
          detection: _that.typeValue === 'D' ? _that.numberValue : '',
          measureType: _that.typeValue === '措施状态' ? _that.measureState : '',
          symbol: _that.symbolValue,
          rpnValue: _that.rpnInputValue,
          soColor: _that.typeValue === 'SXO' ? _that.selectedColor : '',
          sdColor: _that.typeValue === 'SXD' ? _that.selectedColor : '',
          doColor:  _that.typeValue === 'OXD' ? _that.selectedColor : '',
          rmrColor: _that.typeValue === 'RMR' ? _that.selectedColor : '',
          name: _that.nameInputValue || ''
        }
        this.$api.getRiskTable(data).then(res =>{
          if (res.flag) {
            _that.tableData = res.data.riskReportFormModelList
          }
        })
          .catch(error => {
            _that.$message.error(error.response.data.message, 1);
          })
          .finally(() => {
            _that.loading = false;
          });
    },
    // 跳转失效节点
    toLink(record){
      this.$api.getCommentsStruId({
        fmeaId: this.$store.getters.rfmeaId,
        struId: record.faultId
      }).then((res) => {
        if (res.data.rdfmStruTree != null) {
          if (!"06, 99".includes(record.structureType)){
            this.$store.dispatch("fmeaTree/set", {
              key: "rightStruIdFromComments",
              value: record.faultId
            });
          }
          this.$store.dispatch("fmeaTree/set", {
            key: "rightParentStruIdFromComments",
            value: res.data.rdfmStruTree.struId
          });
          this.$store.dispatch("fmeaTree/set", {
            key: "leftStruIdFromComments",
            value: res.data.rdfmStruTree.struId
          });
          this.$store.dispatch("fmeaTree/set", {
            key: "commentsParentIds",
            value: res.data.parentIds
          });
          var fmeaId = this.getUrlParam("fmeaId");
          var deriveId = this.getUrlParam("deriveId");
          var rfmeaId = this.getUrlParam("rfmeaId");
          var _from = this.getUrlParam("from");
          let backUrl = utils.getUrlKey('back');
          this.$router.push(
            "/function2" + "?fmeaId=" + fmeaId +
            "&rfmeaId=" + rfmeaId  +
            "&deriveId=" + deriveId +
            "&from=" + _from +
            "&back=" + backUrl +
            '&ntimet=' + new Date().getTime()
          )
        } else {
          this.$message.error(this.$t('global-message.warn.comment.jump.stru'), 1);
        }
      })
    },
    /**
     * 获取路径参数
     * @param paraName
     * @returns {string}
     */
    getUrlParam(paraName) {
      var url = document.location.toString();
      var arrObj = url.split("?");
      if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;
        for (var i = 0; i < arrPara.length; i++) {
          arr = arrPara[i].split("=");
          if (arr != null && arr[0] == paraName) {
            return arr[1];
          }
        }
        return "";
      } else {
        return "";
      }
    },
    // 初始化数据
    initChartsData() {
      let _that = this;
      this.loading = true;
      this.$api.getRiskMatrix({
        fmeaId: _that.$store.getters.rfmeaId,
      }).then(response => {
        if (response && response.data) {
          let resDatas = response.data.faultAnalysisResult;
          this.calcSOD(resDatas);
          // 改善前SO矩阵数据
          let beforeSOChartData = [];
          // 改善前SD矩阵数据
          let beforeSDChartData = [];
          // 改善前DO矩阵数据
          let beforeDOChartData = [];
          // 改善后SO矩阵数据
          let afterSOChartData = [];
          // 改善后SD矩阵数据
          let afterSDChartData = [];
          // 改善后DO矩阵数据
          let afterDOChartData = [];
          for (let i = 0; i < 10; i++) {
            beforeSOChartData.push([]);
            beforeSDChartData.push([]);
            beforeDOChartData.push([]);
            afterSOChartData.push([]);
            afterSDChartData.push([]);
            afterDOChartData.push([]);
            for (let j = 0; j < 10; j++) {
              beforeSOChartData[i][j] = 0;
              beforeSDChartData[i][j] = 0;
              beforeDOChartData[i][j] = 0;
              afterSOChartData[i][j] = 0;
              afterSDChartData[i][j] = 0;
              afterDOChartData[i][j] = 0;
            }
          }

          let beforeRMRData = [];
          let afterRMRData = [];
          let values = [];
          // 构成三维数组表示 3! 的27种可能
          for (let i = 0; i < 3; i++) {
            beforeRMRData.push([]);
            afterRMRData.push([]);
            for (let j = 0; j < 3; j++) {
              beforeRMRData[i].push([]);
              afterRMRData[i].push([]);
              for (let k = 0; k < 3; k++) {
                beforeRMRData[i][j].push(0);
                afterRMRData[i][j].push(0);

                values.push([i, j, k]);
              }
            }
          }

          resDatas.forEach(resData => {
            // 用S O D作为echar的矩阵坐标，坐标从0，0开始因此都要-1
            beforeSOChartData[resData.beforeOptS - 1][resData.beforeOptO - 1]++
            beforeSDChartData[resData.beforeOptS - 1][resData.beforeOptD - 1]++
            beforeDOChartData[resData.beforeOptD - 1][resData.beforeOptO - 1]++
            afterSOChartData[resData.afterOptS - 1][resData.afterOptO - 1]++
            afterSDChartData[resData.afterOptS - 1][resData.afterOptD - 1]++
            afterDOChartData[resData.afterOptD - 1][resData.afterOptO - 1]++
            // 计算RMR矩阵
            let beforeSo = this.calcSOD(resData.beforeOptO - 1, resData.beforeOptS - 1);
            let beforeSd = this.calcSOD(resData.beforeOptD - 1, resData.beforeOptS - 1);
            let beforeOd = this.calcSOD(resData.beforeOptO - 1, resData.beforeOptD - 1);
            beforeRMRData[beforeSo][beforeSd][beforeOd]++
            let afterSo = this.calcSOD(resData.afterOptO - 1, resData.afterOptS - 1);
            let afterSd = this.calcSOD(resData.afterOptD - 1, resData.afterOptS - 1);
            let afterOd = this.calcSOD(resData.afterOptO - 1, resData.afterOptD - 1);
            afterRMRData[afterSo][afterSd][afterOd]++
          })

          this.beforeSoMatrixChart = echarts.init(document.getElementById('before-so-matrix-chart'));
          this.beforeSdMatrixChart = echarts.init(document.getElementById('before-sd-matrix-chart'));
          this.beforeDodMatrixChart = echarts.init(document.getElementById('before-do-matrix-chart'));
          this.afterSoMatrixChart = echarts.init(document.getElementById('after-so-matrix-chart'));
          this.afterSdMatrixChart = echarts.init(document.getElementById('after-sd-matrix-chart'));
          this.afterDodMatrixChart = echarts.init(document.getElementById('after-do-matrix-chart'));

          this.initSODMatrix(this.beforeSoMatrixChart, 0, beforeSOChartData);
          this.initSODMatrix(this.beforeSdMatrixChart, 1, beforeSDChartData);
          this.initSODMatrix(this.beforeDodMatrixChart, 2, beforeDOChartData);
          this.initSODMatrix(this.afterSoMatrixChart, 3, afterSOChartData);
          this.initSODMatrix(this.afterSdMatrixChart, 4, afterSDChartData);
          this.initSODMatrix(this.afterDodMatrixChart, 5, afterDOChartData);

          let resBeforeRMRData = [];
          let resAfterRMRData = [];
          // 三维数组转长度27的数组，为了放置RMR矩阵最下边一排27个数量统计数据
          beforeRMRData.forEach(i => {
            i.forEach(j => {
              j.forEach(k => {
                resBeforeRMRData.push(k);
              })
            })
          })
          afterRMRData.forEach(i => {
            i.forEach(j => {
              j.forEach(k => {
                resAfterRMRData.push(k);
              })
            })
          })
          // RMR的108格子取值 0绿色 1黄色 2红色
          let resValues = [];
          values.forEach((value, index) => {
            let res = Math.max(...value);
            for (let i = 0; i < 4; i++) {
              if (i === 0) {
                resValues.push([index, i, res]);
              } else {
                resValues.push([index, i, value[i - 1]]);
              }
            }
          });

          // RMR矩阵初始化
          this.beforeRmrMatrixChart = echarts.init(document.getElementById('before-rmr-matrix-chart'));
          this.afterRmrMatrixChart = echarts.init(document.getElementById('after-rmr-matrix-chart'));
          // 改善前标识
          let beforeIndex = 0;
          // 改善后标识
          let afterIndex = 1;
          // 27长度的数组需要反向排序，因为在echart上，绿色是在右侧
          this.initRMRMatrix(this.beforeRmrMatrixChart, resBeforeRMRData, resValues, beforeIndex);
          this.initRMRMatrix(this.afterRmrMatrixChart, resAfterRMRData, resValues, afterIndex);
        }
      }).finally(() => {
        _that.loading = false;
      });
    },
    // 初始化SO SD DO矩阵
    initSODMatrix(chart, index, chartData) {
      // 算法算出低、中、高分别用绿、橙、红表示
      const data = [];
      for (let row = 0; row < 10; row++) {
        for (let col = 0; col < 10; col++) {
          let name = chartData[col][row] === 0 ? '' : chartData[col][row];
          data.push({
            value: [col, row, this.calcSOD(row, col)],
            // 实际存的是数量
            name: name
          });
        }
      }
      const xyAxisName = [
        { xName: "S值", yName: "O\n值", yLabel: "O值", resName: "S×O" },
        { xName: "S值", yName: "D\n值", yLabel: "D值", resName: "S×D" },
        { xName: "D值", yName: "O\n值", yLabel: "O值", resName: "D×O" },
        { xName: "S值", yName: "O\n值", yLabel: "O值", resName: "S×O" },
        { xName: "S值", yName: "D\n值", yLabel: "D值", resName: "S×D" },
        { xName: "D值", yName: "O\n值", yLabel: "O值", resName: "D×O" },
      ];
      // 六个SOD矩阵的数值
      let option = {
        tooltip: {
          formatter: function (params) {
            let value = params.data.value;
            let name = params.data.name ? params.data.name : 0;
            return xyAxisName[index].xName + ": " + (value[0] + 1) + '<br>' +
                xyAxisName[index].yLabel + ": " + (value[1] + 1) + '<br>' +
                xyAxisName[index].resName + ": " + (value[0] + 1) * (value[1] + 1) + '<br>' +
                '数量: ' + name;
          }
        },
        grid: {
          top: '10px',
          bottom: '60px',
          right: '12px',
          height: '70%'
        },
        xAxis: {
          name: xyAxisName[index].xName,
          nameLocation: 'center',
          nameGap: 22,
          type: 'category',
          data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
          offset: 1,
          axisLine: {
            lineStyle: {
              color: '#ccc'
            }
          },
        },
        yAxis: {
          name: xyAxisName[index].yName,
          nameLocation: 'center',
          nameGap: 22,
          nameRotate: 0,
          type: 'category',
          data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
          offset: 2,
          axisLine: {
            lineStyle: {
              color: '#ccc'
            }
          },
        },
        visualMap: {
          type: 'piecewise',
          min: -1,
          max: 2,
          splitNumber: 3,
          color: ['#c84d3c', '#ff8c00', '#42a75e'],
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '0px',
          formatter: function (value) {
            // 范围标签显示内容
            return value === -1 ? '低' : value === 0 ? '中' : '高';
          }
        },
        series: [
          {
            type: 'heatmap',
            data: data,
            label: {
              show: true,
              formatter: function (params) {
                return params.data.name;
              },
              color: '#fff'
            },
            itemStyle: {
              borderColor: 'white'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 6,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      chart.setOption(option);
      chart.on('click', function (params) {
        if (params.name !== '') {
          this.checkFlag = 1;
          // SXO矩阵
          if (index === 0 || index === 3) {
            this.d = null;
            this.s = params.data.value[0] + 1;
            this.o = params.data.value[1] + 1;
            // SXD矩阵
          } else if (index === 1 || index === 4) {
            this.o = null;
            this.s = params.data.value[0] + 1;
            this.d = params.data.value[1] + 1;
            // DXO矩阵
          } else {
            this.s = null;
            this.d = params.data.value[0] + 1;
            this.o = params.data.value[1] + 1;
          }
          if (index >= 3){
            this.beforeIndex = "1";
          } else {
            this.beforeIndex = "0";
          }
          // 搜索框的查询条件置空
          this.selectedColor =  null;
          this.rpnInputValue = null;
          this.nameInputValue = null;
          this.typeValue = null;
          this.symbolValue = null;
          // let data = {
          //   fmeaId: this.$store.getters.rfmeaId,
          //   maxS: this.s || '',
          //   occurrence: this.o || '',
          //   detection: this.d || '',
          //   symbol: "2",
          //   // 改善前后
          //   beforeOrAfter: index >= 3 ? "1" : "0"
          // }

          this.checkSearch()
        }
      }.bind(this));
    },
    // 初始化RMR矩阵
    initRMRMatrix(chart, chartData, values, index) {
      let data = [];
      values.forEach(value => {
        data.push({
          name: '',
          value: value
        })
      })
      chartData.forEach((item, index) => {
        let dataIndex = index * 4;
        data[dataIndex].name = item;
      })
      let option = {
        tooltip: {
          show: false
        },
        grid: {
          top: 'center',
          bottom: '60px',
          right: '12px',
          height: '30%'
        },
        xAxis: {
          show: false,
          nameLocation: 'center',
          nameGap: 22,
          type: 'category',
          offset: 1,
          axisLine: {
            lineStyle: {
              color: '#ccc'
            }
          },
        },
        yAxis: {
          nameLocation: 'center',
          nameGap: 22,
          nameRotate: 0,
          type: 'category',
          data: ['RMR', 'S×O', 'S×D', 'D×O'],
          offset: 2,
          axisLine: {
            lineStyle: {
              color: '#ccc'
            }
          },
        },
        visualMap: {
          type: 'piecewise',
          min: -1,
          max: 2,
          splitNumber: 3,
          // categories: ['低', '中', '高'],
          color: ['#c84d3c', '#ff8c00', '#42a75e'],
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '0px',
          formatter: function (value) {
            // 范围标签显示内容
            return value === -1 ? '低' : value === 0 ? '中' : '高';
          }
        },
        series: [
          {
            type: 'heatmap',
            data: data,
            label: {
              show: true,
              formatter: function (params) {
                return params.data.name ? params.data.name : '';
              },
              color: '#fff'
            },
            itemStyle: {
              borderColor: 'white'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 6,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      chart.setOption(option);
      // 点击事件
      chart.on('click', function (params) {
        if (params.name != 0 ) {
          this.checkFlag = 0;
          this.do = null;
          this.so = null;
          this.sd = null;
          // RMR矩阵
          this.rmr =  params.data.value[2] + 1;
          this.beforeIndex = index;
          //选中节点的so值
          this.so = params.data.value[0] + 27;
          if(this.so >= 27 && this.so <= 35){
            this.so = 1;
          } else if (this.so >= 36 && this.so <= 44){
            this.so = 2;
          } else if (this.so >= 45 && this.so <= 53){
            this.so = 3;
          }
          // 选中节点的sd值
          let sd = params.data.value[0] + 1;
          let sdNum = Math.ceil(sd / 3);
          if (sdNum === 3 || sdNum === 6 || sdNum === 9) {
            this.sd = 3;
          } else if (sdNum === 2 || sdNum === 5 || sdNum === 8) {
            this.sd = 2;
          } else {
            this.sd = 1;
          }
          // 选中节点的do值
          this.do = ((params.data.value[0]) % 3) + 1;
          // 搜索框的查询条件置空
          this.selectedColor =  null;
          this.rpnInputValue = null;
          this.nameInputValue = null;
          this.typeValue = null;
          this.symbolValue = null;

          // let data = {
          //   fmeaId: this.$store.getters.rfmeaId,
          //   rmrColor: this.rmr || '',
          //   symbol: "2",
          //   soColor: this.so,
          //   sdColor: this.sd,
          //   doColor: this.do,
          //   beforeOrAfter: index
          // }
          this.checkSearch()
        }
      }.bind(this));
    },
    // 计算SO/SD/DO的结果0：绿色 1：橙色 2：红色
    calcSOD(row, col) {
      let res = 2;
      if (
          row === 0 ||
          (row === 1 && col < 8) ||
          (row === 2 && col < 3) ||
          (row === 3 && col === 0)
      ) {
        // 低风险
        res = 0;
      } else if (
          (row === 1 && col > 7) ||
          (row === 2 && col > 2 && col < 8) ||
          (row === 3 && col > 0 && col < 6) ||
          (col === 0 && row > 3) ||
          (col === 1 && row > 2 && row < 6)
      ) {
        // 中风险
        res = 1;
      }
      return res;
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .card-margin {
  margin-right: -12px;
  margin-bottom: 12px;
}
.fmea-code {
  color: #1890FF !important;
  cursor: pointer !important;
}
/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);
}
</style>