<template>
  <div class="flex-container-1">
    <div class="flex-content-1 table-fix-head">
      <table
        class="fixed-table table-striped table-bordered"
        :width="tableWidth"
        height="40px"
      >
        <thead>
          <tr height="40px">
            <th width="50px" class="fixed-cell">
              <input
                autocomplete="off"
                :checked="allSelected"
                type="checkbox"
                @click="selectAll($event)"
              />
            </th>

            <th
              v-for="infoGridField in infoGridFields"
              v-show="infoGridField.isShow"
              :key="infoGridField.fieldName"
              :width="infoGridField.width + 'px'"
              @dragover="ondragover($event, infoGridField)"
              @click="onSort(infoGridField)"
            >
              <div
                :id="'infoGridFieldId_' + infoGridField.fieldName"
                class="rz-handle"
                draggable="true"
                @dragstart="ondragstart($event, infoGridField)"
                @drag="ondrag($event, infoGridField)"
                @dragend="ondragend($event, infoGridField)"
              />

              <div class="td-max">
                {{ infoGridField.name }}
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="rowData in dataList" :key="rowData.id" height="40px">
            <td class="fixed-cell">
              <input
                v-model="rowData.checked"
                autocomplete="off"
                type="checkbox"
                :value="rowData.id"
              />
            </td>
            <td
              v-for="infoGridField in infoGridFields"
              :key="infoGridField.fieldName + '_' + rowData.id"
            >
              <input
                v-if="infoGridField.simpleDisplayType == 'TextEditor'"
                autocomplete="off"
                type="text"
                class="form-control"
                :value="getDisplayValue(rowData, infoGridField)"
                @keyup="valueChange($event, rowData, infoGridField)"
              />
              <input
                v-if="infoGridField.simpleDisplayType == 'NumberEditor'"
                autocomplete="off"
                type="number"
                class="form-control"
                :value="getDisplayValue(rowData, infoGridField)"
                @keyup="valueChange($event, rowData, infoGridField)"
              />
              <span
                v-if="
                  infoGridField.simpleDisplayType == null ||
                    infoGridField.simpleDisplayType == '' ||
                    infoGridField.simpleDisplayType == 'NONE'
                "
              >
                {{
                  rowData.data[infoGridField.fieldName] == undefined
                    ? ""
                    : rowData.data[infoGridField.fieldName].displayValue[0]
                }}
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="flex-footer-1" style="margin-top: 10px">
      <div class="pull-left">
        <span>
          第
          {{ (pagination.current_page - 1) * pagination.per_page + 1 }}
          -
          {{ pagination.current_page * pagination.per_page }}
          条,共计
          {{ pagination.total }}
          条,每页
        </span>
        <PageSizeSelect @page-size-changed="gridSizeSelect" />

        <span>条</span>
      </div>
      <div class="pull-right">
        <Pagination :pagination="pagination" :callback="refreshSearch" />
      </div>
    </div>
  </div>
</template>

<script>
import Common from '../../common/Common.js';
import InfoUtil from './InfoUtil.js';
import Pagination from '../../vue-bootstrap-pagination/src/vue-bootstrap-pagination.vue';
import PageSizeSelect from '../../page-size-select/src/PageSizeSelect.vue';

