<template>
  <div :id="tableOutDivId" class="flex-main table-fix-head">
    <table class="fixed-table table-striped table-bordered" :width="tableWidth" height="40px">
      <thead>
        <tr height="40px">
          <th width="50px">{{ $t("lang.QueryPage.serialNumber") }}</th>
          <th
            width="30px" class="text-center" :class="{ 'mulitiple-select': multipleSelect }"
            @click.self="changeSelectMode"
          >
            <input v-model="isSelectAll" autocomplete="off" type="checkbox" />
          </th>
          <template v-for="infoGridField in infoGridFieldsInstance.infoGridFields">
            <th
              v-if="infoGridField.simpleDisplayType != 'OperateButton'" 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
                v-tooltip.right="Language.getHelpTrl($i18n.locale, infoGridField)
                " class="td-max"
              >
                {{ Language.getNameTrl($i18n.locale, infoGridField) }}
              </div>
            </th>
          </template>
          <th v-if="operateButtons != null && operateButtons.length > 0" style="width: 160px;">
            操作
          </th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="(item1, index) in infoWindowDataInstance.dataList" :key="'tr' + item1.id" height="40px"
          :class="{ warning: item1.select }" @dblclick="selectNode(item1)"
        >
          <td style="text-align: center">
            {{
              index +
                1 +
                (pagination.current_page - 1) * pagination.per_page
            }}
          </td>

          <td class="text-center">
            <input
              autocomplete="off" type="checkbox" :checked="item1.select"
              @click.self="selectNodeForSearch(item1)"
            />
          </td>
          <template v-for="item2 in infoGridFieldsInstance.infoGridFields">
            <td
              v-show="item2.isShow" v-if="item2.simpleDisplayType != 'OperateButton'" id="item.id"
              :key="'td-' + item2.id"
            >
              <span v-if="item2.simpleDisplayType == 'Image'">
                <QueryPageImage
                  v-if="item1.data[item2.fieldName] != undefined"
                  :class-name="item2.selectClause"
                  :image-names="item1.data[item2.fieldName].displayValue[0]"
                />
              </span>
              <span v-else>
                {{
                  item1.data[item2.fieldName] != undefined
                    ? item1.data[item2.fieldName].displayValue[0]
                    : ""
                }}
              </span>
            </td>
          </template>
          <td v-if="operateButtons != null && operateButtons.length > 0">
            <template v-for="item in operateButtons" :key="item">
              <a-button @click="executeCallout(item1, item)">{{ item.name }}</a-button>
            </template>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>


<script>

import Context from './Context.js';
import JsUtil from '../../common/JsUtil.js';
import Language from '../../common/Language.js';
import QueryPageImage from './QueryPageImage.vue';

import Uuid from '../../common/Uuid.js';
import Notify from '../../common/Notify.js';



