<template>
  <div>
    <a-col class="colClass" :lg="24" :md="19" :sm="24">
      <!-- 搜索 -->
      <a-row class="mb12">
        <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('base.info.change-record.change-version')">
                <a-select
                  v-model='formData.changeVersion'
                  :placeholder="$t('base.info.change-record.pleace-select-change-version')"
                  allowClear>
                    <a-select-option
                      v-for="option in options"
                      :key="option.value"
                      :value="option.value">
                        {{ option.label }}
                    </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- 变更人 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('base.info.change-record.change-person')">
                <a-input
                  v-model='formData.changePerson'
                  :placeholder="$t('base.info.change-record.pleace-enter-change-person')"
                  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.change-record.change-type')">
                <a-select
                  v-model='formData.changeType'
                  :placeholder="$t('base.info.change-record.pleace-select-change-type')"
                  allowClear>
                  <a-select-option value="0">
                    {{ $t('base.info.change-record.all') }}
                  </a-select-option>
                  <a-select-option value="1">
                    {{ $t('base.info.change-record.insert') }}
                  </a-select-option>
                  <a-select-option value="2">
                    {{ $t('base.info.change-record.update') }}
                  </a-select-option>
                  <a-select-option value="3">
                    {{ $t('base.info.change-record.delete') }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- 变更时间 -->
            <a-col :lg='8' :md='12' :sm='24' :xl='6' :xs='24'>
              <a-form-item :label="$t('base.info.change-record.change-time')">
                <a-range-picker
                  v-model="formData.changeTime"
                  allowClear
                  style="width: 100%"
                  :format="['YYYY-MM-DD', 'YYYY-MM-DD']"
                  @change="handleChangeTime"/>
              </a-form-item>
            </a-col>
            <a-col :lg='8' :md='12' :sm='24' :xl='24' :xs='24'>
              <a-form-item :label="'\xa0'" class='tr'>
                <!--重置、查询按钮-->
                <a-row :gutter='24'>
                  <a-col :lg='24' :md='24' :sm='24' :xl='24' :xs='24'>
                    <a-form-item :label="'\xa0'" class='tr'>
                      <!-- 重置 -->
                      <a-button class="ml_10" type @click='reset'>
                        {{ $t('global-btn.reset') }}
                      </a-button>
                      <!-- 查询 -->
                      <a-button class="ml_10" type='primary' @click='search'>
                        {{ $t('global-btn.search') }}
                      </a-button>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-row>
      <!-- 表格 -->
      <div class="mb12" :style="{ height: tableHeight }" >
        <a-table
          ref="tableRef"
          size="small"
          bordered
          :components='components'
          :columns='tableColumns'
          :dataSource='tableData'
          :loading='tableLoading'
          :pagination='pagination'
          :rowKey='(record, index) => { return index; }'
          :scroll='{ x: tableWidth, y: tableHeightValue }'
          @change='handlePageChange'>
          <!-- 序号列 -->
          <template slot='index' slot-scope='text, record, index'>
            <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
          </template>
          <!-- 变更版本 -->
          <template slot='changeVersion' slot-scope='text, record, index'>
            <span>{{ record.changeVersion >= 10 ? record.changeVersion : '0' + record.changeVersion }}</span>
          </template>
          <!-- 变更类型 -->
          <template slot='changeType' slot-scope='text, record, index'>
            <span>{{ changeMap[record.changeType] || '-' }}</span>
          </template>
        </a-table>
      </div>
    </a-col>
  </div>
</template>

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

export default {
  name: "changeRecord",
  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, 50);
              }
            }
          };
          const drag = h('vue-draggable-resizable', { ...dragProps });
          return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
        }
      }
    };
    return {
      /** 搜索表单数据 */
      formData: {
        changeVersion: undefined,
        changePerson: undefined,
        changeType: undefined,
        changeTime: undefined
      },
      // 变更类型map
      changeMap: {
				'0': this.$t('base.info.change-record.all'),
				'1': this.$t('base.info.change-record.insert'),
				'2': this.$t('base.info.change-record.update'),
        '3': this.$t('base.info.change-record.delete')
			},
      /** 表头 */
      tableColumns: [
        // 序号
        {
          title: this.$t('base.info.serial-number'),
          width: 150,
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true
        },
        // 变更版本
        {
          title: this.$t('base.info.change-record.change-version'),
          dataIndex: 'changeVersion',
          align: 'center',
          width: 200,
          scopedSlots: {
            customRender: 'changeVersion'
          },
          ellipsis: true
        },
        // 变更类型
        {
          title: this.$t('base.info.change-record.change-type'),
          dataIndex: 'changeType',
          align: 'center',
          width: 200,
          scopedSlots: {
            customRender: 'changeType'
          },
          ellipsis: true
        },
        // 试验项目
        {
          title: this.$t('base.info.change-record.test-items'),
          dataIndex: 'verify',
          align: 'center',
          width: 260,
          ellipsis: true
        },
        // 变更内容
        {
          title: this.$t('base.info.change-record.change-content'),
          dataIndex: 'changeContent',
          width: 450,
          align: 'center',
          ellipsis: true
        },
        // 变更人
        {
          title: this.$t('base.info.change-record.change-person'),
          dataIndex: 'userName',
          align: 'center',
          width: 200,
          ellipsis: true
        },
        // 变更原因
        {
          title: this.$t('base.info.change-reason'),
          dataIndex: 'changeReason',
          align: 'center',
          width: 200,
          ellipsis: true
        },
        // 变更时间
        {
          title: this.$t('base.info.change-record.change-time'),
          dataIndex: 'updateTime',
          align: 'center',
          width: 200,
          ellipsis: true
        },
      ],
      /** 表格Loading */
      tableLoading: false,
      /** 表格数据 */
      tableData: [],
      /** 分页 */
      pagination: {
        size: 'small',
        current: 1,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total => this.$t('global-constant.table.show-total', {total: `${total}`}), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['15', '20', '50', '100', '200'], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        total: 0, //总条数
        showQuickJumper: true
      },
      /** 搜索-变更时间-开始时间 */
      changeTimeStart: undefined,
      /** 搜索-变更时间-结束时间 */
      changeTimeEnd: undefined,
      /** 表格高度 */
      tableHeight: window.innerHeight - 200 + 'px',
      tableHeightValue: window.innerHeight - 500,
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
      // 最大版本号
      maxVersion: 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
    }
  },
  computed: {
    // 使用计算属性生成 变更版本的选项数组
    options() {
      if (this.maxVersion !== undefined) {
        let maxVersion = this.maxVersion;
        let options = [];
        for (let i = 1; i <= maxVersion; i++) {
          options.push({ value: i, label: '0' + i.toString() });
        }
        return options;
      } else {
        return null;
      }
    },
  },
  mounted() {
    this.initData();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 200 + 'px';
      this.tableHeightValue = window.innerHeight - 500;
    };
    // 监听页面窗体大小变化
    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(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.tableWidth = this.$refs.tableRef.$el.offsetWidth;
    },
    // 计算表格各列宽度总和
    getColumnWidthTotal(){
      this.columnsWidth = this.tableColumns.reduce((sum, column) => sum + column.width, 0);
    },
    // 动态修改fixe的属性以便表格样式不出现空白列,并平和各列与表格的总宽度
    changeFixed(){
      if (this.columnsWidth <= this.tableWidth) {
        // 获取除最后一列以外其他列的宽度总和
        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;
      }
    },

    /**
     * 列表渲染
     */
    initData() {
      this.tableLoading = true;
      let data = {
        dvpId: this.$store.getters.dvpId,
        changeVersion: this.formData.changeVersion,
        changePerson: this.formData.changePerson,
        changeType: this.formData.changeType,
        changeTimeStart: this.changeTimeStart,
        changeTimeEnd: this.changeTimeEnd,
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize
      };
      this.$api.initChangeRecordByPart(data).then( res => {
        if (res.flag) {
          this.tableData = res.data.data || [];
          this.pagination.current = res.data.pageNo;
          this.pagination.pageSize = res.data.pageSize;
          this.pagination.total = res.data.total;
          if (res.data.data && res.data.data.length > 0 ) {
            this.maxVersion = this.tableData[0].maxVersion;
          }
        } else {
          this.$message.error(res.message);
        }
      }).finally(() => {
        this.tableLoading = false;
      });
    },

    /**
     * 查询
     */
    search(){
      this.initData();
    },

    /**
     * 重置
     */
    reset() {
      this.formData.changeVersion = undefined;
      this.formData.changePerson = undefined;
      this.formData.changeType = undefined;
      this.formData.changeTime = undefined;
      this.changeTimeStart = undefined;
      this.changeTimeEnd = undefined;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.search();
    },

    /**
     * 变更时间 搜索框选择事件
     * @param date
     * @param dateString
     */
    handleChangeTime(date, dateString) {
      if (!dateString) {
        this.formData.changeTime = "";
        return;
      }
      this.formData.changeTime = dateString;
      this.changeTimeStart = dateString[0];
      this.changeTimeEnd = dateString[1];
    },

    /**
     * 表格 - 点击分页中数字触发的方法
     * @param pagination
     */
    handlePageChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.pagination.pageNo = pagination.current;
      this.search();
    },
    /**
     * 下拉选模糊查询
     * @param input
     * @param option
     * @returns {boolean}
     */
    handleFilterDataList(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().includes(input.toLowerCase());
    },
  },
}
</script>

<style lang='less' scoped>
/deep/ .search-wrapper {
  .btn-wrap {
    margin-right: 12px;
  }
}

.colClass {
  padding: 12px 0px 0px 12px;
}

.mb12 {
  margin-bottom: 12px
}

.btnClass {
  margin: 0 6px !important;
}

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