<template>
  <div>
    <a-modal
        :title="$t('globalComponents.masterFmeaDiff.contrast')"
        :visible='visible'
        width="80%"
        :maskClosable="false"
        @cancel="closeModal"
        :footer="null">
      <a-row class='tr'>
        <!-- 同步 -->
        <a-button type='primary' class="mb_20" @click='noMoreNotifications'>{{ $t('plan.comparison-of-differences.no-more-notifications') }}</a-button>
      </a-row>
      <a-row>
        <a-table
            ref="tableRef"
            size='small'
            :columns='tableColumns'
            :dataSource='tableData'
            :loading='tableLoading'
            :rowKey='(record, index) => { return index; }'
            :scroll='{ x: tableWidth }'
            :pagination="pagination"
            @change="handleTableChange"
            :components='components'
            bordered>
          <!-- 参考版本差异节点名称 -->
          <template slot="citedNodeName" slot-scope="text, record">
            <span v-if="'01,07,08,09,10,14,99'.indexOf(record.citedStruTypeCode) != -1" style="color: #232121">{{ record.citedNodeName ? record.citedNodeName : '' }}</span>
            <span v-if="'02'.indexOf(record.citedStruTypeCode) != -1" style="color: rgb(66, 167, 94)">{{ record.citedNodeName ? record.citedNodeName : '' }}</span>
            <span v-if="'04,05'.indexOf(record.citedStruTypeCode) != -1" style="color: #5b9bd5">{{ record.citedNodeName ? record.citedNodeName : '' }}</span>
            <span v-if="'06'.indexOf(record.citedStruTypeCode) != -1" style="color: rgb(200, 77, 60)">{{ record.citedNodeName ? record.citedNodeName : '' }}</span>
          </template>
          <!-- 比较版本差异节点名称 -->
          <template slot="quoteNodeName" slot-scope="text, record">
            <span v-if="'01,07,08,09,10,14,99'.indexOf(record.quoteStruTypeCode) != -1" style="color: #232121">{{ record.quoteNodeName ? record.quoteNodeName : '' }}</span>
            <span v-if="'02'.indexOf(record.quoteStruTypeCode) != -1" style="color: rgb(66, 167, 94)">{{ record.quoteNodeName ? record.quoteNodeName : '' }}</span>
            <span v-if="'04,05'.indexOf(record.quoteStruTypeCode) != -1" style="color: #5b9bd5">{{ record.quoteNodeName ? record.quoteNodeName : '' }}</span>
            <span v-if="'06'.indexOf(record.quoteStruTypeCode) != -1" style="color: rgb(200, 77, 60)">{{ record.quoteNodeName ? record.quoteNodeName : '' }}</span>
          </template>
          <!-- 同步 -->
          <template slot="sync" slot-scope="text, record">
            <a-button class="ml7" size="small" @click="sync(record)" type="primary">
              {{ $t("plan.comparison-of-differences.sync") }}
            </a-button>
          </template>
          <!-- 差异状态 -->
          <template slot="optType" slot-scope="text, record">
            <span v-if="record.optType === 1" class="ant-tag ant-tag-has-color ck" style="background-color: #03B615;">{{ $t("plan.comparison-of-differences.add") }}</span>
            <span v-if="record.optType === 2" class="ant-tag ant-tag-has-color ck" style="background-color: #2DB7F5;">{{ $t("plan.comparison-of-differences.update") }}</span>
            <span v-if="record.optType === 3" class="ant-tag ant-tag-has-color ck" style="background-color: #D9001B;">{{ $t("plan.comparison-of-differences.project-del") }}</span>
            <span v-if="record.optType === 4" class="ant-tag ant-tag-has-color ck" style="background-color: #D9001B;">{{ $t("plan.comparison-of-differences.master-del") }}</span>
          </template>
        </a-table>
      </a-row>
    </a-modal>
  </div>
</template>

<script>

import AntSpinDot from "@/components/AntSpinDot/index.vue";
import VueDraggableResizable from 'vue-draggable-resizable';

