<template>
  <div class="box">
    <!--整车DVP频次-->
    <a-card class="layout-card">
      <a-form layout='vertical'>
        <a-row :gutter='24'>
          <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
            <!-- 试验代码 -->
            <a-form-item :label="$t('dvp.full.vehicle.dvp.test-code')">
              <a-input
                v-model='formDataFrequency.testCode'
                :placeholder="$t('global-btn.please-enter') + $t('dvp.full.vehicle.dvp.test-code')"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
            <!-- 试验内容 -->
            <a-form-item :label="$t('dvp.full.vehicle.dvp.test-content')">
              <a-input
                v-model='formDataFrequency.testContent'
                :placeholder="$t('global-btn.please-enter') + $t('dvp.full.vehicle.dvp.test-content')"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
            <!-- 试验标准 -->
            <a-form-item :label="$t('base.info.Test-standards')">
              <a-input
                v-model='formDataFrequency.testStandard'
                :placeholder="$t('global-btn.please-enter') + $t('base.info.Test-standards')"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
            <!-- 备注 -->
            <a-form-item :label="$t('dvp.full.vehicle.dvp.notes')">
              <a-input
                v-model='formDataFrequency.remark'
                :placeholder="$t('global-btn.please-enter') + $t('dvp.full.vehicle.dvp.notes')"
                allowClear
              />
            </a-form-item>
          </a-col>
          <!-- 按钮 -->
          <a-col :lg='8' :md='24' :sm='24' :xl='24' :xs='24'>
            <a-form-item :label="'\xa0'" class='tr'>
              <!-- 重置 -->
              <a-button class='ml10' @click='resetFrequency'>
                {{ $t('global-btn.reset') }}
              </a-button>
              <!-- 查询 -->
              <a-button class='ml10' type='primary' @click='editTableDataInit'>
                {{ $t('global-btn.search') }}
              </a-button>
              <!-- 新建 -->
              <a-button class='ml10' @click='doSave' type="primary" :disabled="isLook || frequencyButtonFlag">
                {{ $t('global-btn.new') }}
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <!-- 表格 -->
    <a-card class="layout-card" :style="{ height: tableHeight }">
      <a-table
        ref="editTableRef"
        :columns="editColumns"
        :dataSource="editTableData"
        :pagination="frequencyPagination"
        :rowKey="(record, index) => { return index; }"
        :loading="tableLoading"
        size="small"
        bordered
        @change='handlePageChange'
        :scroll="{ x: editTableWidth, y: tableHeightValue }"
        :components='components'
      >
        <!-- 序号列 -->
        <template slot='index' slot-scope='text, record, index'>
          <span>{{ index + 1 }}</span>
        </template>

        <!-- P0到P8频次列插槽 -->
        <template slot="P0" slot-scope="text, row">
          <a-input-number v-model.trim="row.P0" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P1" slot-scope="text, row">
          <a-input-number v-model.trim="row.P1" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P2" slot-scope="text, row">
          <a-input-number v-model.trim="row.P2" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P3" slot-scope="text, row">
          <a-input-number v-model.trim="row.P3" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P4" slot-scope="text, row">
          <a-input-number v-model.trim="row.P4" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P5" slot-scope="text, row">
          <a-input-number v-model.trim="row.P5" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P6" slot-scope="text, row">
          <a-input-number v-model.trim="row.P6" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P7" slot-scope="text, row">
          <a-input-number v-model.trim="row.P7" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <template slot="P8" slot-scope="text, row">
          <a-input-number v-model.trim="row.P8" :min="0" :placeholder="$t('global-btn.please-enter')" @change="flushAll" @blur="saveReform(row)"></a-input-number>
        </template>

        <!-- 备注 -->
        <template slot="remark" slot-scope="text, row">
          <a-textarea v-model.trim="row.remark" :maxLength="300" autoSize :placeholder="$t('global-btn.please-enter') + $t('dvp.full.vehicle.dvp.notes')" @blur="saveReform(row, true)"></a-textarea>
        </template>

        <!-- 操作 -->
        <template slot="action" slot-scope="name, row, index">
          <div>
            <!-- 保存 -->
<!--            <a class="operate-btn"-->
<!--              :disabled="isLook || frequencyButtonFlag"-->
<!--              @click="saveReform(row)">-->
<!--              <a-tooltip :title="$t('global-btn.save')">-->
<!--                <a-icon type="check"/>-->
<!--              </a-tooltip>-->
<!--            </a>-->
            <!-- 取消 -->
            <a class="ml10 operate-btn"
              :disabled="isLook || frequencyButtonFlag"
              @click="cancel(row)">
              <a-tooltip :title="$t('global-btn.delete')">
                <i class='iconfont iconshanchu'></i>
              </a-tooltip>
            </a>
          </div>
        </template>
      </a-table>
    </a-card>
    <!-- 新建频次 -->
    <AddFrequency ref="addFrequency" @editTableDataInit="editTableDataInit" />
  </div>