export default {
  components: {
    Pagination,
    PageSizeSelect,
  },

  props: {
    // 查询窗口编号
    infoWindowNo: {
      type: String,
      default: null,
    },
    // 表格字段
    infoGridFields: {
      type: Array,
      default: null,
    },
    // 渲染的数据
    infoWindowData: {
      type: Object,
      default: null,
    },
    // 方法：根据id判断数据是否被选中
    isSelectedById: {
      type: Function,
      default: null,
    },
  },

  emits: ['selectChanged', 'refreshSearch'],

  data: function () {
    return {
      dataList: [],
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 10, // required
      },
      sortStyle: '',
      sortClause: '',
    };
  },

  computed: {
    /**
     * 自动计算表格的宽度
     * @author YangZhiJie 20210909
     */
    tableWidth: function () {
      var totalWidth = 50;
      if (this.infoGridFields !== undefined) {
        this.infoGridFields.forEach(function (infoGridField) {
          if (
            infoGridField.width !== undefined &&
            infoGridField.width !== null &&
            infoGridField.width !== ''
          ) {
            totalWidth += Number(infoGridField.width);
          }
        });
      }
      return totalWidth + 'px';
    },

    /**
     * 是否选择了全部的数据
     * @author YangZhiJie 20210909
     */
    allSelected: function () {
      var _self = this;
      if (
        this.dataList === undefined ||
        this.dataList === null ||
        this.dataList.length == 0
      ) {
        return false;
      }

      for (
        let index = 0, length = this.dataList.length;
        index < length;
        index++
      ) {
        if (this.dataList[index].checked === false) {
          return false;
        }
      }

      return true;
    },
  },

  watch: {
    infoWindowData: function (newValue, oldValue) {
      this.setDataList(newValue);
    },

    dataList: {
      handler: function (newValue, oldValue) {
        // 清除延迟执行
        if (
          this.selectChangedTimeout !== undefined &&
          this.selectChangedTimeout !== null
        ) {
          window.clearTimeout(this.selectChangedTimeout);
        }

        // 设置延迟执行
        this.selectChangedTimeout = setTimeout(() => {
          this.$emit('selectChanged', this.dataList);
        }, 500);
      },
      deep: true,
    },
  },

  methods: {
    /**
     * 重新设置分页
     * 供外部组件调用
     * @author YangZhiJie 20210909
     */
    resetPagination: function () {
      this.pagination.current_page = 1;
      this.pagination.last_page = 10;
      this.pagination.total = 0;
    },

    /**
     * 设置分页
     * @author YangZhiJie 20210909
     */
    setPagination: function (total, lastPage) {
      this.pagination.last_page = lastPage;
      this.pagination.total = total;
    },

    /**
     * 获取查询参数
     * 供外部组件调用
     * @author YangZhiJie 20210909
     */
    getQueryParam: function () {
      return {
        infoWindowNo: this.infoWindowNo,
        start: (this.pagination.current_page - 1) * this.pagination.per_page,
        length: this.pagination.per_page,
        sortClause: this.sortClause,
      };
    },

    /**
     * 页码数量改变
     * @author YangZhiJie 20210909
     */
    gridSizeSelect: function (newPageSize) {
      this.pagination.per_page = newPageSize;
      this.pagination.current_page = 1;
    },

    /**
     * 列开始拖动
     * @author YangZhiJie 20210909
     */
    ondragstart: function (event, gridFieldItem) {
      var _self = this;
      _self.startX = event.pageX;
      _self.startWidth = Number(gridFieldItem.width);
      event.dataTransfer.setDragImage(event.target, 0, 20);
      event.dataTransfer.effectAllowed = 'move';
    },

    /**
     * 列拖动
     * @author YangZhiJie 20210909
     */
    ondrag: function (event, gridFieldItem) {
      var _self = this;
      gridFieldItem.width = _self.startWidth + (event.pageX - _self.startX);
    },

    /**
     * 列结束拖动
     * @author YangZhiJie 20210909
     */
    ondragend: function (event, gridFieldItem, index) {
      var _self = this;

      let newWidth = _self.startWidth + (event.pageX - _self.startX);
      if (newWidth < 50) {
        newWidth = 50;
      }
      gridFieldItem.width = newWidth;

      //gridFieldItem.width = gridFieldItemClone.width;
      InfoUtil.saveInfoGridFields(_self.infoWindowDto.no, _self.infoGridFields);
    },

    ondragover: function (event, gridFieldItem) {
      event.preventDefault();
      event.dataTransfer.dropEffect = 'move';
    },

    /**
     * 排序
     * @author YangZhiJie 20210909
     */
    onSort: function (infoGridField) {
      var _self = this;
      var fieldName = null;
      if (
        infoGridField.sortFieldName != undefined &&
        infoGridField.sortFieldName != ''
      ) {
        fieldName = infoGridField.sortFieldName;
      } else {
        fieldName = infoGridField.fieldName;
      }
      _self.sortClause = fieldName + _self.sortStyle;

      this.$emit('refreshSearch');

      _self.sortStyle = _self.sortStyle === ' ASC' ? ' DESC' : ' ASC';
    },

    /**
     * 发送查询请求
     * @author YangZhiJie 20210909
     */
    refreshSearch: function () {
      this.$emit('refreshSearch');
    },

    /**
     * 冻结表头
     * @author YangZhiJie 20210909
     */
    fixedTableHeader: function () {
      let _self = this;
      _self.$nextTick(function () {
        var $th = $('.table-fix-head').find('thead');
        var $fixedCell = $('.table-fix-head').find('.fixed-cell');
        $('.table-fix-head').on('scroll', function () {
          $th.css('transform', 'translateY(' + this.scrollTop + 'px)');
          $fixedCell.css('transform', 'translateX(' + this.scrollLeft + 'px)');
        });
      });
    },

    /**
     * 表格中填写的值发生了改变
     * @author YangZhiJie 20210909
     */
    valueChange: function (event, rowData, infoGridField) {
      var _self = this;
      var value = event.target.value;
      const fieldName = infoGridField.fieldName;
      if (rowData.data[fieldName] == undefined) {
        var tempFieldValue = {
          displayValue: [value],
        };
        rowData.data[fieldName] = tempFieldValue;
      } else {
        rowData.data[fieldName].displayValue[0] = value;
      }
      rowData.checked = true;
    },

    /**
     * 获取显示的值
     * @author YangZhiJie 20210909
     */
    getDisplayValue(rowData, infoGridField) {
      let fieldValue = rowData.data[infoGridField.fieldName];
      if (fieldValue === undefined || fieldValue === null) {
        return '';
      } else {
        return fieldValue.displayValue[0];
      }
    },

    /**
     * 选择所有/取消选择的数据
     * @author YangZhiJie 20210909
     */
    selectAll: function (event) {
      var isChecked = event.currentTarget.checked;

      if (
        this.dataList === undefined ||
        this.dataList === null ||
        this.dataList.length == 0
      ) {
        return;
      }

      for (
        let index = 0, length = this.dataList.length;
        index < length;
        index++
      ) {
        this.dataList[index].checked = isChecked;
      }
    },

    /**
     * 设置dataList数据
     * @author YangZhiJie 20210908
     */
    setDataList: function (dataList) {
      let _self = this;
      if (dataList === null || dataList === undefined) {
        this.dataList.splice(0, this.dataList.length);
        return;
      }
      if (!Array.isArray(dataList)) {
        console.error('参数异常，参数不是数组类型。');
        console.error(dataList);
        return;
      }

      const tempDataList = JSON.parse(JSON.stringify(dataList));
      for (
        let index = 0, length = tempDataList.length;
        index < length;
        index++
      ) {
        if (this.isSelectedById != null) {
          tempDataList[index].checked = this.isSelectedById(
            tempDataList[index].id,
          );
        } else {
          tempDataList[index].checked = false;
        }
      }

      this.dataList = tempDataList;

      this.$nextTick(function () {
        _self.fixedTableHeader();
      });
    },
  },
};
</script>

