//重写源码分页组件

// function createDragLine() {
//   return {
//     data() {
//       return { x: 0, y: 0, show: false, rowEdge: false };
//     },
//     render() {
//       return this._c('div', {
//         class: ['t-table-drag-line', this.rowEdge && 'row-edge'],
//         directives: [{ name: 'show', value: this.show }],
//         style: {
//           transform: `translate(${this.x}px,${this.y}px)`,
//         },
//       });
//     }
//   }
// }

const INTERNAL_COL_DEFINE = 'RC_TABLE_INTERNAL_COL_DEFINE';
import difference from 'lodash/difference';
import isEqual from 'lodash/isEqual';
export default function () {
  let _Table = require('ant-design-vue/es/table/Table.js').default;
  const SelectionBox = require('ant-design-vue/es/table/SelectionBox.js').default;
  SelectionBox.props.indeterminate = {
    type:null
  }
  _Table.data = (function (fn) {
    return function () {
      if (this.tableType == 't-table') {
        this.befKey = null
        this._cached = {}
        this.sk={}
        this._beforeChecks=this.selectedRowKeys

      if (this.selectedRowKeys) {
          this.$watch('selectedRowKeys', (arrKey) => {
           let selectionBoxValues=this.selectionBoxValues
            if (this._beforeChecks.length > 0) {
              let removekeyArr = difference(this._beforeChecks, arrKey);
              if (removekeyArr.length > 0) {
                for (let i = 0; i < removekeyArr.length; i++){
                  let key = removekeyArr[i]
                  let o= selectionBoxValues[key]
                  if (o&&o.value) {
                    o.value = false
                    delete this.sk[key];
                  }
                }
              }
            }
            if (arrKey.length > 0) {
              for (let i = 0; i < arrKey.length; i++){
                let key = arrKey[i]
                let o= selectionBoxValues[key]
                if (o&&!o.value) {
                  o.value = true
                  this.sk[key] = o
                }
              }
            }
            this.reslutSelectionAll(this.sk)
            this._beforeChecks = arrKey
          });
      }
        this.$watch('dataSource', (value, old) => {
          // console.log(isEqual(value,old))
          if (!isEqual(value, old)) {
            this.sk = {};
            this.selectionBoxValues = {};
            let data = this.getFlatCurrentPageData();
            this.currentPageDataCount = data.length;
            this.reslutSelectionAll(this.sk);

           }

      });
        return {
          ...fn.apply(this, arguments),
          currentPageDataCount: this?.dataSource?.length,
          checkboxAllIndeterminate: false,
          checkboxAllValue: false,
          selectionBoxValues: {}

        };
      } else {
        return fn.apply(this, arguments);
      }
    };
  })(_Table.data);


  _Table.methods.reslutSelectionAll = function (sk) {
    let keys = Object.keys(sk);
    if (!sk || !keys.length) {
      this.checkboxAllValue=false
      this.checkboxAllIndeterminate=false
    } else {

      this.checkboxAllValue = this.currentPageDataCount == keys.length;
      this.checkboxAllIndeterminate = keys.length > 0 && !this.checkboxAllValue;
    }
    this.$listeners.hcheckboxAllIndeterminateasSelected&&this.$emit('hasSelected', keys.length > 0)
  };

  _Table.inject.tableType = {
    default: 'tableType'
  };
  _Table.props.tPagination = {
    type: null
  };
  _Table.props.selectedRowKeys = {
    type: Array
  };
  _Table.props.customCell = {
    type: Function
  };
  _Table.props.getCheckboxProps = {
    type: Function
  };
  _Table.props.hasRowSelectCheck = {
    type: Boolean
  };
  _Table.props.attachFooter = {
    type: null
  };
  _Table.props.defaultCountKey = {
    type: null
  };
  _Table.props.hideDefaultSelections = {
    type: null
  };


  _Table.props.rowSelectType = {
  };
  _Table.props.vScrollX = {
    type: Object
  };
  _Table.props.vScrollY = {
    type: Object
  };

  _Table.methods.getSelectionData = function () {
    return Object.values(this.sk);
  };

  _Table.methods.renderSelectionBox = (function (fn) {
    return function (type) {
      if (this.tableType == 't-table') {
        this.renderSelectionBox = function () {

          this.valueKey = {};
          let { onChange, onSelect, onSelectInvert, onSelectAll } = this.rowSelection;
          const { selectedRowKeys,_cached,$createElement,getCheckboxProps, rowSelectType, getRecordKey } = this;
          if(!rowSelectType) return null
          let updateSelectedRowKeys = null;
          if ('update:selectedRowKeys' in this.$listeners) {
            updateSelectedRowKeys = this.$listeners['update:selectedRowKeys'];
          }


          return (_, record, index) => {
            var h =$createElement;
            const rowKey = getRecordKey(record, index); // 从 1 开始

            let props = {
              value: this.checkboxAllValue,
              index,
              disabled: false,
              rowIndex: rowKey,
              indeterminate:false,
              record
            };

            if (selectedRowKeys) {
              let check = selectedRowKeys.includes(rowKey);
              if (check) {
                props.value = true;
              } else {
              }
            }

            // props.name = rowKey;
            if (!(rowKey in this.selectionBoxValues)) {
              this.$set(this.selectionBoxValues, rowKey, props);
            }
            if (typeof getCheckboxProps == 'function') {
              let reslut = getCheckboxProps(record, index);
              if (reslut?.props) {
                for (let key in reslut.props) {
                  let v = reslut.props[key];
                  props[key] = v;
                 this.selectionBoxValues[rowKey][key]=v;
                }
              }
            }

            if (props.value) {
              this.sk[rowKey] = record;
            }
            let  selectionBoxProps = {
              props: this.selectionBoxValues[rowKey],
              on: {
                change: (e) => {
                  if (e.target.disabled) return false;
                  e.target.value=e.target.checked
                  if(rowSelectType===1){
                    this.sk = {}
                    if (this.befKey) {
                      this.selectionBoxValues[this.befKey]['value'] = false
                    }

                  }
                  if ((onChange || updateSelectedRowKeys || onSelect)) {

                    if (e.target.checked) {
                      this.sk[rowKey] = record;
                    } else {
                      delete this.sk[rowKey];

                    }
                    let selectedKeys = Object.keys(this.sk);
                    updateSelectedRowKeys?.(selectedKeys);
                    let getSelectionData=this.getSelectionData()
                    onChange?.(Object.keys(this.sk), getSelectionData);
                    onSelect?.(record, e.target.checked, getSelectionData, e.nativeEvent);
                  }
                  if (!selectedRowKeys) {
                    this.reslutSelectionAll(this.sk)
                    this.selectionBoxValues[rowKey]['value'] = e.target.checked;
                  }
                  this.befKey=rowKey

                }
              }
            };
            return <span
            onClick={(e) => {
              e.stopPropagation();
            }}
          >
            <SelectionBox {...selectionBoxProps} />
          </span>

          };
        };
      } else {
        this.renderSelectionBox = fn;
      }

     return this.renderSelectionBox(type);
    };
  })(_Table.methods.renderSelectionBox);


  _Table.methods.renderAllColumnTitle = function () {
    var h = this.$createElement;
    let {hideDefaultSelections, rowSelectType ,selectedRowKeys} = this;
    if (!rowSelectType) return null
    let {  onSelectAll,onChange } = this.rowSelection;
    let _this = this;
    let updateSelectedRowKeys=null
    if ('update:selectedRowKeys' in this.$listeners) {
      updateSelectedRowKeys = this.$listeners['update:selectedRowKeys'];
    }
    let selectionAllProps = {
      attrs: {
        checked: this.checkboxAllValue,
        indeterminate:this.checkboxAllIndeterminate
      },
      ref: 'selectionAll',
      on: {
        change: (event, a) => {
          let data = this.getFlatCurrentPageData();
          let checked = event.target.checked;
          for (let i = 0; i < data.length; i++) {
            let record = data[i];
            const rowKey = this.getRecordKey(record, i);
            let props = this.selectionBoxValues[rowKey];
            this.sk[rowKey] = record;
            if (props) {
              props.value = checked;
              if (!checked || props.disabled) {
                delete this.sk[rowKey];
              }
            }
            // 从 1 开始
          }
          if (checked) {
            // this.checkboxAllValue =true
            // this.checkboxAllIndeterminate = false
          } else {
            this.sk = {}
            // this.checkboxAllValue =false
            // this.checkboxAllIndeterminate = false
            data = []
          }

          if (onSelectAll || updateSelectedRowKeys||onChange) {
            let selectKey = checked ? Object.keys(this.sk) : []
            onChange?.(Object.keys(this.sk), data);
            updateSelectedRowKeys?.(selectKey);
            onSelectAll?.(checked, data, data);
          }

          if (!selectedRowKeys) {
            this.reslutSelectionAll(this.sk)
          }

        }
      }
    };

    return hideDefaultSelections&& rowSelectType == 2 ? <a-checkbox {...selectionAllProps} /> : <span/>;
  };
  _Table.methods.renderRowSelection = (function (fn) {
    return function ({ prefixCls, locale, getPopupContainer }) {
      if (this.tableType !== 't-table') {
        return fn.apply(this, arguments);
      }

      if (!this.rowSelectType) return this.columns


      this.rowSelection.columnTitle =this.renderAllColumnTitle

      const vNode = fn.apply(this, arguments);

      let col = vNode.find((col) => {
        if (col.key == 'selection-column') {
          return col;
        }
      });

      if (col?.fixed) {
        col._vc_class = 'ant-table-column-fixed-sticky-left';
        col.customHeaderCell = (column) => {
          column.class = 'ant-table-column-fixed-sticky-left';
          return column;
        };
      }
      if (typeof this.customCell == 'function') {
        col.customCell=this.customCell
      }
      return vNode;
    };
  })(_Table.methods.renderRowSelection);
  /**分页重写 */
  _Table.methods.renderPagination = (function (fn) {
    return function (prefixCls, paginationPosition) {
      if (this.tableType !== 't-table') {
        return fn.apply(this, arguments);
      }
      if (!this.hasPagination()) {
        return null;
      }
      const {vScrollY}=this
      var h = this.$createElement;
      const { sPagination: pagination } = this;
      const { style, total, onShowSizeChange, pageSize,onChange,...restProps } = pagination;

      var position = pagination.position || 'bottom';

      var paginationProps = {
        class: prefixCls + '-pagination',
        style,
        attrs: {
          ...restProps,
          total:total||1,
          disabled:!total,
          current: this.getMaxCurrent(total),

        },
        on: {
          click(event) {
            return false;
          },
          change: this.handlePageChange,
          showSizeChange: this.handleShowSizeChange,
        }
      };

      return (position === paginationPosition || position === 'both') ? (
        <a-pagination {...paginationProps} />
      ) : null;
    };
  })(_Table.methods.renderPagination);

  // _Table.render = (function (fn) {
  //   return function (h) {

  //     let dragLine = h(createDragLine(this),{ref: "dragLine",key:'dragLine' })
  //     const vNode = fn.apply(this, arguments);
  //     vNode.children.push(dragLine)
  //     return vNode
  //   }
  // })(_Table.render);
}
