<template>
  <tr class="sticky-row">
    <th
      v-if="$i18n.locale === 'zh-CN'"
      class="text-center sticky-col"
      width="50px"
    >
      <div>{{ $t('lang.gridHeader.serialNumber') }}</div>
    </th>
    <th
      v-else
      class="text-center sticky-col"
      width="100px"
    >
      <div>{{ $t('lang.gridHeader.serialNumber') }}</div>
    </th>
    <th
      class="text-center sticky-col"
      width="30px"
      :class="{'mulitiple-select': multipleSelect}"
      style="left:50px" @click.self="changeSelectMode"
    >
      <input
        v-model="isSelectAll"
        autocomplete="off"
        type="checkbox"
        class="select-checkbox"
      />
    </th>
    <th
      v-if="isShowEdit == undefined || isShowEdit"
      class="text-center sticky-col"
      width="95px"
      style="left:80px"
    >
      <div>
        {{ $t('lang.gridHeader.operate') }}
      </div>
    </th>
    <template v-if="tabGridFields != null && tabGridFields.length > 0">
      <th
        v-for="tabGridField in tabGridFields"
        v-show="tabGridField.visible"
        :id="tabGridField.fieldId" :key="'th_' + getTabGridFieldId(tabGridField)"
        v-tooltip="tabGridField.help"
        class="text-center"
        :width="tabGridField.width + 'px'"
        style="position: relative;"
        @dragover="ondragover($event, tabGridField)"
        @click="onSort(tabGridField)"
      >
        <div
          :id="getTabGridFieldId(tabGridField)"
          class="rz-handle"
          draggable="true"
          @dragstart="ondragstart($event, tabGridField)"
          @drag="ondrag($event, tabGridField)"
          @dragend="ondragend($event, tabGridField)"
        />

        <div class="td-max">
          <span
            v-if="tabGridField.mandatory"
            class="require-mark"
          >*</span>
          <span size="2">{{ Language.getDisplayNameTrl($i18n.locale, tabGridField) }}</span><br />
          <span v-if="isChineseEnglish && $i18n.locale == 'zh-CN'" size="0.5">{{ tabGridField.displayNameEng }}</span>
        </div>
      </th>
    </template>
  </tr>
</template>
<script>
import WindowClientUtil from '../../resource/dictionary/WindowClientUtil.js';
import GridColumnDef from './GridColumnDef.js';
import Language from '../../common/Language.js';

import Context from '../common/Context.js';
import JsUtil from '../../common/JsUtil.js';
import { Notify, Uuid } from 'pc-component-v3';
export default {

  
  props: {
   
    windowNo: {
      type: String,
      default: null,
    },
    tabIndex: {
      type: Number,
      default: null,
    },
    tabGridFields: {
      type: Array,
      default : function(){
        return null;
      },
    },
    parentModelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
    isShowEdit: {
      type: Boolean,
      default : false,
    },
    isChineseEnglish: {
      type: Boolean,
      default: null,
    },
  },
  emits: ['onSort', 'multipleSelect'],



  data: function () {
    this.Language = Language;
    return {
      startX: '',
      startWidth: '',
      isSelectAll: false,
      multipleSelect: true,
    };
  },
  watch: {
    'isSelectAll': function (val) {
      var _self = this;
      if (_self.multipleSelect) {
        _self.$emit('selectAll', _self.isSelectAll);
      } else {
        _self.isSelectAll = false;
      }
    },

    'parentModelData.data': {
      deep: true,
      handler(curVal, oldVal) {
        var _self = this;
        for(let index = 0; index < _self.tabGridFields.length; index ++){
          const tabGridField = _self.tabGridFields[index];
          const columnShowLogical = tabGridField.columnShowLogical;
          if(columnShowLogical != null && columnShowLogical.length > 0){                    
            let functionName = tabGridField.fieldName.replace('.', '_') + '_showLogical';

            
            let executeFunction = function(){
              let parentCtx = new _self.getContext(_self.parentModelData);
              try{
                tabGridField.visible = _self[functionName](null, parentCtx.modelData);
              }catch(e){
                console.error('js代码 %s 执行异常 %o', columnShowLogical, e);
                tabGridField.visible = true;
              }
            };


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

                _self[functionName] = targetFunction;

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

  methods: {
    /**
         * 获取Context
         */
    getContext : Context,

    /**
		 * 获取表格列的Id
		 */
    getTabGridFieldId: function (tabGridField) {
      var tabGridFieldId = 'GridHeader' + this.windowNo + '_' + this.tabIndex + '_' + tabGridField.fieldName + '_' + tabGridField.entityFieldIndex;
      return tabGridFieldId;
    },

    ondragstart: function (event, tabGridField) {
      var _self = this;
      _self.startX = event.pageX;
      _self.startWidth = tabGridField.width;

      var tabGridFieldId = this.getTabGridFieldId(tabGridField);
      var element1 = document.getElementById(tabGridFieldId);
      $(element1).addClass('rz-handle-active');

      // event.dataTransfer.setDragImage(element1, 0, 30);
      event.dataTransfer.setDragImage(event.target, 0, 20);

      event.dataTransfer.effectAllowed = 'move';
      // event.dataTransfer.dropEffect = 'move';
    },

    ondrag: function (event, tabGridField) {
      var _self = this;
      if ((_self.startWidth + (event.pageX - _self.startX)) > 20) {
        tabGridField.width = _self.startWidth + (event.pageX - _self.startX);
      } else {
        tabGridField.width = 20;
      }
    },

    ondragend: function (event, tabGridField) {
      var _self = this;

      if ((_self.startWidth + (event.pageX - _self.startX)) > 20) {
        tabGridField.width = _self.startWidth + (event.pageX - _self.startX);
      } else {
        tabGridField.width = 20;
      }

      GridColumnDef.saveGridFieldDef(_self.windowNo, _self.tabIndex, _self.tabGridFields).then(successData => {
        _self.$emit('propertyChanged', _self.tabGridFields);

        var tabGridFieldId = _self.getTabGridFieldId(tabGridField);
        var element1 = document.getElementById(tabGridFieldId);
        $(element1).removeClass('rz-handle-active');
      }, errorData => {
        console.log(errorData);
      });
    },

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

    onSort: function (tabGridField) {
      this.$emit('onSort', tabGridField);
    },

    changeSelectMode: function () {
      this.multipleSelect = !this.multipleSelect;
      this.$emit('multipleSelect', this.multipleSelect);
    },
  },

};

</script>
<style scoped>
.require-mark {
    color: red;
}
.mulitiple-select {
    background-color: #6699cc;
}
.text-center {
    text-align: center;
}
th {
    background-color: #f7f7f7;
}
.td-max {
    max-width: 250px;
}
</style>


<style scoped>
table.curd-table th {
    /* position: relative; */
    min-width: 25px;
}

table th,
table td {
    text-align: left;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    /* padding: 0.75em; */
    border-right: 1px solid rgba(0, 0, 0, 0.05);
}

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

.rz-handle {
    width: 10px;
    height: 100%;
    position: absolute;
    top: 0;
    right: 0;
    cursor: ew-resize !important;
    z-index: 3;
}

.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;
}


/* 固定列 */
.sticky-col {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  left: 0;
  background: #fafafa;
  z-index: 1; /* 确保固定列在其他内容之上 */
}

/* 固定行 */
.sticky-row {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
  background: #fafafa;
  z-index: 2; /* 确保固定列在其他内容之上 */
}
</style>