<template>
  <div ref="MaturityEvaluation" class="summary-archive-content">
<!--    <div class="summary-archive-content-card" :style="{ height: chartHeight }">-->
    <a-card>
      <div class="MaturityEvaluation-from">
        <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('fmeamanager.maturity.node')">
                <a-select v-model="gradeCode" @change="nodeChange" :loading="tableLoading"
                  :placeholder="$t('fmeamanager.maturity.please-enter-node')">
                  <a-select-option v-for="(item, index) in evaluationNodeList" :key="index" :value="item">
                    {{ item }}
                  </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('fmeamanager.maturity.total-score')">
                <a-input v-model="mark" disabled />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :sm="24" :xs="24">
              <a-form-item :label="$t('fmeamanager.maturity.evaluation-results')">
                <a-select v-model="evaluationResult" :disabled="true">
                  <a-select-option v-for="(item, index) in resultList" :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('summary-archive.fmea-table.state')">
                <a-select v-model="state" :disabled="true">
                  <a-select-option v-for="(item, index) in stateList" :key="index" :value="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- switch Start -->
            <span class="fr mr15">
              <a-form-item>
                <a-tooltip @click="showMaturityModal" placement="topRight" arrow-point-at-center
                  :overlayStyle="{ width: '100px' }">
                  <template slot="title">
                    {{ $t('summary-archive.maturity.standard') }}
                  </template>
                  <i class="iconfont iconwenhao help-icon" />
                </a-tooltip>
              </a-form-item>
            </span>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card style="border-radius:10px 10px 0px 0px">
      <template slot="extra">
        <a-row class='tr'>
          <a-button @click="excelExport" class="mr10" type="primary">
            {{ $t('global-btn.export') }}
          </a-button>
          <a-button @click="approve" type="primary" :loading="loading"
            :disabled="isLook || this.libraryId === undefined || !this.approveFlag">
            {{ $t('global-btn.submit-approval') }}
          </a-button>
        </a-row>
      </template>
      <div :style="{ height: chartHeight }">
        <a-table ref='tableRef' :components='components' :data-source="maturityTableData" :columns="tableColumns" :rowKey="(row, index) => { return index; }"
                 bordered :disabled="isLook" size="small" :loading="tableLoading"
                 :scroll="{  x: tableWidth, y: tableHeightValue  }" :pagination=false>
          <template slot="sectionNumber" slot-scope="text, record">
            {{ record.sectionNumber + (record.isStar === 0 ? " ★" : "") }}
          </template>
          <template slot="standardId" slot-scope="text,record">
            <a-select v-model="record.standardId" style="width: 90%" @change="() => subMarkChange(record)"
                      :disabled="isLook" :allowClear="judgeIsClear(record)">
              <a-select-option v-for="item in subMatkList" :key="item.id" :value="item.id">
                {{ item.scoreCode }}
              </a-select-option>
            </a-select>
          </template>
          <template slot="indentify" slot-scope="text, record, index">
            <a-textarea autoSize style="width: 90%" :maxLength="80" v-model="record.indentify" :disabled="isLook"
                        @blur="handleCellChange(record, 'indentify', record.indentify, index)">
            </a-textarea>
          </template>
        </a-table>
      </div>
    </a-card>
    <MatruityModal ref="materityModal" />
    <!-- 提交审批 -->
    <SubmitApproval ref='submitApproval' :visible='submitApprovalVisible' :rfmeaType="'D'"
                     @close='submitApprovalVisible = false' @list='handleUpdateMaturityData'/>
  </div>
</template>

<script>
import MatruityModal from "./components/MaturityModal";
import EditTableCell from "./components/EditTableCell";
import SubmitApproval from '@/components/SubmitApprovalModal';
import VueDraggableResizable from 'vue-draggable-resizable';

/**
 * 合并单元格
 * @param data
 * @param key
 * @param index
 * @returns {number}
 */
