<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-content')">
                <a-input v-model='formData.changeContent' :placeholder="$t('base.info.please-enter-change-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.change-reason')">
                <a-input v-model='formData.changeReason' :placeholder="$t('base.info.please-enter-change-reason')" 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.version')">
                <a-select
                  v-model='formData.versionNo'
                  :filter-option="handleFilterDataList"
                  :options="versionNoList"
                  :placeholder="$t('base.info.please-select-version')"
                  allowClear>
                </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-person')">
                <a-input v-model='formData.changePerson' :placeholder="$t('base.info.please-enter-change-person')" allowClear/>
              </a-form-item>
            </a-col>
            <span v-show="advanceExpand">
                <!-- 变更时间 -->
					        <a-col :lg='12' :md='24' :sm='24' :xl='advanceExpand ? 6 : 18' :xs='24'>
						        <a-form-item :label="$t('base.info.change-time')">
							        <a-range-picker v-model="formData.changeTime" allowClear style="width: 100%" @change="handleChangeTime"/>
						        </a-form-item>
					        </a-col>
                </span>
            <a-col :lg='8' :md='24' :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 @click="toggleAdvance">
                        {{ advanceExpand ? $t('plan.dvp.collapse') : $t('plan.dvp.expand') }}
                        <a-icon :type="advanceExpand ? 'up' : 'down'"/>
                      </a>
                      <!-- 重置 -->
                      <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"
          :columns='tableColumns'
          :dataSource='tableData'
          :loading='tableLoading'
          :pagination='pagination'
          :rowKey='(record, index) => { return index; }'
          :scroll='{ x: tableWidth, y: tableHeightValue - 200 }'
          size="small"
          :components='components'
          bordered
          @change='handlePageChange'>
          <template slot='action' slot-scope='row'>
            <!-- 编辑 -->
            <a v-if="row.isFinish === 1" class="operation-btn btnClass" @click="editChangeManagement(row)">
              <a-tooltip :title="$t('global-btn.edit')">
                <i class="iconfont iconbianji"></i>
              </a-tooltip>
            </a>
            <!-- 查看 -->
            <a v-if="row.isFinish === 0" class="operation-btn btnClass" @click="viewChangeManagement(row)">
              <a-tooltip :title="$t('global-btn.look')">
                <i class="iconfont iconchakan"></i>
              </a-tooltip>
            </a>
          </template>
          <!-- 变更来源 -->
          <template slot="changeResource" slot-scope="text, record">
            <span :title="text"> {{ changeSourceMap[record.changeResource] || '-' }} </span>
          </template>
          <!-- 序号列 -->
          <template slot='index' slot-scope='text, record, index'>
            <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
          </template>
        </a-table>
      </div>
    </a-col>
    <!-- 变更内容查看和编辑弹框 -->
    <change-content-modal ref="changeContentModal" @initData="initData"/>
  </div>
</template>

<script>

import ChangeContentModal from "./changeContentModal";

