<template>
  <a-modal
      class="funcNetDialog"
      :title="$t('functional-analysis.top-modal.function-matrix')"
      :visible="modalVisible"
      :maskClosable="false"
      @cancel="close"
      :keyboard="false"
      width="100%"
      destroyOnClose
      :footer="false"
      @afterClose="close">
    <div ref="functionMatrixModal">
      <div class="functionMatrixModal-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('functional-analysis.top-modal.structure')">
                <a-tree-select
                    ref="leftTree"
                    :v-model="leftTreeSelectValue"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :placeholder="$t('functional-analysis.top-modal.please-select-a-structure')"
                    allow-clear
                    show-search
                    tree-default-expand-all
                    :replaceFields="replaceFields"
                    :filterTreeNode="filterTreeNode"
                    :tree-data="leftTreeData"
                    @change="leftTreeSelectChange">
                  <template #title="{ value: val, title }">
                    <template>{{ title }}</template>
                  </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('functional-analysis.top-modal.child')">
                <a-select
                    ref="rightTree"
                    v-model="rightTreeSelectValue"
                    mode="tags"
                    :placeholder="$t('functional-analysis.top-modal.please-select-a-structure')"
                    allow-clear
                    @change="rightTreeSelectChange">
                  <a-select-option
                      v-for="item in rightTreeData"
                      :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
        <span class="fr">
          <a-button @click="search" type="primary">
            {{ $t('global-btn.search') }}
          </a-button>
        </span>
          </a-row>
        </a-form>
      </div>

      <!-- 功能矩阵表格 -->
      <div class="mt10">
        <a-table
            v-if="topTableColumns && topTableColumns.length > 0"
            :data-source="tableData"
            :columns="tableColumns"
            :rowKey="(row, index) => {return row.key;}"
            bordered
            size="small"
            :loading="tableLoading"
            :scroll="{ x: tableScrollX, y: tableScrollY }"
            :pagination="false">
        </a-table>
        <!-- 表格无数据 -->
        <a-table v-if="!topTableColumns"/>
      </div>
    </div>
  </a-modal>
</template>

<script>

import {arrayToTree} from "@/utils/tree";

const defaultTopTableColumns = [{
  title: '',
  dataIndex: 'leftStructure',
  width: 150,
  fixed: 'left',
  align: 'center',
}];

