<template>
  <a-modal
      class="funcNetDialog"
      :title="$t('functional-analysis.top-modal.interface-matrix')"
      :visible="modalVisible"
      :maskClosable="false"
      @cancel="close"
      :keyboard="false"
      width="100%"
      destroyOnClose
      :footer="false"
      @afterClose="close">
    <div ref="interfaceMatrixModal">
      <div class="interfaceMatrixModal-form">
        <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.row-filter')">
                <a-select
                    :placeholder="$t('functional-analysis.top-modal.please-select-row-filter')"
                    v-model="rowFilters"
                    :filter-option="rowFilterOption"
                    mode="multiple"
                    allow-clear
                >
                  <a-select-option
                      v-for="(item, index) in rowData"
                      :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('functional-analysis.top-modal.column-filter')">
                <a-select
                    :placeholder="$t('functional-analysis.top-modal.please-select-column-filter')"
                    v-model="columnFilters"
                    :filter-option="columnFilterOption"
                    mode="multiple"
                    allow-clear
                >
                  <a-select-option
                      v-for="(item, index) in columnData"
                      :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('functional-analysis.top-modal.matrix-type')">
                <a-select
                    :placeholder="$t('functional-analysis.top-modal.please-select-matrix-type')"
                    v-model="matrixType"
                >
                  <a-select-option
                      v-for="(item, index) in matrixTypeDict"
                      :key="index"
                      :value="item.value"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="24" :md="12" :sm="24" :xs="24">
              <a-form-item class="tr" :label="'\xa0'">
                <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>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <span class="fr">
              <a-button @click="excelExport" type="primary" :disabled="!resData">
                {{ $t('global-btn.export') }}
              </a-button>
            </span>
          </a-row>
        </a-form>

        <!-- Switch Start -->
        <a-form layout="inline">
          <a-row>
            <a-form-item :label="$t('functional-analysis.top-modal.switch.physical-contact')">
              <a-switch v-model='PSwitch' @change="handlePSwitch"/>
            </a-form-item>
            <a-form-item :label="$t('functional-analysis.top-modal.switch.energy-transfer')">
              <a-switch v-model='ESwitch' @change="handleESwitch"/>
            </a-form-item>
            <a-form-item :label="$t('functional-analysis.top-modal.switch.information-exchange')">
              <a-switch v-model='ISwitch' @change="handleISwitch"/>
            </a-form-item>
            <a-form-item :label="$t('functional-analysis.top-modal.switch.material-transfer')">
              <a-switch v-model='MSwitch' @change="handleMSwitch"/>
            </a-form-item>
            <a-form-item :label="$t('functional-analysis.top-modal.switch.human-computer-interaction')">
              <a-switch v-model='HMSwitch' @change="handleHMSwitch"/>
            </a-form-item>
          </a-row>
        </a-form>
        <!-- Switch End -->
      </div>
      <!-- 表格 -->
      <div class="mt10">
        <a-table
            :data-source="tableData"
            :columns="tableColumns"
            :rowKey="(row, index) => {return index;}"
            bordered
            size="small"
            :loading="tableLoading"
            :scroll="{ x: tableScrollX, y: tableScrollY }"
            :pagination="false">
        </a-table>
      </div>
      <!-- 接口属性 Start -->
      <PropertyEdgeModal
        ref="propertyEdgeModal"
        @initLeftTree="initLeftTree"
        @initRightTree="initRightTree"
        @list="list"/>
    </div>
  </a-modal>
</template>

<script>

