<template>
  <a-modal
    :visible="measureVisible"
    :title="measureType === 1 ?
    (measureTitleFlag === 1 ? $t('summary-archive.fmea-table.risk-analysis-preventive-measures') : $t('summary-archive.fmea-table.risk-analysis-detection-measures'))
    : (measureTitleFlag === 1 ? $t('summary-archive.fmea-table.preventive-measures-for-DFMEA-optimization') : $t('summary-archive.fmea-table.DFMEA-optimized-detection-measures'))"
    width="800px"
    @ok="handleOk"
    :getContainer="() => displayElemnt"
    @cancel="handleCancel">
    <!-- 新增 -->
    <a-button class="mb10" type='primary' @click="addMeasure">
      {{ $t('global-btn.insert') }}
    </a-button>
    <a-tabs :activeKey='tabKey' @change="callback" v-if="measureTitleFlag === 2">
      <!-- 失效原因措施 -->
      <a-tab-pane :key="'1'" :tab="$t('summary-archive.fmea-table.risk-analysis-cause-of-failure-measures')">
        <a-table
          ref="tableRef"
          bordered
          :dataSource="tableData"
          :columns="tableColumns"
          :rowKey="(row, index) => { return index; }"
          size="small"
          :scroll="{ x: tableWidth, y: 400 }"
          :pagination="false"
          :components='components'
          >
          <!-- 措施名称 -->
          <template slot="measure" slot-scope="text, record, index">
            <a-input allowClear v-model="record.name"/>
          </template>
          <!-- 操作列-删除 -->
          <template slot="action" slot-scope="text, record">
            <a class="operate-btn" @click="deleteMeasure(record)">
              <a-tooltip :title="$t('global-btn.delete')">
                <i class="iconfont iconshanchu"></i>
              </a-tooltip>
            </a>
          </template>
        </a-table>
      </a-tab-pane>
      <!-- 失效模式措施 -->
      <a-tab-pane :key="'2'" :tab="$t('summary-archive.fmea-table.risk-analysis-failure-mode-measures')">
        <a-table
          ref="tableRef"
          bordered
          :dataSource="modeTableData"
          :columns="tableColumns"
          :rowKey="(row, index) => { return index; }"
          size="small"
          :scroll="{ x: tableWidth, y: 400 }"
          :pagination="false"
          :components='components'
          >
          <!-- 措施名称 -->
          <template slot="measure" slot-scope="text, record, index">
            <a-input allowClear v-model="record.name"/>
          </template>
          <!-- 操作列-删除 -->
          <template slot="action" slot-scope="text, record">
            <a class="operate-btn" @click="deleteMeasure(record)">
              <a-tooltip :title="$t('global-btn.delete')">
                <i class="iconfont iconshanchu"></i>
              </a-tooltip>
            </a>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <div v-if="measureTitleFlag === 1">
      <a-table
        ref="tableRef"
        bordered
        :dataSource="tableData"
        :columns="tableColumns"
        :rowKey="(row, index) => { return index; }"
        size="small"
        :scroll="{ x: tableWidth, y: 400 }"
        :pagination="false"
        :components='components'
        >
        <!-- 措施名称 -->
        <template slot="measure" slot-scope="text, record, index">
          <a-input allowClear v-model="record.name"/>
        </template>
        <!-- 操作列-删除 -->
        <template slot="action" slot-scope="text, record">
          <a class="operate-btn" @click="deleteMeasure(record)">
            <a-tooltip :title="$t('global-btn.delete')">
              <i class="iconfont iconshanchu"></i>
            </a-tooltip>
          </a>
        </template>
      </a-table>
    </div>
  </a-modal>
</template>

<script>
import VueDraggableResizable from "vue-draggable-resizable";