export default {
  name: 'MasterFmeaDiff',
  components: {
    AntSpinDot, 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 {
      visible: false,

      /** 加载对象 */
      loader: undefined,
      /** 是否显示空状态 */
      isEmpty: true,
      /** 差异总数 */
      diffTotal: 0,
      /** 当前位置 */
      curPosition: 0,
      /** 分页 */
      pagination: {
        current: 1,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total => this.$t('plan.comparison-of-differences.a-total-of-data' , {total:`${total}`}), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100', '200'], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        total: 0, //总条数
        showQuickJumper: true,
        position: "bottom"
      },
      /** 表格列 */
      tableColumns: [
        {
          title: () => this.$t('plan.comparison-of-differences.serial-number'),
          dataIndex: 'index',
          width: 100,
          align: 'center',
          customRender: (value, row, index) => {
            return (this.pagination.current - 1) * this.pagination.pageSize + index + 1;
          }
        },
        {
          title: () => this.$t('plan.comparison-of-differences.super-structure') +
              ' (' + (this.fmeaType != 3 ? this.$t('plan.comparison-of-differences.master-fmea') : this.$t('plan.comparison-of-differences.project-fmea')) + ')',
          width: 300,
          align: 'center',
          dataIndex: 'citedParentStruName',
          ellipsis: true
        },
        {
          title: () => this.$t('plan.comparison-of-differences.reference-version') +
              ' (' + (this.fmeaType != 3 ? this.$t('plan.comparison-of-differences.master-fmea') : this.$t('plan.comparison-of-differences.project-fmea')) + ')',
          width: 300,
          align: 'center',
          dataIndex: 'citedNodeName',
          scopedSlots: {
            customRender: 'citedNodeName'
          },
          ellipsis: true
        },
        {
          title: () => this.$t('plan.comparison-of-differences.super-structure') +
              ' (' + (this.fmeaType != 3 ? this.$t('plan.comparison-of-differences.project-fmea') : this.$t('plan.comparison-of-differences.master-fmea')) + ')',
          width: 300,
          align: 'center',
          dataIndex: 'quoteParentStruName',
          ellipsis: true
        },
        {
          title: () => this.$t('plan.comparison-of-differences.compare-version') +
              ' (' + (this.fmeaType != 3 ? this.$t('plan.comparison-of-differences.project-fmea') : this.$t('plan.comparison-of-differences.master-fmea')) + ')',
          width: 300,
          align: 'center',
          dataIndex: 'quoteNodeName',
          scopedSlots: {
            customRender: 'quoteNodeName'
          },
          ellipsis: true
        },
        {
          title: () => this.$t('plan.comparison-of-differences.sync'),
          width: 100,
          align: 'center',
          dataIndex: 'sync',
          scopedSlots: {
            customRender: 'sync'
          },
          ellipsis: true
        },
        {
          title: () => this.$t('plan.comparison-of-differences.status'),
          width: 100,
          align: 'center',
          dataIndex: 'optType',
          scopedSlots: {
            customRender: 'optType'
          },
          ellipsis: true
        }
      ],
      /** 表格数据 */
      tableData: [],
      /** 表格loading */
      tableLoading: false,
      /** 表格总宽度 */
      tableWidth: 0,
      /** 表格各列宽度总和 */
      columnsWidth: 0,
      masterFmeaId: undefined,
      curFmeaId: undefined,
      /** 同步按钮可以点击状态 */
      syncButtonEnableStatus: true,
      /** fmea类型 3：家族fmea，其他：项目fmea*/
      fmeaType: undefined,
      fmeaId: undefined
    };
  },
  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
    }
  },
  mounted() {
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
    // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
    this.getTableDivCss();
  },
  //剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  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.visible ? 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) {
        // 遍历 tableColumns 数组，将有 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].width = 150;
      }
    },
    /**
     * 弹窗--点击分页中数字触发的方法
     * @param pagination
     */
    handleTableChange(pagination) {
      this.pagination.pageSize = pagination.pageSize;
      this.pagination.current = pagination.current;
      this.pagination.pageNo = pagination.current;
    },
    /**
     * 列表
     */
    list(curFmeaId, masterFmeaId) {
      let _that = this;
      let fmeaId = _that.fmeaId;
      _that.masterFmeaId = masterFmeaId;
      _that.curFmeaId = curFmeaId;
      _that.isEmpty = true;
      _that.tableLoading = true;
      _that.$api.getQuoteMasterFmeaDiff(fmeaId).then(res => {
        if (res.flag) {
          let treeData = res.data?.treeData || [];
          _that.diffTotal = res.data?.diffNum || 0
          _that.fmeaType = res.data?.fmeaType || 1
          _that.curPosition = 0;
          if (treeData.length > 0) {
            _that.isEmpty = false;
          }
          /** 处理差异对比表格数据 */
          _that.pagination.total = _that.diffTotal;
          _that.tableData = res.data.treeData || [];
          if (_that.diffTotal <= 0) {
            // 同步后，如果差异对比全部相同，则更新通知标识
            _that.$confirm({
              title: _that.$t('global-message.warn'),
              content: _that.$t('plan.comparison-of-differences.after-all-synchronization-Prompt'),
              icon: "aaoopqa", //图标，不想用就随便写一个
              okText: _that.$t('global-btn.ok'),
              cancelText: _that.$t('global-btn.cancel'),
              onCancel() {
              },
              onOk() {
                _that.updateReferenceVersion(fmeaId);
              }
            });
          }
        } else {
          _that.$notification.error({message: res.message});
        }
      }).finally(() => {
        _that.tableLoading = false;
      });
    },
    /**
     * 关闭弹框
     */
    closeModal() {
      this.$emit("closeModal");
    },

    /**
     * 同步
     * @param id
     */
    sync(record) {
      let _that = this;
      _that.tableLoading = true;
      // 防止检索方法将loading放开导致方法重复执行
      if (!_that.syncButtonEnableStatus) return;
      _that.syncButtonEnableStatus = false;
      if (!record) return;
      let optType;
      if (_that.fmeaType === 3) {
        optType = record.optType === 4 ? 1 : record.optType;
      } else {
        optType = record.optType === 3 ? 1 : record.optType;
      }
      let struId;
      if (optType === 1) {
        struId = record.citedId;
      } else {
        struId = record.quoteId;
      }
      let data = {
        sourceFmeaId: _that.masterFmeaId,
        targetFmeaId: _that.curFmeaId,
        struId: struId,
        optType: optType,
        struTypeCode: record.struTypeCode,
      };
      if (record.struTypeCode === '01') {
        _that.$api.checkRootNode(data).then(res => {
          if (res.flag) {
            if (res.data.isSameRoot) {
              _that.nodeSync(data);
            } else {
              _that.$confirm({
                title: _that.$t('global-message.warn'),
                content: _that.$t('plan.comparison-of-differences.root-node-has-changed'),
                icon: "aaoopqa", //图标，不想用就随便写一个
                okText: _that.$t('global-btn.ok'),
                cancelText: _that.$t('global-btn.cancel'),
                onCancel() {
                },
                onOk() {
                  _that.nodeSync(data);
                }
              });
            }
          }
        });
      } else {
        _that.nodeSync(data);
      }
    },
    nodeSync(data) {
      let _that = this;
      _that.$api.nodeSync(data).then(res => {
        if (res.flag) {
          _that.$message.success(res.message, 1);
          _that.list(_that.curFmeaId, _that.masterFmeaId);
        }
      }).finally(() => {
        // 推迟半秒钟再继续执行
        setTimeout(function() {
          _that.tableLoading = false;
          // 防止检索方法将loading放开导致方法重复执行
          _that.syncButtonEnableStatus = true;
        }, 500);
      });
    },
    /**
     * 更新通知标识，当前被引用的fmea如果不升级版本则不会再通知
     * @param fmeaId
     */
    updateReferenceVersion(fmeaId) {
      let _that = this;
      _that.$api.updateReferenceVersion({
        fmeaId: fmeaId
      }).then(res => {
        if (res.flag) {
          _that.closeModal();
        } else {
          _that.$notification.error({message: res.message});
        }
      });
    },
    // 不再通知
    noMoreNotifications() {
      let _that = this;
      _that.$confirm({
        title: _that.$t('global-message.warn'),
        content: _that.$t('plan.comparison-of-differences.no-more-notifications-Prompt'),
        icon: "aaoopqa", //图标，不想用就随便写一个
        okText: _that.$t('global-btn.ok'),
        cancelText: _that.$t('global-btn.cancel'),
        onCancel() {
        },
        onOk() {
          _that.updateReferenceVersion(_that.fmeaId);
        }
      });

    }
  }
};

/**
 * 同步
 * @param id
 */
window.sync = function (id) {
  sync(id);
}
</script>

<style lang="less" scoped>

</style>