export default {
  name: 'QueryPageTable',

  components: {
    QueryPageImage,
  },

  props: {
    callOutJsUrl:{
      type: String,
      default() {
        return null;
      },
    },
    infoWindowDataInstance: {
      type: Object,
      default() {
        return {};
      },
    },
    pagination: {
      type: Object,
      default() {
        return {};
      },
    },
    infoGridFieldsInstance: {
      type: Object,
      default() {
        return {};
      },
    },
    /**
         * 是否多选
         */
    multiple: {
      type: Boolean,
      default: false,
    },
    // 是否勾选了全选
    isSelectAllInput: {
      type: Boolean,
      default : false,
    },
    /**
         * 排序对象实例
         */
    sortInstance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  
  emits: ['dataSelected', 'deleteSelected','infoSelected'],
  data: function () {
    this.Language = Language;
    return {
      isSelectAll: false,
      multipleSelect: false,
      // 表格外面的DIV的id
      tableOutDivId: Uuid.createUUID(),
      modelDatas:[],
    };
  },
  
  computed: {
    tableWidth: function () {
      var totalWidth = 50;
      if (this.infoGridFieldsInstance != undefined
                && this.infoGridFieldsInstance.infoGridFields != undefined) {
        this.infoGridFieldsInstance.infoGridFields.forEach(function (item) {
          if (item.isShow) {
            totalWidth += Number(item.width);
          }
        });
      }
      return totalWidth + 'px';
    },
    operateButtons: function () {
      let buttons = [];
      this.infoGridFieldsInstance.infoGridFields.forEach(item => {
        if (item.simpleDisplayType == 'OperateButton') {
          buttons.push(item);
        }
      });
      return buttons;
    },
  },


  watch: {    
    isSelectAllInput: function (val) {
      var _self = this;
      _self.isSelectAll = val;
    },
    /**
         * 是否选择了全部的数据
         */
    isSelectAll: function (val) {
      var _self = this;
      if (_self.multipleSelect) {
        if (_self.isSelectAll) {
          if (val) {                        
            _self.infoWindowDataInstance.setAllSelect();                       
            _self.$emit('infoSelected',val);
          }
        } else {
          _self.infoWindowDataInstance.setAllUnSelect();
          _self.$emit('infoSelected',val);
        }
      } else {
        _self.isSelectAll = false;
        _self.$emit('infoSelected',val);

      }
    },
    multiple: {
      handler: function (newValue, oldValue) {
        this.multipleSelect = newValue;
      },
      immediate: true,
    },
    'infoWindowDataInstance.timestamp': function (newValue, oldValue) {
      this.fixedTableHeader();
    },
  },

  methods: {

    getContext: Context,

    executeCallout: function (rowData, filedItem) {
      let _self = this;

      const methodName = filedItem.callOutJsMethod;

      const callOutJsUrl = this.infoWindowDto.callOutJsUrl;

      let functionName = methodName.replace('.', '_') + '_calloutjs';

      let executeFunction = function () {

        let context = new _self.getContext(rowData, {});
        try {
          _self[functionName](context);
        } catch (e) {
          console.error(e);
          Notify.error('数据字典定义异常', ` 【 ${methodName} 】前端列显示逻辑定义异常,请联系管理员检查数据字典的定义。`, false);
        }
      };

      if (_self[functionName] == null) {
        // 执行服务端的脚本
        const jsUrl = callOutJsUrl;
        if (jsUrl == null || jsUrl == undefined) {
          Notify.error('数据字典定义异常', `【 ${methodName} 】Callout前端逻辑的JS文件不存在,请联系管理员检查数据字典是否JS文件。`, false);
          return;
        }
        let promise = JsUtil.dynamicLoadJsFunction(jsUrl, methodName);
        promise.then(targetFunction => {
          if (targetFunction == null) {
            Notify.error('数据字典定义异常', `【 ${methodName} 】Callout前端逻辑定义异常,请联系管理员检查数据字典的定义。`, false);
            return;
          }

          _self[functionName] = targetFunction;
          executeFunction();

        }, errorData => {
          console.error(errorData);
        });
      } else {
        executeFunction();
      }
    },


    /**
         * 切换全选/单选
         */
    changeSelectMode: function () {
      this.multipleSelect = !this.multipleSelect;
    },


    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';
    },

    ondrag: function (event, gridFieldItem) {
      var _self = this;
      gridFieldItem.width = _self.startWidth + (event.pageX - _self.startX);
    },

    ondragend: function (event, gridFieldItem, index) {
      var _self = this;
      let newWidth = _self.startWidth + (event.pageX - _self.startX);
      if (newWidth < 50) {
        newWidth = 50;
      }
      _self.infoGridFieldsInstance.changeGridFieldWidth(gridFieldItem, newWidth);
    },

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


    /**
         * 选择/取消选择表格行中的复选框事件
         */
    selectNodeForSearch: function (modelData) {
      var _self = this;

      var currentStatus = modelData.select;
      if (!_self.multipleSelect) {
        _self.infoWindowDataInstance.setAllUnSelect();
      }

      _self.infoWindowDataInstance.selectSelectState(modelData, !currentStatus);

      if (modelData.select === true) {
        _self.$emit('dataSelected', modelData);
        _self.$emit('infoSelected');
      } else {
        _self.$emit('deleteSelected', modelData);
        _self.$emit('infoSelected');
      }
    },


    /**
         * 双击表格行事件
         */
    selectNode: function (modelData) {
      this.$emit('dataSelected', modelData);
    },


    /**
         * 冻结表头
         */
    fixedTableHeader: function () {
      let _self = this;
      _self.$nextTick(function () {
        var $th = $('#' + _self.tableOutDivId).find('thead');
        $('#' + _self.tableOutDivId).on('scroll', function () {
          $th.css('transform', 'translateY(' + this.scrollTop + 'px)');
        });
      });
    },


    /**
         * 排序
         */
    onSort: function (infoGridField) {
      var _self = this;
      var fieldName = null;
      if (
        infoGridField.sortFieldName != undefined &&
                infoGridField.sortFieldName != ''
      ) {
        fieldName = infoGridField.sortFieldName;
      } else {
        fieldName = infoGridField.fieldName;
      }
      _self.sortInstance.changeFieldName(fieldName);
    },
  },
};
</script>

<style scoped>
.flex-main {
    overflow: scroll;
    flex: 1;
    margin-bottom: 0px;
}


.fixed-table {
    table-layout: fixed;
}

table.fixed-table tr th {
    text-align: center;
}

table.fixed-table td {
    text-align: center;
    word-wrap: break-word;
    word-break: normal;
}



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

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

table.fixed-table th {
    min-width: 10px;
    background-color: #f8f8f8;
}

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>