<template>
  <div class="analyseDetails">
    <!-- 关联失效 基本信息 -->
    <a-card :title="$t('research.association-failure')">
      <a-form v-bind='formItemLayout'>
        <a-form-item :label="$t('research.problem-number')">
          {{ showData.issueCode }}
        </a-form-item>
        <a-form-item :label="$t('research.problem-title')">
          {{ showData.title }}
        </a-form-item>
        <a-form-item :label="$t('research.problem-description')">
          {{ showData.descriptions }}
        </a-form-item>
        <a-form-item :label="$t('research.root-cause')">
          {{ showData.rootCause }}
        </a-form-item>
        <a-form-item :label="$t('research.solution')">
          {{ showData.solution }}
        </a-form-item>
      </a-form>
    </a-card>
    <!-- 关联失效 表格 -->
    <a-card class="mb50">
      <a-table
        ref="tableRef"
        :components='components'
        bordered
        size="small"
        :rowKey="(record, index) => record.id"
        :scroll="{ x: tableWidth, y: 1000 }"
        :columns="tableColumns"
        :dataSource="sourceData"
        @change="handleOuterTableChange"
        :pagination="pagination">
        <!-- 操作 -->
        <template slot="action" slot-scope="text, row">
          <!-- 删除 -->
          <a class="operate-btn" :disabled="!$api.btnPms" @click="deleted(row)">
            <a-tooltip :title="$t('global-btn.delete')">
              <i class="iconfont iconshanchu"></i>
            </a-tooltip>
          </a>
        </template>
      </a-table>
      <!-- 返回 -->
      <div class="tr mt10">
        <a-button class="ml10" @click="back" type="primary">
          {{ $t('global-btn.return') }}
        </a-button>
      </div>
    </a-card>
    <!-- end search panel -->
  </div>
</template>
<script>

import VueDraggableResizable from "vue-draggable-resizable";