export default {
  name: "FunctionMatrixModal",
  props: {
    showFunctionMatrixModal: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /** 表格数据 */
      tableData: [],
      /** 表格表头据 */
      tableColumns: [],
      /** 顶部表格列数据 */
      topTableColumns: defaultTopTableColumns,
      /** 表格数据 */
      funNet: [],
      /** 左侧树数据 */
      leftTreeData: [],
      /** 左侧树选中值 */
      leftTreeSelectValue: undefined,
      /** 左侧树选中ID */
      leftTreeSelectId: undefined,
      /** 右侧树数据 */
      rightTreeData: [],
      /** 右侧树选中值 */
      rightTreeSelectValue: undefined,
      /** 右侧树选中ID数组 */
      rightTreeSelectIds: [],
      /** 替换 treeNode 中 title,key,children,value 字段为 treeData 中对应的字段 */
      replaceFields: {children: 'children', label: 'name', key: 'id', value: 'id'},
      /** 模态框是否可见 */
      modalVisible: false,
      /** 表格Loading */
      tableLoading: false,
      /** 表格动态宽度 */
      tableScrollX: 0,
      /** 表格动态高度 */
      tableScrollY: 0,
      /** 顶部功能索引 */
      topFunctionIndex: 0,
    };
  },
  watch: {
    showFunctionMatrixModal(val) {
      this.rightTreeSelectValue = undefined;
      this.rightTreeSelectIds = [];
      this.modalVisible = val;
    },
  },
  methods: {
    /**
     * 取得表格高度
     */
    getTableHeight() {
      this.$nextTick(() => {
        let dom = this.$refs.functionMatrixModal;
        let functionMatrixModalFromH = dom.querySelector(".functionMatrixModal-from").offsetHeight;
        let otherDomH = 194 + functionMatrixModalFromH;
        this.tableScrollY = "calc(100vh - " + otherDomH + "px)";
        console.log("功能矩阵 ==> tableHeight:" + this.tableScrollY);
      });
    },
    /**
     * 关闭模态框
     */
    close() {
      this.$emit("closeModal");
      this.$emit("initRightTree");
    },
    /**
     * 获取左侧下拉值
     */
    getLeftSelect() {
      let _that = this;
      _that.$api.getLeftTree({
        fmeaId: _that.$store.getters.rfmeaId
      }).then(res => {
        if (res.flag) {
          let targetNode = res.data.mfmeaStruTreeModels.filter((item) => {
            return item.pid === '00000000000000000000000000000000';
          })[0];
          _that.leftTreeSelectId = targetNode.id;
          // 获取下级下拉
          _that.getChildSelect(targetNode.id);
          // 数组转Tree
          _that.leftTreeData = arrayToTree(targetNode, res.data.mfmeaStruTreeModels);
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      });
    },
    /**
     * 获取下级下拉
     * @param leftId 左侧结构ID
     */
    getChildSelect(leftId) {
      let _that = this;
      _that.$api.getFunctionMatrixChild({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: leftId
      }).then(res => {
        if (res.flag) {
          _that.rightTreeData = res.data.mfmeaStruTreeModels;
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      });
    },
    /**
     * 列表
     *@param rootNodeId 根节点ID
     */
    list(rootNodeId) {
      let _that = this;
      _that.tableLoading = true;
      _that.$api.getFunctionMatrix({
        fmeaId: _that.$store.getters.rfmeaId,
        struId: rootNodeId ? rootNodeId : _that.leftTreeSelectId,
        childStruId: _that.rightTreeSelectIds && _that.rightTreeSelectIds.length > 0
            ? _that.rightTreeSelectIds.toString() : _that.rightTreeSelectIds,
      }).then(res => {
        if (res.flag) {
          let resTopStruList = res.data.topStruList;
          let resLeftStru = res.data.leftStru;
          let resFunNet = res.data.funNet;
          // 顶部表格列数据
          _that.topTableColumns = resTopStruList;
          if (!resTopStruList) return;
          // 表格数据
          if (resFunNet) _that.funNet = Object.keys(resFunNet);

          // 表格宽度默认300（左侧结构 + 左侧功能，两列宽度）
          _that.tableScrollX = 300;
          // 处理表格列
          _that.handleTableColumns(resLeftStru, resTopStruList);
          // 处理表格数据
          _that.handleTableData(res.data.leftStru);
          // 取得表格高度
          _that.getTableHeight();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.tableLoading = false;
      })
    },
    /**
     * 输入项筛选
     * @param inputValue
     * @param treeNode
     */
    filterTreeNode(inputValue, treeNode) {
      return treeNode.data.props.name.includes(inputValue)
    },
    /**
     * 搜索
     */
    search() {
      this.list();
    },
    /**
     * 保存
     * @param leftFuncId 左侧功能ID
     * @param topFuncId 顶部功能ID
     * @param checkFlag 选中标识
     */
    save(leftFuncId, topFuncId, checkFlag) {
      let _that = this;
      _that.$api.saveFunctionMatrix({
        fmeaId: _that.$store.getters.rfmeaId,
        functionId: [leftFuncId, topFuncId].toString(),
        checkFlag: checkFlag,
      }).then(res => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          let k = leftFuncId + topFuncId;
          if (checkFlag) { // 追加
            _that.funNet.push(k);
          } else { // 删除
            for (let i = _that.funNet.length - 1; i >= 0; i--) {
              if (k === _that.funNet[i]) _that.funNet.splice(i, 1);
            }
          }
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      });
    },
    /**
     * 处理表格列
     * @param leftStru 左侧结构
     * @param topStruList 顶部结构数组
     */
    handleTableColumns(leftStru, topStruList) {
      let _that = this;
      let tableColumns = [
        _that.handleLeftStructureTableColumns(leftStru.funList.length),
        _that.handleLeftFunctionTableColumns(),
      ];
      let topTableColumns = _that.handleTopStructureTableColumns(topStruList);
      (topTableColumns || []).forEach(item => {
        tableColumns.push(item);
      });
      _that.tableColumns = tableColumns;
    },
    /**
     * 处理表格数据
     * @param leftStru 左侧结构数据
     */
    handleTableData(leftStru) {
      let _that = this;
      let tableData = [];
      if (leftStru.funList && leftStru.funList.length > 0) {
        let funList = leftStru.funList;
        for (let i = 0, len = funList.length; i < len; i++) {
          let data = {
            key: i,
            leftStructure: leftStru.name,
            leftFunction: funList[i].name,
            leftFunctionId: funList[i].id,
            leftFunctionType: funList[i].struTypeCode,
          };
          let topFunctionData = _that.handleTopFunctionIdTableData(leftStru);
          // 合并
          Object.assign(data, topFunctionData);
          tableData.push(data);
        }
      }
      _that.tableData = tableData;
    },
    /**
     * 处理顶部功能表格数据
     * @param leftStru 左侧结构数据
     */
    handleTopFunctionIdTableData(leftStru) {
      let tableData = {};
      if (leftStru.funList && leftStru.funList.length > 0
          && leftStru.funList[0].funList && leftStru.funList[0].funList.length > 0) {
        let topFunList = leftStru.funList[0].funList;
        for (let i = 0, len = topFunList.length; i < len; i++) {
          tableData['topFunctionId' + i] = topFunList[i].id;
        }
      }
      return tableData;
    },
    /**
     * 处理左侧结构表格列
     * @param rowSpan 合并行数
     */
    handleLeftStructureTableColumns(rowSpan) {
      return {
        title: '',
        dataIndex: 'leftStructure',
        width: 150,
        fixed: 'left',
        align: 'center',
        customRender: (value, row, index) => {
          const obj = {
            children: value,
            attrs: {},
          };
          if (index === 0) {
            obj.attrs.rowSpan = rowSpan;
          } else {
            obj.attrs.rowSpan = 0
          }
          return obj;
        },
        customCell: (row, index) => {
          return {
            style: {
              'background-color': '#fafafa'
            }
          };
        },
      }
    },
    /**
     * 处理左侧功能表格列
     */
    handleLeftFunctionTableColumns() {
      return {
        title: '',
        dataIndex: 'leftFunction',
        width: 150,
        fixed: 'left',
        customCell: (row, index) => {
          let color = row.leftFunctionType === '02' ? 'rgb(66, 167, 94)' : '#5b9bd5';
          return {
            style: {
              'color': color,
              'background-color': '#fafafa'
            }
          };
        },
        align: 'center',
        ellipsis: true
      }
    },
    /**
     * 处理顶部结构表格列
     * @param topStruList 顶部结构数据
     */
    handleTopStructureTableColumns(topStruList) {
      let tableColumns = [];
      this.topFunctionIndex = 0;
      for (let i = 0, len = topStruList.length; i < len; i++) {
        let children = []
        if (topStruList[i].funList && topStruList[i].funList.length > 0) {
          // 默认追加动态列宽度：150px
          this.tableScrollX += topStruList[i].funList.length * 150;
          children = this.handleTopFunctionTableColumns(topStruList[i].funList);
        }
        tableColumns.push({
          title: () => {
            return <span title={topStruList[i].name}>
              {topStruList[i].name}
            </span>
          },
          align: 'center',
          ellipsis: true,
          children: children,
        },)
      }
      return tableColumns;
    },
    /**
     * 处理顶部功能表格列
     * @param topFunList 数据数据
     */
    handleTopFunctionTableColumns(topFunList) {
      let tableColumns = [];
      for (let i = 0, len = topFunList.length; i < len; i++) {
        tableColumns.push({
          title: () => {
            return <span class={topFunList[i].struTypeCode === '02' ? 'function-color' : 'productFeature-color'}
                         title={topFunList[i].name}>
              {topFunList[i].name}
            </span>
          },
          dataIndex: 'topFunctionId' + this.topFunctionIndex,
          customRender: (value, row, index) => {
            if (value) {
              return <a-checkbox
                  checked={this.isCheck(row.leftFunctionId, value)}
                  onChange={(e) => this.checkboxChange(e, row.leftFunctionId, value)}/>;
            } else {
              return '';
            }
          },
          align: 'center',
          ellipsis: true
        },)
        this.topFunctionIndex++;
      }
      return tableColumns;
    },
    /**
     * 左侧树选中事件
     * @param value
     * @param label
     * @param extra
     */
    leftTreeSelectChange(value, label, extra) {
      this.leftTreeSelectId = value;
      this.rightTreeSelectValue = undefined;
      this.rightTreeSelectIds = undefined;
      this.getChildSelect(value);
    },
    /**
     * 左侧树选中事件
     * @param value
     * @param option
     */
    rightTreeSelectChange(value, option) {
      this.rightTreeSelectIds = value;
    },
    /**
     * 复选框：是否选中
     * @param leftFuncId 左侧功能ID
     * @param topFuncId 顶部功能ID
     */
    isCheck(leftFuncId, topFuncId) {
      let k = leftFuncId + topFuncId;
      return this.funNet.indexOf(k) !== -1;
    },
    /**
     * 复选框改变事件
     * @param e
     * @param leftFuncId 左侧功能ID
     * @param topFuncId 顶部功能ID
     */
    checkboxChange(e, leftFuncId, topFuncId) {
      if (this.$api.isLook !== '1') {
        this.save(leftFuncId, topFuncId, e.target.checked);
      }
    },
  },
  destroyed() {
    this.$emit("closeModal");
  }
}
</script>
<style lang="less" scoped>

// 设置model 全屏
/deep/ .ant-modal {
  top: 0 !important;
}

// 设置model 全屏
/deep/ .ant-modal-content {
  height: calc(100vh);
}

// 不加上弹窗就会有滚动条;
/deep/ .ant-modal-wrap {
  overflow: hidden !important
}

/*/deep/ .ant-modal-close-x {
  font-size: 40px;
  color: white;
}

/deep/ .ant-modal-header {
  background: #5170b7;
}

/deep/ .ant-modal-title {
  color: white;
}*/



/deep/ .ant-table-fixed-left .ant-table-fixed {

  .ant-table-thead tr {
    height: 76px !important;
  }

  .ant-table-tbody tr {
    height: 38px !important;
  }

  .ant-table-tbody td {
    border-bottom: 1px solid #e8e8e8;
  }
}

</style>