</template>

<script>

import AddFrequency from "./addFrequency.vue";

export default {
  name: "EditDvpFrequency",
  components: {
    AddFrequency
  },
  data() {
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props;
          // 此处的this.columns 是定义的table的表头属性变量
          let col = null;
          col = this.editColumns.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 {
      // 权限
      isLook: false,
      /** 按钮显隐 */
      frequencyButtonFlag: false,
      /** 编辑 表头信息 */
      editColumns: [
        // 序号
        {
          title: () => this.$t('dvp.full.vehicle.dvp.serial-number'),
          width: 50,
          dataIndex:'index',
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true
        },
        // 试验代码
        {
          title: () => this.$t('dvp.full.vehicle.dvp.test-code'),
          width: 150,
          align: 'center',
          dataIndex: 'testCode',
          ellipsis: true
        },
        // 试验内容
        {
          title: () => this.$t('dvp.full.vehicle.dvp.test-content'),
          width: 200,
          align: 'center',
          dataIndex: 'testContent',
          ellipsis: true
        },
        // 试验标准
        {
          title: () => this.$t('base.info.Test-standards'),
          width: 200,
          align: 'center',
          dataIndex: 'testStandard',
          ellipsis: true
        }
      ],
      /** 编辑 表格数据 */
      editTableData: [],
      editColumnsWidth: 0,
      /** 修改表格数据 */
      /** 表格Loading */
      tableLoading: false,
      editTableWidth: 0,
      /** 分页 */
      frequencyPagination: {
        size: 'small',
        current: 1,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total => this.$t('global-constant.table.show-total', {total: `${total}`}), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100', '200'], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        total: 0, //总条数
        showQuickJumper: true
      },
      formDataFrequency: {
        /** 试验代码 */
        testCode: undefined,
        /** 试验内容 */
        testContent: undefined,
        /** 试验标准 */
        testStandard: undefined,
        /** 备注 */
        remark: undefined
      },
      /** 表格高度 */
      tableHeight: window.innerHeight - 421 + 'px',
      tableHeightValue: window.innerHeight - 540,
    };
  },
  watch: {
    editColumns: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    },
    editTableWidth: {
      handler() {
        this.$nextTick(() => {
          // 获取表格的总宽度
          this.handleResize();
          // 计算 width 属性的总和
          this.getColumnWidthTotal();
          // 动态修改fixe属性
          this.changeFixed();
          // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
          this.getTableDivCss();
        });
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.isLook = this.$api.isLook === '1'
    // 初始化表格数据
    this.editTableDataInit();
    // 初始化表格
    this.initTableColumns();
    // 监听页面窗体大小变化
    window.addEventListener('resize', this.handleResize);
    // 修改table表格表头外边盒子的背景颜色以及外边距，以适应表格动态变化
    this.getTableDivCss();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 421 + 'px';
      this.tableHeightValue = window.innerHeight - 421;
    };
  },
  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(250, 250, 250)';
        // 表头外层盒子的的实际样式
        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.editTableWidth = this.$refs.editTableRef.$el.offsetWidth;
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal(){
      this.editColumnsWidth = this.editColumns.reduce((sum, column) => sum + column.width, 0);
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed(){
      if (this.editColumnsWidth <= this.editTableWidth) {
        // 遍历 columns 数组，将有 fixed 属性的元素的 fixed 值设置为 false（当有固定列时，列宽总和小于表格总宽度时会串行）
        this.editColumns.forEach((column) => {
          if (column.fixed) {
            column.fixed = false;
          }
        });
        // 获取除最后一列以外其他列的宽度总和
        let otherColumnsWidth = this.editColumns.slice(0, -1).reduce((total, column) => {
          return total + column.width;
        }, 0);
        // 将最后一列的宽度设置为剩余宽度，避免页面表头与内容显示串行
        this.editColumns[this.editColumns.length - 1].width = this.editTableWidth - otherColumnsWidth;
      } else {
        // 恢复最后一列原始宽度
        this.editColumns[this.editColumns.length - 1].width = 150;
      }
    },

    /**
     * 初始化表格列
     */
    initTableColumns() {
      // 添加P0到P8频次
      for (let i = 0; i <= 8; i++) {
        let addColumns = {
          title: this.$t('dvp.full.vehicle.dvp.frequency',{ name : `${i}`}),
          width: 170,
          align: 'center',
          dataIndex: 'P' + i,
          scopedSlots: {
            customRender: 'P' + i
          }
        };
        this.editColumns.push(addColumns);
      }
      // 添加备注
      let addNotesColumns = {
        title: this.$t('dvp.full.vehicle.dvp.notes'),
        align: 'center',
        width: 200,
        dataIndex: 'remark',
        scopedSlots: {
          customRender: 'remark'
        }
      };
      this.editColumns.push(addNotesColumns);
      // 添加操作列
      let addActionColumns = {
        title: this.$t('global-constant.operation'),
        align: 'center',
        width: 50,
        scopedSlots: {
          customRender: 'action'
        }
      };
      this.editColumns.push(addActionColumns);
    },

    /**
     * 初始化
     */
    editTableDataInit() {
      let _that = this;
      _that.tableLoading = true;
      _that.$api.getDvpInitDvpFrequencyList({
        dvpId: _that.$route.query.dvpId,
        /** 试验代码 */
        testCode: _that.formDataFrequency.testCode,
        /** 试验内容 */
        testContent: _that.formDataFrequency.testContent,
        /** 试验标准 */
        testStandard: _that.formDataFrequency.testStandard,
        /** 备注 */
        remark:_that.formDataFrequency.remark,
        /** 分页 */
        pagination: {
					pageCurrent: _that.frequencyPagination.current,
					pageSize: _that.frequencyPagination.pageSize
				}
      }).then(res => {
        if (res.flag) {
          _that.editTableData = res.data.data || [];
          _that.frequencyPagination.total = res.data.total || 0;
          // 循环处理P0-P8频次数据
          _that.editTableData.forEach(item => {
            let frequencyList = item.frequencyList;
            if (frequencyList && frequencyList.length > 0) {
              frequencyList.forEach((data, index) => {
                item['P' + index] = data;
              })
            }
          })
        } else {
          _that.$notification.error({message: res.message});
        }
      }).finally(() => {
        _that.tableLoading = false;
      });
      // 变更申请按钮显示隐藏，如果DVP编制进行到DVP验证阶段，则显示
      let data = {
        dvpId: _that.$store.getters.dvpId,
        dvpType: _that.$store.getters.dvpType
      }
      _that.$api.getDvpCurrentStep(data).then(res => {
        if (res.flag) {
          _that.frequencyButtonFlag = res.data === 2 ;
        }
      });
    },

    /**
     * 新建频次
     */
    doSave() {
      this.$refs.addFrequency.addFlag = true;
      this.$refs.addFrequency.initData();

    },
    /**
     * 编辑频次表格 保存
     * @param val
     * @param remarkFlag 是否为备注更新
     */
    saveReform(val, remarkFlag) {
      let _that = this;
      let frequencyList = [];
      // 频次数据整理
      for (let index = 0; index <= 8; index++) {
        const element = val['P' + index] || '';
        frequencyList.push(element);
      }
      if (val.frequencyList == null || val.frequencyList.sort().join(",") !== frequencyList.sort().join(",") || remarkFlag) {
        let data = {
          dvpId: _that.$route.query.dvpId,
          frequencyId: val.id,
          frequencyList: frequencyList,
          remark: val.remark
        };
        _that.$api.dvpSaveFrequency(data).then(res => {
          if (res.flag){
            _that.$message.success(res.message, 1);
          } else{
            _that.$message.error(res.message, 1);
          }
        })
      }
    },

    /**
     * 编辑表格 删除
     * @param val
     */
    cancel(val) {
      let _that = this;
			_that.$confirm({
				title: _that.$t('fmea.warn'),
				content: _that.$t('global-message.warn.delete-frequency'),
				icon: 'exclamation-circle',
				okText: _that.$t('global-btn.confirm'),
				cancelText: _that.$t('global-btn.cancel'),
				onOk() {
      let data = {
        dvpId: _that.$route.query.dvpId,
        frequencyId: val.id,
        isDeleteFlag: 1
      };
      _that.$api.dvpSaveFrequency(data).then(res => {
        if (res.flag){
          _that.$message.success(res.message, 1);
          _that.editTableDataInit();
        } else{
          _that.$message.error(res.message, 1);
        }
      })
				},
				onCancel() {
				}
			});
    },
    /**
     * 重置试验频次
     */
    resetFrequency() {
      /** 表单参数 */
      this.formDataFrequency = {
        /** 试验代码 */
        testCode: undefined,
        /** 试验内容 */
        testContent: undefined,
        /** 试验标准 */
        testStandard: undefined,
        /** 备注 */
        remark: undefined
      };
      this.frequencyPagination.current = 1;
      this.frequencyPagination.pageSize = 10;
      this.editTableDataInit();
    },
    /**
     * 表格 - 点击分页中数字触发的方法
     * @param pagination
     */
    handlePageChange(pagination) {
      this.frequencyPagination.current = pagination.current;
      this.frequencyPagination.pageSize = pagination.pageSize;
      this.frequencyPagination.pageNo = pagination.current;
      this.editTableDataInit();
    },
    /**
     * 刷新频次数据
     */
    flushAll() {
      this.$forceUpdate();
    }
  },
  //剔除页面窗体大小变化得监听事件
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>
<style lang='less' scoped>
.layout-card {
  padding: 12px;
}
.box {
  padding: 0 12px !important;
}
.text-right {
  text-align: right;
}
</style>