export default {
  name: "analyse",
  components: {
    VueDraggableResizable
  },
  data() {
    // 表格拖拽
    this.components = {
      header: {
        cell: (h, props, children) => {
          const {key, ...restProps} = props;
          // 此处的this.columns 是定义的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, 35);
              }
            }
          };
          const drag = h('vue-draggable-resizable', {...dragProps});
          return h('th', {...restProps, class: 'resize-table-th'}, [...children, drag]);
        }
      }
    };
    return {
      // 表格总宽度
      tableWidth: 0,
      // 表格各列宽度总和
      columnsWidth: 0,
      /** 表单布局 */
      formItemLayout: {
        labelCol: {
          xxl: {span: 3},
          xl: {span: 3},
          lg: {span: 4},
          md: {span: 24},
          xs: {span: 24},
          sm: {span: 24}
        },
        wrapperCol: {
          xxl: {span: 21},
          xl: {span: 21},
          lg: {span: 20},
          md: {span: 24},
          xs: {span: 24},
          sm: {span: 24}
        }
      },
      showData: {
        issueCode: "",
        title: "",
        descriptions: "",
        rootCause: "",
        solution: ""
      },
      sourceData: [],
      // 表格列
      tableColumns: [
        // 序号
        {
          title: () => this.$t('research.serial-number'),
          width: 150,
          align: "center",
          customRender: (value, row, index) => {
            return (
                (this.pagination.current - 1) * this.pagination.pageSize +
                1 + index
            );
          },
          ellipsis: true
        },
        // 失效
        {
          title: () => this.$t('research.failure'),
          width: 550,
          dataIndex: "faultName",
          align: "center",
          ellipsis: true
        },
        // 功能
        {
          title: () => this.$t('research.function'),
          width: 500,
          dataIndex: "functionName",
          align: "center",
          ellipsis: true
        },
        // 结构
        {
          title: () => this.$t('research.structure'),
          width: 500,
          align: "center",
          dataIndex: "struName",
          ellipsis: true
        },
        // 操作
        {
          title: () => this.$t('research.operate'),
          width: 150,
          align: "center",
          scopedSlots: {
            customRender: "action"
          },
          ellipsis: true
        }
      ],
      listQuery: {
        pageSize: 10,
        pageNo: 1,
        id: this.$router.currentRoute.query.id,
        fmeaId: this.$store.getters.fmeaId
      },
      pagination: {
        current: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: (total) => this.$t('global-constant.table.show-total', [total]), // 显示总数
        showSizeChanger: false, // 显示可改变每页数量
        pageSizeOptions: ["10", "20", "50", "100", "200"], // 每页数量选项
        total: 0 //总条数
      }
    };
  },

  created() {
    this.getResearch();
    this.initSourceData();
  },

  mounted() {
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
    // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
    this.getTableDivCss();
  },

  // 剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },

  destroyed() {
  },

  watch: {
    tableColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    },
    tableWidth:{
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    }
  },


  methods: {

    // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
    getTableDivCss() {
      // 选中包裹表格的 div 元素
      let tableHeaderDiv = document.querySelector('.ant-table-header.ant-table-hide-scrollbar');
      let tableHeaderReal = document.querySelector('.resize-table-th');
      // 检查是否成功选中
      if (tableHeaderDiv) {
        // 设置背景颜色为灰色
        tableHeaderDiv.style.backgroundColor = 'rgb(245, 246, 247)';
        // 表头外层盒子的的实际样式
        let computedDivStyle = window.getComputedStyle(tableHeaderDiv);
        // 表头外层盒子的的实际高度
        let tableDivHeight = parseFloat(computedDivStyle.getPropertyValue('height'));
        // 表头的实际样式
        let computedTableStyle = window.getComputedStyle(tableHeaderReal);
        // 表头的实际高度
        let tableHeight = parseFloat(computedTableStyle.getPropertyValue('height'));
        // 设置底部外边距，一下会是负值，用于将表头下的数据单元格纵向对齐
        tableHeaderDiv.style.marginBottom = (tableHeight-tableDivHeight)+'px';
      }
    },
    // 获取表格的总宽度
    handleResize() {
      this.tableWidth = this.$refs.tableRef !== undefined ? this.$refs.tableRef.$el.offsetWidth : 1;
    },
    // 计算表格各列宽度总和
    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[0].fixed='left';
        // this.tableColumns[1].fixed='left';
        // this.tableColumns[this.tableColumns.length - 1].fixed='right';
        // 恢复最后一列原始宽度
        // this.tableColumns[this.tableColumns.length - 1].width = 100;
      }
    },

    // 表格 - 点击分页中数字触发的方法
    handleOuterTableChange(pagination) {
      this.listQuery.pageSize = pagination.pageSize;
      this.listQuery.pageNo = pagination.current;
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.initSourceData();
    },

    back() {
     if (this.$route.query.funFlag) {
      this.$router.go(-1);
     } else {
      this.$router.replace({
        path: this.$route.query.from,
        query: {
          ...this.$route.query,
          back: this.$route.query.back,
          backFlag: true // 添加一个标识，表示是通过返回按钮返回
        }
      });
     }
    },

    deleted(row) {
      var _that = this;
      this.$confirm({
        title: this.$t('global-message.warn'),
        content: this.$t('global-message.warn.delete-row'),
        icon: "aaoopqa", //图标，不想用就随便写一个
        okText: this.$t('global-btn.ok'),
        cancelText: this.$t('global-btn.cancel'),
        onOk() {
          _that.$api.delResearchTree({
            id: row.id,
            fmeaId: _that.$store.getters.fmeaId
          }).then((res) => {
            if (res.flag) {
              _that.$message.success(res.message);
              if (_that.listQuery.pageNo != 1 && _that.sourceData.length == 1) {
                _that.listQuery.pageNo -= 1;
              }
              _that.initSourceData();
            } else {
              _that.$message.error(res.message);
            }
          });
        }
      });
    },

    getResearch() {
      this.$api.getOneResearch({
        id: this.$router.currentRoute.query.id,
        fmeaId: this.$store.getters.fmeaId
      }).then((response) => {
        if (response.flag) {
          this.showData = response.data;
        } else {
          this.$message.error(response.message);
        }
      });
    },

    initSourceData() {
      this.$api.getResearchTree(this.listQuery).then((res) => {
        if (res.flag) {
          this.sourceData = res.data.data;
          this.pagination.total = res.data.total;
        } else {
          this.$message.error(res.message);
        }
      });
    }
  }

};
</script>

<style lang="less" scoped>

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


/deep/ .ant-table-tbody {
  .ant-table-row-cell-ellipsis:nth-of-type(2) {
    text-align: left !important;
  }

  .ant-table-row-cell-ellipsis:nth-of-type(3) {
    text-align: left !important;
  }

  .ant-table-row-cell-ellipsis:nth-of-type(4) {
    text-align: left !important;
  }
}
</style>