export default {
  name: "changeManagement",
  components: {
    ChangeContentModal
  },
  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: {
        changeContent: undefined,
        changeReason: undefined,
        changePerson: undefined,
        versionNo: undefined,
        changeTime: undefined
      },
      /** 展开/折叠 */
      advanceExpand: false,
      /** 表头 */
      tableColumns: [
        // 序号
        {
          title: this.$t('base.info.serial-number'),
          width: 100,
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true
        },
        // 变更内容
        {
          title: this.$t('base.info.description-of-change-content'),
          dataIndex: 'description',
          align: 'center',
          width: 150,
          ellipsis: true
        },
        // 变更原因
        {
          title: this.$t('base.info.change-reason'),
          dataIndex: 'reason',
          align: 'center',
          width: 150,
          ellipsis: true
        },
        // 变更来源
        {
          title: this.$t('base.info.change-source'),
          dataIndex: 'changeResource',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: "changeResource"
          }
        },
        // 产品类型
        {
          title: this.$t('base.info.product.type'),
          dataIndex: 'projectType',
          width: 120,
          align: 'center',
          ellipsis: true
        },
        // 系列号
        {
          title: this.$t('base.management.serial-number'),
          dataIndex: 'serialNumber',
          align: 'center',
          width: 120,
          ellipsis: true
        },
        // 车型代号
        {
          title: this.$t('base.info.vehicle-model-code'),
          dataIndex: 'vehicleModel',
          align: 'center',
          width: 150,
          ellipsis: true
        },
        // 项目编号
        {
          title: this.$t('base.info.project.number'),
          dataIndex: 'projectName',
          align: 'center',
          width: 150,
          ellipsis: true
        },
        // 版本
        {
          title: this.$t('base.info.version'),
          dataIndex: 'version',
          align: 'center',
          width: 100,
          ellipsis: true
        },
        // 变更人
        {
          title: this.$t('base.info.change-person'),
          dataIndex: 'userName',
          align: 'center',
          width: 150,
          ellipsis: true
        },
        // 变更时间
        {
          title: this.$t('base.info.change-time'),
          dataIndex: 'updateTime',
          align: 'center',
          width: 100,
          ellipsis: true
        },
        // 操作
        {
          title: this.$t('global-constant.operation'),
          key: 'operation',
          fixed: 'right',
          align: 'center',
          width: 100,
          scopedSlots: {
            customRender: 'action'
          },
          ellipsis: true
        }
      ],
      /** 表格Loading */
      tableLoading: false,
      /** 表格数据 */
      tableData: [],
      /** 分页 */
      pagination: {
        size: 'small',
        current: 1,
        pageNo: 1,
        pageSize: 15, // 默认每页显示数量
        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
      },
      /** 版本下拉选数据 */
      versionNoList: [
        {
          label: 1,
          value: 1
        },
        {
          label: 2,
          value: 2
        },
        {
          label: 3,
          value: 3
        },
        {
          label: 4,
          value: 4
        },
        {
          label: 5,
          value: 5
        },
        {
          label: 6,
          value: 6
        },
        {
          label: 7,
          value: 7
        }
      ],
      /** 搜索-变更时间-开始时间 */
      changeTimeStart: undefined,
      /** 搜索-变更时间-结束时间 */
      changeTimeEnd: undefined,
      /** 表格高度 */
      tableHeight: window.innerHeight - 200 + 'px',
      tableHeightValue: window.innerHeight - 352,
      changeSourceMap: {
        '2': this.$t("base.info.ecr-design-change")
      },
      // 表格总宽度
      tableWidth: 0,
      //表格各列宽度总和
      columnsWidth: 0,
    };
  },

  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() {
    this.initData();
    this.initSelectData();
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 200 + 'px';
      this.tableHeightValue = window.innerHeight - 352;
    };
    // 监听页面窗体大小变化
    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) {
        // 遍历 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].fixed='right';
        // 恢复最后一列原始宽度
        this.tableColumns[this.tableColumns.length - 1].width = 100;
      }
    },

    /**
     * 列表渲染
     */
    initData() {
      this.tableLoading = true;
      let data = {
        dvpId: this.$store.getters.dvpId,
        dvpType: this.$store.getters.dvpType,
        description: this.formData.changeContent,
        reason: this.formData.changeReason,
        version: this.formData.versionNo,
        userName: this.formData.changePerson,
        changeTimeStart: this.changeTimeStart,
        changeTimeEnd: this.changeTimeEnd,
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize
      };
      this.$api.getChangePageList(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;
        } else {
          this.$message.error(res.message);
        }
      }).finally(() => {
        this.tableLoading = false;
      });
    },

    /**
     * 版本下拉列表
     */
    initSelectData() {

    },

    /**
     * 编辑变更内容
     * @param row
     */
    editChangeManagement(row) {
      this.$refs.changeContentModal.initFormData(row);
      this.$refs.changeContentModal.isDisabled = false;
      this.$refs.changeContentModal.isShowChangeContentModal = true;
    },

    /**
     * 查看变更内容
     * @param row
     */
    viewChangeManagement(row) {
      console.log(row);
      this.$refs.changeContentModal.initFormData(row);
      this.$refs.changeContentModal.isDisabled = true;
      this.$refs.changeContentModal.isShowChangeContentModal = true;
    },

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

    /**
     * 重置
     */
    reset() {
      this.formData.changeContent = undefined;
      this.formData.changeReason = undefined;
      this.formData.changePerson = undefined;
      this.formData.versionNo = 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();
    },

    /**
     * 展开/收起点击事件
     */
    toggleAdvance() {
      this.advanceExpand = !this.advanceExpand;
    },

    /**
     * 下拉选模糊查询
     * @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;
}
</style>