import PropertyEdgeModal from "../PropertyModal/PropertyEdgeModal.vue"
export default {
  name: "InterfaceMatrixModal",
  components: {
    PropertyEdgeModal
  },
  props: {
    showInterfaceMatrixModal: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /** 模态框是否可见 */
      modalVisible: false,
      /** 表格动态宽度 */
      tableScrollX: 0,
      /** 表格动态高度 */
      tableScrollY: 0,
      /** 表格数据 */
      tableData: [],
      /** 表格表头数据 */
      tableColumns: [],
      /** 表格Loading */
      tableLoading: false,
      /** 行筛选，数据 */
      rowData: [],
      /** 行筛选 */
      rowFilters: undefined,
      /** 列筛选，数据 */
      columnData: [],
      /** 列筛选 */
      columnFilters: undefined,
      /** 矩阵类型，默认内外部 */
      matrixType: '00',
      /** 矩阵类型字典 */
      matrixTypeDict: [
        {name: this.$t('global-dict.matrix-type.inside-and-outside'), value: "00"},
        {name: this.$t('global-dict.matrix-type.inside'), value: "01"},
        {name: this.$t('global-dict.matrix-type.outside'), value: "99"},
      ],
      /** Switch */
      PSwitch: true,
      ESwitch: true,
      ISwitch: true,
      MSwitch: true,
      HMSwitch: true,
      /** 响应数据 */
      resData: undefined
    };
  },
  watch: {
    showInterfaceMatrixModal(val) {
      this.rowFilters = undefined;
      this.columnFilters = undefined;
      this.matrixType = '00';
      this.modalVisible = val;
    },
  },
  methods: {
    /**
     * 取得表格高度
     */
    getTableHeight() {
      this.$nextTick(() => {
        let dom = this.$refs.interfaceMatrixModal;
        let interfaceMatrixModalFormH = dom.querySelector(".interfaceMatrixModal-form").offsetHeight;
        let otherDomH = 160 + interfaceMatrixModalFormH;
        this.tableScrollY = "calc(100vh - " + otherDomH + "px)";
      });
    },
    /**
     * 刷新左侧树
     */
     initLeftTree() {
      this.$emit('initLeftTree');
    },
    /**
     * 刷新右侧树
     */
    initRightTree() {
      this.$emit('initRightTree');
    },
    /**
     * 关闭模态框
     */
    close() {
      this.$emit("closeModal");
    },
    /**
     * 行筛选
     * @param input
     * @param option
     */
    rowFilterOption(input, option) {
      return option.componentOptions.children[0].text.includes(input);
    },
    /**
     * 列筛选
     * @param input
     * @param option
     */
    columnFilterOption(input, option) {
      return option.componentOptions.children[0].text.includes(input);
    },
    /**
     * 处理物理接触，switch
     */
    handlePSwitch() {
      if (!this.resData) return;
      this.handleTableData(this.resData.leftData, this.resData.cellData);
    },
    /**
     * 处理能量传递，switch
     */
    handleESwitch() {
      if (!this.resData) return;
      this.handleTableData(this.resData.leftData, this.resData.cellData);
    },
    /**
     * 处理信息交换，switch
     */
    handleISwitch() {
      if (!this.resData) return;
      this.handleTableData(this.resData.leftData, this.resData.cellData);
    },
    /**
     * 处理物质传递，switch
     */
    handleMSwitch() {
      if (!this.resData) return;
      this.handleTableData(this.resData.leftData, this.resData.cellData);
    },
    /**
     * 处理人机交互，switch
     */
    handleHMSwitch() {
      if (!this.resData) return;
      this.handleTableData(this.resData.leftData, this.resData.cellData);
    },
    /**
     * 列表
     */
    list() {
      let _that = this;
      _that.tableLoading = true;
      _that.tableColumns = [];
      _that.tableData = [];
      _that.$api.getInterfaceMatrix({
        fmeaId: _that.$store.getters.rfmeaId,
        pairFlag: 1 // 查询/导出标识 默认为1
      }).then(res => {
        if (res.flag) {
          // 接受数据
          _that.resData = res.data;
          if (!_that.resData || _that.resData.length === 0) {
            return;
          }
          // 处理行筛选数据
          _that.rowData = _that.resData.leftData.map(item => {
            return {name: item.fromName, value: item.fromId};
          });
          // 处理列筛选数据
          _that.columnData = _that.resData.topData.map(item => {
            return {name: item.toName, value: item.toId};
          });
          // 表格宽度默认150（左侧结构）
          _that.tableScrollX = 150;
          // 处理表格列
          _that.handleTableColumns(_that.resData.leftData, _that.resData.topData);
          // 处理表格数据
          _that.handleTableData(_that.resData.leftData, _that.resData.cellData);
          // 取得表格高度
          _that.getTableHeight();
        } else {
          _that.$message.error(res.message, 1);
        }
      }).catch((error) => {
        _that.$message.error(error.response.data.message, 1);
      }).finally(() => {
        _that.tableLoading = false;
      })
    },
    // 单元格点击事件
    handleCellClick(text) {
      if (text.connectId) {
        this.$refs.propertyEdgeModal.visible = true;
        this.$refs.propertyEdgeModal.linkId = text.connectId;
      }
    },
    /**
     * 输入项筛选
     * @param inputValue
     * @param treeNode
     */
    filterTreeNode(inputValue, treeNode) {
      return treeNode.data.props.name.includes(inputValue)
    },
    /**
     * 重置
     */
    reset() {
      this.rowFilters = undefined;
      this.columnFilters = undefined;
      this.matrixType = '00';
      this.list();
    },
    /**
     * 搜索
     */
    search() {
      this.list();
    },
    /**
     * Excel导出
     */
    excelExport() {
      let rfmeaId = this.$store.getters.rfmeaId;
      let rowFilters = this.rowFilters || '';
      let columnFilters = this.columnFilters || '';
      let matrixType = this.matrixType || '';
      let url = this.$api.baseUrl + "/DFMEA/mfmeaInterfereMatrix/excelExport?fmeaId=" + rfmeaId
          + "&rowFilters=" + rowFilters
          + "&columnFilters=" + columnFilters
          + "&matrixType=" + matrixType
      window.open(url);
    },
    /**
     * 处理表格列
     * @param leftData 左侧数据
     * @param topData 顶部数据W
     */
    handleTableColumns(leftData, topData) {
      let _that = this;
      let tableColumns = [
        _that.handleLeftTableColumns(),
      ];
      let topTableColumns = _that.handleTopTableColumns(topData);
      (topTableColumns || []).forEach(item => {
        tableColumns.push(item);
      });
      _that.tableColumns = tableColumns;
      // 给每一个单元格生成点击事件
      (_that.tableColumns || []).forEach(item => {
        item.customRender = text => {
          if (text) {
            // 使用分号分割字符串为数组
            let entries = text.trim().split(';');
            // 创建一个新的数组来存储处理后数据
            let processedEntries = entries.map(entry => {
              // 使用下划线分割数据为描述和connectId
              let [description, connectId] = entry.trim().split('_');
              // 返回一个对象，其中包含描述和唯一ID
              return {
                description: description,
                connectId: connectId || null // 如果没有connectId，则设为null
              };
            });
            // 渲染每个描述，并为每个描述添加点击事件
            return (
              <div>
                {processedEntries.map((entry, index) => (
                  <span
                    key={index}
                    class={ entry.connectId ? 'clickable-description' : '' } // 如果connectId存在则添加悬停变色类
                    style={{ cursor: entry.connectId ? 'pointer' : 'default' }} // 鼠标悬停样式
                    onClick={() => _that.handleCellClick(entry)} // 传递当前点击的描述对应的对象
                  >
                    {entry.description}
                    {/* 如果不是最后一个并且connectId不为空，则添加换行 */}
                    {index < processedEntries.length - 1  && entry.connectId !== null ? <br /> : null}
                  </span>
                ))}
              </div>
            )
          }
        };
      });
    },
    /**
     * 处理表格数据
     * @param leftData 左侧数据
     * @param cellData 单元格数据
     */
    handleTableData(leftData, cellData) {
      if(!cellData) return;
      let _that = this;
      let tableData = [];
      for (let i = 0, len = leftData.length; i < len; i++) {
        // 处理行筛选
        if (this.rowFilters && this.rowFilters.length > 0
            && !this.rowFilters.includes(leftData[i].fromId)) {
          continue;
        }
        // 处理矩阵类型
        if (this.matrixType === '01' && leftData[i].fromTypeCode !== '01') {
          continue;
        }
        if (this.matrixType === '99' && leftData[i].fromTypeCode !== '99') {
          continue;
        }
        let data = {
          first: leftData[i].fromName,
          typeCode: leftData[i].fromTypeCode
        };
        for (let j = 0, len = _that.tableColumns.length; j < len; j++) {
          if (_that.tableColumns[j].dataIndex !== 'first') {
            let v = _that.handleCellData(leftData[i].fromId, _that.tableColumns[j].dataIndex, cellData);
            data[_that.tableColumns[j].dataIndex] = v;
          }
        }
        tableData.push(data);
      }
      // >1列
      if (_that.tableColumns.length > 1) {
        _that.tableData = tableData;
      }
    },
    /**
     * 处理单元格数据
     * @param fromId 左侧ID
     * @param toId 顶部ID
     * @param cellData 单元格数据
     */
    handleCellData(fromId, toId, cellData) {
      let key = fromId + toId;
      if (cellData[key]) {
        let str = '';
        for (let i = 0, len = cellData[key].length; i < len; i++) {
          // 筛选，根据switch状态
          let item = cellData[key][i];
          if (!this.PSwitch && Object.keys(item)[0] === 'P') {
            continue;
          }
          if (!this.ESwitch && Object.keys(item)[0] === 'E') {
            continue;
          }
          if (!this.ISwitch && Object.keys(item)[0] === 'I') {
            continue;
          }
          if (!this.MSwitch && Object.keys(item)[0] === 'M') {
            continue;
          }
          if (!this.HMSwitch && Object.keys(item)[0] === 'HM') {
            continue;
          }
          str += Object.values(item) + '\xa0';
        }
        return str;
      }
    },
    /**
     * 处理左侧表格列
     */
    handleLeftTableColumns() {
      // 获取矩阵类型
      let title = this.matrixTypeDict.filter(item => item.value === this.matrixType)[0].name;
      return {
        title: () => {
          return <span title={title}>
              {title}
            </span>
        },
        dataIndex: 'first',
        width: 150,
        fixed: 'left',
        align: 'center',
        ellipsis: true,
        customCell: (row, index) => {
          return {
            style: {
              'background-color': row.typeCode === '01' ? '#e1efda' : '#f8cbad'
            }
          };
        },
      }
    },
    /**
     * 处理顶部表格列
     * @param topData 顶部数据
     */
    handleTopTableColumns(topData) {
      let tableColumns = [];
      for (let i = 0, len = topData.length; i < len; i++) {
        // 处理列筛选
        if (this.columnFilters && this.columnFilters.length > 0
            && !this.columnFilters.includes(topData[i].toId)) {
          continue;
        }
        // 处理矩阵类型
        if (this.matrixType === '01' && topData[i].toTypeCode !== '01') {
          continue;
        }
        if (this.matrixType === '99' && topData[i].toTypeCode !== '99') {
          continue;
        }
        // 默认追加动态列宽度：150px
        this.tableScrollX += 150;
        tableColumns.push({
          title: () => {
            return <span title={topData[i].toName}>
              {topData[i].toName}
            </span>
          },
          dataIndex: topData[i].toId,
          className: topData[i].toTypeCode === '01' ? 'structure' : 'interface',
          align: 'center',
        },);
      }
      return tableColumns;
    },
  },
  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-table-wrapper .ant-table-thead tr th.structure {
  background-color: #e1efda !important;
}

/deep/ .ant-table-wrapper .ant-table-thead tr th.interface {
  background-color: #f8cbad !important;
}
.clickable-description {
  color: inherit; /* 初始颜色 */
  transition: color 0.3s ease; /* 过渡效果 */
}

.clickable-description:hover {
  color: #1890FF; /* 悬停时变为蓝色 */
}
</style>