<style scoped>
.flex-container-1 {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100% - 10px);
}

.flex-content-1 {
  flex: 1;
  overflow: auto;
  width: 100%;
  margin-top: 5px;
}

.flex-footer-1 {
  height: 35px;
  /*放大缩小比例为0 */
  flex: 0 0 35px;
}
</style>


<style scoped>
.fixed-table {
  table-layout: fixed;
}

table.fixed-table th {
  position: relative;
  min-width: 10px;
}

table.fixed-table tr td:first-child,
table.fixed-table tr th:first-child {
  text-align: center;
}

table.fixed-table th,
table.fixed-table td {
  text-align: left;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0.1em;
  border-right: 1px solid rgba(0, 0, 0, 0.05);
  background-color: white;
}

table.fixed-table th .rz-handle {
  width: 10px;
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  background: repeating-linear-gradient(
    45deg,
    transparent,
    transparent 2px,
    rgba(0, 0, 0, 0.05) 2px,
    rgba(0, 0, 0, 0.05) 4px
  );
  cursor: ew-resize !important;
}

table.fixed-table th .rz-handle.rz-handle-active {
  border-right: 2px solid #000;
  transform: scaleX(100);
  background: rgba(0, 0, 0, 0.05) 2px;
}

.rz-handle:hover {
  background: rgba(0, 0, 0, 0.2) 4px;
}
</style>