export default {
  name: "ModifyMeasure",
  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 {
      tabKey: '1',
      // 表格总宽度
      tableWidth: 0,
      // 表格各列宽度总和
      columnsWidth: 0,
      // 模态框内容是否改变
      isModalChange: false,
      // 模态框是否可见
      measureVisible: false,
      // 模态框标题标识
      measureTitleFlag: undefined,
      // 措施类型 1：当前措施 2：优化措施
      measureType: undefined,
      // 保存提示
      saveMessage: '',
      // 失效原因措施组struId
      groupId:'',
      // 失效模式措施组struId
      groupDetectionId:'',
      // 措施类型
      struTypeCode: '',
      // 措施名称
      measureName: '',
      // 失效模式的措施数据源
      modeTableData: [],
      // 失效原因的措施数据源
      tableData: [],
      originalTableData: [],
      newTableData: [],
      // 修改的数据集合
      updateRows: [],
      // 新增的数据集合
      addRows: [],
      // 删除的数据集合
      delRows: [],
      // 表头
      tableColumns:[
      {
          title: () => this.$t("summary-Archive.feature-list.serial-number"),
          width: 100,
          align: "center",
          // dataIndex: "index",
          // scopedSlots: { customRender: "index" },
          ellipsis: true,
          customRender: (text, record, index) => `${index + 1}` // 序号计算
        },
        // 当前探测/预防措施名称
        {
          title: () => this.$t("summary-archive.fmea-table.risk-analysis-measures-name"),
          width: 550,
          align: "center",
          dataIndex: "name",
          scopedSlots: { customRender: "measure" },
          ellipsis: true
        },
        {
					title: () => this.$t('global-btn.delete'),
					dataIndex: 'action',
					width: 100,
					align: 'center',
					scopedSlots: {
						customRender: 'action'
					},
					className: 'operationBtn'
				}
      ],
      // 挂载元素
      displayElemnt: undefined,
      // 切换tap保存标识
      changeSaveFlag: false
    };
  },
  watch: {
    tableColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
        });
      },
      deep: true,
      immediate: true
    },
    tableWidth: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
        });
      },
      deep: true,
      immediate: true
    }
  },
  // 剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // TAB页切换
    callback(key) {
      this.tabKey = key;
      this.changeSave();
      this.changeTabReset();
      this.list();
    },
    // 初始化方法
    list() {
      let _that = this;
      let data = {};
      if (_that.measureTitleFlag === 2 && _that.tabKey === '2') {
        // 失效模式参数
        data = {
          fmeaId: _that.$store.getters.rfmeaId,
          struId: _that.groupDetectionId,
          struTypeCode: _that.struTypeCode
        }
      } else {
        // 失效原因参数
        data = {
          fmeaId: _that.$store.getters.rfmeaId,
          struId: _that.groupId,
          struTypeCode: _that.struTypeCode
        }
      }
      _that.$api.getGroupByMeasureList(data).then(res => {
        if (res.flag) {
          if (_that.measureTitleFlag === 2 && _that.tabKey === '2') {
            _that.modeTableData = res.data;
             // 对originalTableData进行深拷贝，如果用浅拷贝，指向的是同一个地址
             _that.originalTableData = JSON.parse(JSON.stringify(_that.modeTableData));
            // 浅拷贝一份新的表格集合，用于保存时的逻辑
            _that.newTableData = [..._that.modeTableData];
          } else {
            _that.tableData = res.data;
            // 对originalTableData进行深拷贝，如果用浅拷贝，指向的是同一个地址
            _that.originalTableData = JSON.parse(JSON.stringify(_that.tableData));
            // 浅拷贝一份新的表格集合，用于保存时的逻辑
            _that.newTableData = [..._that.tableData];
          }
        } else {
          _that.$message.error(res.message, 1);
        }
      });
    },
    // 新增
    addMeasure() {
      // 添加新数据
      const newData = { id: Date.now(), name: '' };
      if (this.measureTitleFlag === 2 && this.tabKey === '2') {
        this.modeTableData.push(newData);
      } else {
        this.tableData.push(newData);
      }
      this.addRows.push(newData);
    },
    // 删除
    deleteMeasure(record) {
      let _that = this;
      // 删除已保存的措施
      if (record.fmeaId && record.struId) {
        // 删除的数据集合
        _that.delRows.push(record.struId);
        if (_that.measureTitleFlag === 2 && _that.tabKey === '2') {
          let index = _that.modeTableData.findIndex(item => item.struId === record.struId);
          if (index !== -1) {
            _that.modeTableData.splice(index, 1);
          }
        } else {
          let index = _that.tableData.findIndex(item => item.struId === record.struId);
          if (index !== -1) {
            _that.tableData.splice(index, 1);
          }
        }
      } else { // 删除未保存的措施
        if (_that.measureTitleFlag === 2 && _that.tabKey === '2') {
          let index = _that.modeTableData.findIndex(item => item.id === record.id);
          if (index !== -1) {
            _that.modeTableData.splice(index, 1);
            _that.addRows = _that.addRows.filter(item => item.id !== record.id);
          }
        } else {
          let index = _that.tableData.findIndex(item => item.id === record.id);
          if (index !== -1) {
            _that.tableData.splice(index, 1);
            _that.addRows = _that.addRows.filter(item => item.id !== record.id);
          }
        }
      }
    },
    // 输入框新增/修改措施-校验
    validatePreventionMeasureData(mfmeaStruInputModels, mfmeaStruInputModelsByUpdate) {
      if (mfmeaStruInputModels || mfmeaStruInputModelsByUpdate) {
        for (let i = 0; i < mfmeaStruInputModels.length; i++) {
          let name = mfmeaStruInputModels[i].name;
          // 非空校验
          if (!name || name === '' || name.trim().length === 0) {
            this.$message.warning(this.$t('summary-archive.fmea-table.risk-analysis-measures-name-not-be-empty'));
            return false;
          } else if (name.trim().length > 1000) { // 长度校验
              this.$message.warning(this.$t('summary-archive.fmea-table.risk-analysis-measures-name-not-be-exceed'));
              return false;
          }
        }
        for (let i = 0; i < mfmeaStruInputModelsByUpdate.length; i++) {
          let name = mfmeaStruInputModelsByUpdate[i].name;
          // 非空校验
          if (!name || name === '' || name.trim().length === 0) {
            this.$message.warning(this.$t('summary-archive.fmea-table.risk-analysis-measures-name-not-be-empty'));
            return false;
          } else if (name.trim().length > 1000) { // 长度校验
              this.$message.warning(this.$t('summary-archive.fmea-table.risk-analysis-measures-name-not-be-exceed'));
              return false;
          }
        }
      }
      return true;
    },
    // 确定按钮
    handleOk () {
      let _that = this;
      _that.handleSave();
    },
    // 保存
    handleSave() {
      let _that = this;
      // 新增的数据集合
      let mfmeaStruInputModels = [];
      // 遍历addRows将名称插入到mfmeaStruInputModels中
      _that.addRows.forEach(item => {
        mfmeaStruInputModels.push({
          name: item.name
        });
      });
      // 循环表格数据
      _that.newTableData.forEach((record, index) => {
        if (record.name !== _that.originalTableData[index].name) {
          // 将修改后的名称push到updateRows中
          _that.updateRows.push({
            struId: record.struId,
            name: record.name
          });
        }
      });
      // 修改的数据集合
      let mfmeaStruInputModelsByUpdate = [];
      _that.updateRows.forEach(item => {
        mfmeaStruInputModelsByUpdate.push({
            struId: item.struId,
            name: item.name
          });
      });
      // 过滤出删除的数据
      mfmeaStruInputModelsByUpdate = mfmeaStruInputModelsByUpdate.filter(item => !_that.delRows.includes(item.struId));
      // 未进行更改
      if (_that.updateRows.length == 0 && _that.addRows.length == 0 && _that.delRows.length === 0) {
          _that.isModalChange = false;
          // 如果探测措施弹窗切换tap的时候调用保存接口，关闭弹窗的时候刷新数据
          if(_that.changeSaveFlag) {
            _that.close();
          } else {
            _that.measureVisible = false;
          }
      } else if (_that.updateRows.length > 0 || _that.addRows.length > 0 || _that.delRows.length > 0) {
        // 校验
        if (!_that.validatePreventionMeasureData(mfmeaStruInputModels, mfmeaStruInputModelsByUpdate)) {
          _that.updateRows = [];
          return;
        }
        let data = {};
        if (_that.measureTitleFlag === 2 && _that.tabKey === '2') {
          if (_that.groupDetectionId) {
            data = {
              fmeaId: _that.$store.getters.rfmeaId,
              groupStruId: _that.groupDetectionId,
              struTypeCode: _that.struTypeCode,
              libraryAddFlag: false,
              mfmeaStruInputModels: mfmeaStruInputModels,
              mfmeaStruInputModelsByUpdate: mfmeaStruInputModelsByUpdate,
              struIdListByDel: _that.delRows
            };
          } else {
            _that.$message.warning(_that.$t('summary-archive.fmea-table.risk-analysis-unable-toadd'));
            return;
          }
        } else {
          if (_that.groupId) {
            data = {
              fmeaId: _that.$store.getters.rfmeaId,
              groupStruId: _that.groupId,
              struTypeCode: _that.struTypeCode,
              libraryAddFlag: false,
              mfmeaStruInputModels: mfmeaStruInputModels,
              mfmeaStruInputModelsByUpdate: mfmeaStruInputModelsByUpdate,
              struIdListByDel: _that.delRows
            };
          } else {
            _that.$message.warning(_that.$t('summary-archive.fmea-table.risk-analysis-unable-toadd'));
            return;
          }
        }
        _that.$api.updateAndAddMeasure(data).then(res => {
          if (res.flag) {
            _that.$message.success(res.message, 1);
            _that.isModalChange = true;
          } else {
            _that.$message.error(res.message, 1);
          }
        }).finally(()=>{
          _that.close();
        });
      }
    },
    // TAB切换保存
    changeSave() {
      let _that = this;
      // 新增的数据集合
      let mfmeaStruInputModels = [];
      // 遍历addRows将名称插入到mfmeaStruInputModels中
      _that.addRows.forEach(item => {
        mfmeaStruInputModels.push({
          name: item.name
        });
      });
      // 循环表格数据
      _that.newTableData.forEach((record, index) => {
        if (record.name !== _that.originalTableData[index].name) {
          // 将修改后的名称push到updateRows中
          _that.updateRows.push({
            struId: record.struId,
            name: record.name
          });
        }
      });
      // 修改的数据集合
      let mfmeaStruInputModelsByUpdate = [];
      _that.updateRows.forEach(item => {
        mfmeaStruInputModelsByUpdate.push({
            struId: item.struId,
            name: item.name
          });
      });
      // 过滤出删除的数据
      mfmeaStruInputModelsByUpdate = mfmeaStruInputModelsByUpdate.filter(item => !_that.delRows.includes(item.struId));
      // 未进行更改
      if (_that.updateRows.length == 0 && _that.addRows.length == 0 && _that.delRows.length === 0) {
          _that.isModalChange = false;
      } else if (_that.updateRows.length > 0 || _that.addRows.length > 0 || _that.delRows.length > 0) {
        // 校验
        if (!_that.validatePreventionMeasureData(mfmeaStruInputModels, mfmeaStruInputModelsByUpdate)) {
          _that.updateRows = [];
          return;
        }
        // 切换tap保存标识
        _that.changeSaveFlag = true;
        let data = {};
        if (_that.measureTitleFlag === 2 && _that.tabKey === '1') {
          if (_that.groupDetectionId) {
            data = {
              fmeaId: _that.$store.getters.rfmeaId,
              groupStruId: _that.groupDetectionId,
              struTypeCode: _that.struTypeCode,
              libraryAddFlag: false,
              mfmeaStruInputModels: mfmeaStruInputModels,
              mfmeaStruInputModelsByUpdate: mfmeaStruInputModelsByUpdate,
              struIdListByDel: _that.delRows
            };
          } else {
            _that.$message.warning(_that.$t('summary-archive.fmea-table.risk-analysis-unable-toadd'));
            return;
          }
        } else {
          if (_that.groupId) {
            data = {
              fmeaId: _that.$store.getters.rfmeaId,
              groupStruId: _that.groupId,
              struTypeCode: _that.struTypeCode,
              libraryAddFlag: false,
              mfmeaStruInputModels: mfmeaStruInputModels,
              mfmeaStruInputModelsByUpdate: mfmeaStruInputModelsByUpdate,
              struIdListByDel: _that.delRows
            };
          } else {
            _that.$message.warning(_that.$t('summary-archive.fmea-table.risk-analysis-unable-toadd'));
            return;
          }
        }
        _that.$api.updateAndAddMeasure(data).then(res => {
          if (res.flag) {
            // _that.$message.success(res.message, 1);
            _that.isModalChange = true;
          } else {
            _that.$message.error(res.message, 1);
          }
        });
      }
    },
    // 关闭
    close() {
      this.tableData = [];
      this.modeTableData = [];
      this.addRows = [];
      this.updateRows = [];
      this.delRows = [];
      this.originalTableData = [];
      this.newTableData = [];
      this.measureVisible = false;
      this.tabKey = '1';
      // 如果模态框内容发生改变则调用父组件的查询方法，否则不调用
      // if (this.isModalChange) {
      this.searchInit();
      this.isModalChange = false;
      // }
    },
    // tab页改变重置
    changeTabReset() {
      this.addRows = [];
      this.updateRows = [];
      this.delRows = [];
      this.originalTableData = [];
      this.newTableData = [];
      this.isModalChange = false;
    },
    // 关闭模态框
    handleCancel() {
      this.close();
    },
    // 设置父组件的单元格标识为true
    searchInit() {
      this.$emit('update:modifyCellFlag', true);
    },
    // 获取表格的总宽度
    handleResize() {
      if (this.measureVisible) {
        this.tableWidth = this.$refs.tableRef !== undefined ? this.$refs.tableRef.$el.offsetWidth : 1;
      }
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal() {
      if (this.measureVisible) {
        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[this.tableColumns.length - 1].width = 100;
      }
    },
  }
}
</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);
}
</style>