<template>
  <a-modal
    :footer='null'
    :title="$t('research.association-failure')"
    :visible='showViewDrawer'
    class="full-modal"
    width='100%'
    @cancel='handleClose'
  >
    <div class="analyseDetails">
      <!-- 关联失效 基本信息 -->
      <a-card>
        <a-form layout='inline'>
          <a-row :gutter='24'>
            <!-- 问题标题 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-title')" class="ellipsis-text">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.issueTitle }}</span>
                  </template>
                  <span>{{ formData.issueTitle }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 问题编号 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-code')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.issueNo }}</span>
                  </template>
                  <span>{{ formData.issueNo }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 项目名称 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-project-name')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.projectName }}</span>
                  </template>
                  <span>{{ formData.projectName }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 产品名称 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-product-name')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.productName }}</span>
                  </template>
                  <span>{{ formData.productName }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter='24'>
            <!-- 结构代码 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-svpps')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.svpps }}</span>
                  </template>
                  <span>{{ formData.svpps }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 失效零件名称 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-part-name')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.partName }}</span>
                  </template>
                  <span>{{ formData.partName }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 失效零件代码 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-part-code')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.partNumber }}</span>
                  </template>
                  <span>{{ formData.partNumber }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 问题种类 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-type')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.problemType }}</span>
                  </template>
                  <span>{{ formData.problemType }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 发生时间 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-occur-time')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.occurTime }}</span>
                  </template>
                  <span>{{ formData.occurTime }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 问题来源 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-source')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.issueSource }}</span>
                  </template>
                  <span>{{ formData.issueSource }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 问题等级 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-issue-level')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.issueLevel }}</span>
                  </template>
                  <span>{{ formData.issueLevel }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 失效分类 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-fault-type')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.failureType }}</span>
                  </template>
                  <span>{{ formData.failureType }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 责任人 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-duty-person')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.responsible }}</span>
                  </template>
                  <span>{{ formData.responsible }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 责任部门 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('report.history-problem-duty-department')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.responsibleDepartment }}</span>
                  </template>
                  <span>{{ formData.responsibleDepartment }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 问题描述 -->
            <a-col :md='24' :sm='24'>
              <a-form-item :label="$t('report.history-problem-issue-description')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.descriptions }}</span>
                  </template>
                  <span>{{ formData.descriptions }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 临时措施 -->
            <a-col :md='24' :sm='24'>
              <a-form-item :label="$t('report.history-problem-interim-measure')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.interimMeasure }}</span>
                  </template>
                  <span>{{ formData.interimMeasure }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 根本原因 -->
            <a-col :md='24' :sm='24'>
              <a-form-item :label="$t('report.history-problem-root-cause')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.rootCause }}</span>
                  </template>
                  <span>{{ formData.rootCause }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 纠正措施 -->
            <a-col :md='24' :sm='24'>
              <a-form-item :label="$t('report.history-problem-corrective-action')">
                <a-popover>
                  <template slot="content">
                    <span>{{ formData.correctiveAction }}</span>
                  </template>
                  <span>{{ formData.correctiveAction }}</span>
                </a-popover>
              </a-form-item>
            </a-col>
            <!-- 附件 -->
            <a-col :md='24' :sm='24'>
              <a-form-item :label="$t('functional-analysis.property-modal.attachment')">
                <a :href="$api.requestUrl + '/DFMEA/file/downloadFile.do?id=' + formData.attachmentId + '&fileType=2'"
                   class="attachment-color">
                  {{ formData.attachmentName }}
                </a>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <!-- 关联失效 表格 -->
      <a-card class="mb50">
        <a-table
          ref="tableRef"
          :columns="tableColumns"
          :components='components'
          :dataSource="sourceData"
          :pagination="pagination"
          :rowKey="(record, index) => record.id"
          :scroll="{ x: tableWidth, y: 1000 }"
          bordered
          size="small"
          @change="handleOuterTableChange">
          <!-- 操作 -->
          <template slot="action" slot-scope="text, row">
            <!-- 删除 -->
            <a :disabled="!$api.btnPms" class="operate-btn" @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" type="primary" @click="handleClose">
            {{ $t('global-btn.return') }}
          </a-button>
        </div>
      </a-card>
      <!-- end search panel -->
    </div>
  </a-modal>
</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.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, 35);
              }
            }
          };
          const drag = h('vue-draggable-resizable', {...dragProps});
          return h('th', {...restProps, class: 'resize-table-th'}, [...children, drag]);
        }
      }
    };
    return {
      issueId: undefined,
      // 弹窗标识
      showViewDrawer: false,
      // 表格总宽度
      tableWidth: 0,
      // 表格各列宽度总和
      columnsWidth: 0,
      /** 表单布局 */
      formData: {
        issueNo: undefined, // 问题编号
        issueTitle: undefined, // 问题标题
        projectName: undefined, // 项目名称
        productName: undefined, // 产品名称
        svpps: undefined, // 结构代码
        partName: undefined, // 零件名称
        partNumber: undefined, // 零件编号
        problemType: undefined, // 问题种类
        occurTime: undefined, // 发生时间
        issueSource: undefined, // 问题来源
        issueLevel: undefined, // 问题等级
        failureType: undefined, // 失效类型
        responsible: undefined, // 责任人
        responsibleDepartment: undefined, // 部门名称
        descriptions: undefined, // 问题描述
        interimMeasure: undefined, // 临时措施
        rootCause: undefined, // 根本原因
        correctiveAction: undefined, // 纠正措施
        attachmentName: undefined, // 附件名称
        attachmentPath: undefined, // 附件路径
        attachmentId: undefined // 附件id
      },
      // 表格数据
      sourceData: [],
      // 表格列
      tableColumns: [
        // 序号
        {
          title: this.$t('research.serial-number'),
          width: 200,
          dataIndex: "index",
          align: "center",
          customRender: (value, row, index) => {
            return (
              (this.pagination.current - 1) * this.pagination.pageSize +
              1 + index
            );
          },
          ellipsis: true
        },
        // 失效
        {
          title: this.$t('research.failure'),
          width: 320,
          dataIndex: "faultName",
          align: "center",
          ellipsis: true
        },
        // 功能
        {
          title: this.$t('research.function'),
          width: 320,
          dataIndex: "functionName",
          align: "center",
          ellipsis: true
        },
        // 结构
        {
          title: this.$t('research.structure'),
          width: 320,
          align: "center",
          dataIndex: "struName",
          ellipsis: true
        },
        // 操作
        {
          title: this.$t('research.operate'),
          width: 150,
          dataIndex: "action",
          align: "center",
          fixed: "right",
          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 //总条数
      }
    };
  },

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

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

  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() {
      if (this.showViewDrawer) {
        
        // 选中包裹表格的 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() {
      if (this.showViewDrawer) {
        this.tableWidth = this.$refs.tableRef !== undefined ? this.$refs.tableRef.$el.offsetWidth : 1;
      }
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal(){
      if (this.showViewDrawer) {
        this.columnsWidth = this.tableColumns.reduce((sum, column) => sum + column.width, 0); 
      }
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed() {
      if (this.showViewDrawer) {
        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 = 150;
        }
      }
    },

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

    // 删除
    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.$route.query.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(this.issueId);
            } else {
              _that.$message.error(res.message);
            }
          });
        }
      });
    },
    // 初始化表单
    getResearch(id, fmeaId) {
      this.$api.getOneResearch({
        id: id,
        fmeaId: fmeaId
      }).then((response) => {
        if (response.flag) {
          this.formData = response.data;
        } else {
          this.$message.error(response.message);
        }
      });
    },
    // 初始化表格
    initSourceData(id, fmeaId) {
      this.issueId = id;
      let data = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        id: id,
        fmeaId: fmeaId
      }
      this.$api.getResearchTree(data).then((res) => {
        if (res.flag) {
          this.sourceData = res.data.data;
          this.pagination.total = res.data.total;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 返回
    handleClose() {
      this.showViewDrawer = false;
      this.formData = {};
      this.sourceData = [];
      this.$emit("initData");
    },
  }
};
</script>

<style lang="less" scoped>

.ellipsis-text {
  display: block; /* 确保文本内容可以设置为块级元素 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
  white-space: nowrap; /* 防止文本换行 */
  max-width: 100%; /* 根据需要调整或移除 */
}

.attachment-color {
  color: #409eff;
}
</style>