const mergeCells = (data, key, index) => {
  let oldStr = data[index][key].substring(0, data[index][key].indexOf('.'));
  if (index !== 0 && oldStr === data[index-1][key].substring(0, data[index-1][key].indexOf('.'))) {
    return 0
  }
  let rowSpan = 1
  for (let i = index + 1; i < data.length; i++) {
    let newStr = data[i][key].substring(0, data[i][key].indexOf('.'));
    if (oldStr !== newStr) {
      break
    }
    rowSpan++
  }
  return rowSpan;
};
export default {
  name: "MaturityEvaluation",
  components: {
    MatruityModal,
    EditTableCell,
    SubmitApproval,
    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 - 243 + 'px',
      tableHeightValue: window.innerHeight - 400,
      /** 数据源 */
      maturityTableData: [],
      /** 表格高度 */
      // tableHeight: "",
      /** 评估节点 */
      gradeCode: undefined,
      /** 评估结果 */
      evaluationResult: undefined,
      /** 状态 */
      state: undefined,
      /** 评估节点数据源 */
      evaluationNodeList: [],
      /** 子评分集合 */
      subMatkList: [],
      /** 子评分map */
      subMatkMap: {},
      /** 评估结果数据源 */
      resultList: [
        {name: this.$t('fmeamanager.maturity.high-maturity'), value: 1},
        {name: this.$t('fmeamanager.maturity.medium-maturity'), value: 2},
        {name: this.$t('fmeamanager.maturity.low-maturity'), value: 3},
      ],
      /** 状态下拉数据源 */
      stateList: [
        {name: this.$t('fmeamanager.maturity.under-evaluation'), value: 0},
        {name: this.$t('fmeamanager.maturity.approving'), value: 1},
        {name: this.$t('fmeamanager.maturity.passed'), value: 2},
        {name: this.$t('fmeamanager.maturity.failed'), value: 3},
      ],
      /** 表头 */
      tableColumns: [
        {
          title: () => this.$t('fmeamanager.maturity.principal-dimension'),
          width: 150,
          align: 'center',
          dataIndex: 'mainDimension',
          ellipsis: true,
          customRender: (text, record, index) => {
            const obj = {
              children: text,
              attrs: {}
            }
            obj.attrs.rowSpan = mergeCells(this.maturityTableData, 'sectionNumber', index)
            return obj
          }
        },
        {
          title: () => this.$t('fmeamanager.maturity.check-item-serial-number'),
          width: 100,
          align: 'center',
          dataIndex: 'sectionNumber',
          scopedSlots: { customRender: 'sectionNumber' },
          ellipsis: true,
        },
        {
          title: () => this.$t('fmeamanager.maturity.check-item'),
          width: 300,
          align: 'center',
          dataIndex: 'inspectionItem',
        },
        {
          title: () => this.$t('fmeamanager.maturity.evaluation-node'),
          width: 300,
          align: 'center',
          ellipsis: true,
          dataIndex: 'gradeCode',
        },
        {
          title: () => this.$t( 'fmeamanager.maturity.mark'),
          width: 150,
          align: 'center',
          dataIndex: 'mark',
          scopedSlots: { customRender: 'mark' },
          ellipsis: true,
          customRender: (text, record, index) => {
            let subMatkMap = this.subMatkMap[record.standardId];
            if ( subMatkMap !== undefined &&subMatkMap !== null ) {
              this.maturityTableData[index].mark = subMatkMap.score === 0
                  ? 0 : subMatkMap.score
                      ? (subMatkMap.score) * (record.childWeight) / 100 : null;
            }
            const obj = {
              attrs: {}
            }
            obj.attrs.rowSpan = mergeCells(this.maturityTableData, 'sectionNumber', index)
            if (obj.attrs.rowSpan > 0) {
              for (let i = 0; i < obj.attrs.rowSpan - 1; i++) {
                let subMatkMapElement = this.subMatkMap[this.maturityTableData[index+i+1].standardId];
                if (subMatkMapElement !== undefined
                    && subMatkMapElement !== null) {
                  this.maturityTableData[index].mark +=
                      (subMatkMapElement.score) * (this.maturityTableData[index+i+1].childWeight) / 100
                }
              }
            }
            obj.children = this.maturityTableData[index].mark
                ? this.maturityTableData[index].mark : this.maturityTableData[index].id
                    ? '0': '';
            return obj
          }
        },
        {
          title: () => this.$t('fmeamanager.maturity.sub-mark'),
          width: 150,
          align: 'center',
          dataIndex: 'standardId',
          scopedSlots: { customRender: 'standardId' },
          ellipsis: true,
        },
        {
          title: () => this.$t('fmeamanager.maturity.discovery-item'),
          width: 150,
          align: 'center',
          dataIndex: 'indentify',
          scopedSlots: { customRender: 'indentify' },
          ellipsis: true,
        },
      ],
      subMatk: undefined,
      /** 总分 */
      mark: null,
      /** 当前的评分标准数据 */
      currentMaturityGuideList: [],
      /** 加载状态 */
      loading: false,
      /** 表格加载状态 */
      tableLoading: false,
      /** 成熟度主键 */
      libraryId: null,
      /** 项目编号 */
      projectNo: '',
      /** 项目名称 */
      projectSn: "",
      projectId: undefined,
      chartHeight: window.innerHeight - 125 + 'px',
      /** 提交审批：开关 */
      submitApprovalVisible: false,
      /** 成熟度节点 */
      maturityNode: undefined,
    }
  },

  watch: {
    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 = 120;
      }
    },
    /**
     * 判断子评分是否可以清除
     */
    judgeIsClear(record) {
      if (record.standardId) {
        return true;
      }else {
        return false;
      }
    },
    /**
     * 打开模态框
     */
    showMaturityModal() {
      this.$refs.materityModal.showMaturity = true;
      this.$refs.materityModal.initData();
    },

    /**
     * 取得表格高度
     */
    getTableHeight() {
      this.$nextTick(() => {
        let dom = this.$refs.TestPlan;
        // DRBFM表单高度：from+操作按钮
        let measureTrackFormH = dom.querySelector(".MaturityEvaluation-from").offsetHeight;
        this.tableHeight = getTableHeight(dom, measureTrackFormH);
      });
    },

    /**
     * 导出
     */
    excelExport() {
      let markList = [];
      let rfmeaId = this.$store.getters.rfmeaId;
      let gradeCode = this.gradeCode;
      let mark = this.mark;
      let evaluationResult = this.evaluationResult;
      if (this.maturityTableData.length > 0) {
        for (let i = 0; i < this.maturityTableData.length; i++) {
          markList.push(this.maturityTableData[i].mark);
        }
      }
      let state =this.state || '';
      let url = this.$api.baseUrl + "/DFMEA/rdfmMaturity/export?fmeaId=" + rfmeaId
          + "&gradeCode=" + gradeCode
          + "&mark=" + mark
          + "&evaluationResult=" + evaluationResult
          + "&state=" + state
          + "&markList=" + markList;
      window.open(url);
    },

    /**
     * 提交审批
     */
    approve() {
      let that = this;
      that.$refs.submitApproval.inputArgs.businessId = that.$store.getters.fmeaId;
      that.$refs.submitApproval.inputArgs.libraryId = that.libraryId;
      that.$refs.submitApproval.inputArgs.projectNo = that.projectNo;
      that.$refs.submitApproval.inputArgs.projectSn = that.projectSn;
      that.$refs.submitApproval.inputArgs.projectId = that.projectId;
      that.$refs.submitApproval.inputArgs.gradeCode = that.gradeCode;
      that.$refs.submitApproval.inputArgs.approveType = '12';
      that.$refs.submitApproval.inputArgs.fmeaType = "1";
      that.submitApprovalVisible = true;
    },

    /**
     * 子评分数据
     * @param record
     */
    subMarkChange(record) {
      this.tableLoading = true;
      let data = {
        fmeaId: this.$store.getters.rfmeaId,
        libraryId: record.libraryId,
        gradeCode: record.gradeCode,
        subdimenId: record.subdimenId,
        standardId: record.standardId,
        indentify: record.indentify,
        childWeight: record.childWeight,
        id: record.id,
        maturityRecordId: this.libraryId,
        rdfmMaturityDimenModels: this.maturityTableData
      }
      this.$api.saveRdfmMaturityDetail(data).then(res => {
        if (res.flag) {
          this.initMaturityData(record.gradeCode);
          this.$message.success(res.message, 1);
        } else {
          this.$notification.error({message: res.message});
        }
        this.tableLoading = false;
      });
    },

    /**
     * 处理成熟度标准单元格编辑事件
     * @param record
     * @param dataIndex
     * @param value
     * @param index
     * @returns {boolean}
     */
    handleCellChange(record, dataIndex, value, index) {
      // 发现项有值未保存，子评分为空，保存发现项时执行
      if (record.standardId === null) {
        this.$message.warning(this.$t('fmeamanager.maturity.please-select-a-sub-rating'));
        this.maturityTableData[index].indentify = undefined;
        return false;
      }
      // 发现项有值未保存，子评分有值，清除子评分时执行
      if (record.standardId === undefined) {
        this.maturityTableData[index].indentify = undefined;
        return false;
      }
      const dataSource = [...this.maturityTableData];
      const find = dataSource.find(item => item.id === record.id);
      if (find) {
        find[dataIndex] = value;
        this.maturityTableData = dataSource;
      }
      this.subMarkChange(record)
    },

    /**
     * 改变节点触发的事件
     * @param val
     */
    nodeChange(val) {
      this.initMaturityData(val);
    },
    // 审批确定后调用初始化方法 
    handleUpdateMaturityData() {
      this.initMaturityData(this.maturityNode);
    },
    /**
     * 成熟度管理页面初始化
     * @param val
     */
    initMaturityData(val) {
      this.maturityNode = val;
      this.tableLoading = true;
      this.$api.getRdfmMaturityDetail({
        rfmeaId: this.$store.getters.rfmeaId,
        fmeaId: this.$route.query.fmeaId,
        gradeCode: val
      }).then(res => {
        if (res.flag) {
          let sum = null;
          let isDowngrade = false;
          this.maturityTableData = res.data.rdfmMaturityDetailDTOS;
          this.subMatkList = res.data.rdfmMaturityStandards;
          this.evaluationResult = res.data.evaluationResult ? res.data.evaluationResult : undefined;
          this.state = res.data.state !== null ? res.data.state : 0;
          this.libraryId = res.data.id !== null ? res.data.id : undefined;
          this.projectNo = res.data.projectNo ? res.data.projectNo : '';
          this.projectSn = res.data.projectSn ? res.data.projectSn : '';
          this.projectId = res.data.projectId ? res.data.projectId : '';
          res.data.rdfmMaturityStandards.forEach(item => {
            this.subMatkMap[item.id] = item
          })
          res.data.rdfmMaturityDetailDTOS.forEach(item => {
            if (item.score && item.childWeight) {
              sum += parseInt(item.score) * item.childWeight
            }
            if (item.isStar === 0 && item.scoreCode !== '0') {
              isDowngrade = true;
            }
          })
          // 校验是否可以提交审批
          this.approveFlag = this.maturityTableData.some(item => item.standardId !== null && item.standardId !== undefined && item.standardId !== '');
          this.mark = sum ? sum/100 : 0;
          res.data.rdfmMaturityStageResultList.forEach((item, index) => {
            if (this.mark) {
              if (index === 0 && item.lowerValue <= this.mark
                  && this.mark <= item.highValue) {
                this.evaluationResult = parseInt(item.result.substr(-1));
                if (isDowngrade && this.evaluationResult !== 3
                    && item.isNeedStar === 0) {
                  this.evaluationResult += 1;
                }
              } else if ((index === 1 || index === 2)
                  && item.lowerValue <= this.mark && this.mark < item.highValue) {
                this.evaluationResult = parseInt(item.result.substr(-1));
                if (isDowngrade && this.evaluationResult !== 3
                    && item.isNeedStar === 0) {
                  this.evaluationResult += 1;
                }
              }
            }
          })
        } else {
          this.$notification.error({message: res.message});
        }
      });
      this.tableLoading = false;
    },

    /**
     * 获取评估节点下拉数据
     */
    getEvaluationNodeList() {
      this.$api.getEvaluationNodeList({
        fmeaId: this.$route.query.rfmeaId,
      }).then(res =>{
        if (res.flag) {
          this.evaluationNodeList = res.data;
          if (this.evaluationNodeList.length > 0) {
            this.gradeCode = this.evaluationNodeList[0];
            this.initMaturityData(this.gradeCode);
          }
        }else {
          this.$message.error(res.message, 1);
        }
      })
    },
  },

  mounted(){
    this.getEvaluationNodeList();
    window.onresize = () => {
      this.chartHeight = window.innerHeight - 125 + 'px';
      this.tableHeightValue = window.innerHeight - 420;
    };
  },
  computed: {
    // 判断查看/编辑权限
    isLook() {
      return this.state === 1 || this.state === 2 || this.$api.isLook === '1';
    },
  },
}
</script>

<style scoped lang="less">
.help-icon {
  cursor: pointer;
  color: #FF9933;
}
/deep/ .ant-input {
  resize: none!important;
  overflow-y: hidden;
}
</style>