<!-- @desc:显示表格  @auth:周兴  @time:2022/11/14 16:29 -->
<template>
  <div :style="{height: 100 + '%',width:divWidth}" v-if="existsFlag">
    <div v-if="title" class="table-title">{{ title }}
      <Poptip trigger="hover" transfer placement="top-start" :content="titleInfo" v-if="titleInfo">
        <Icon type="iconfont iconfont icon-question" style="cursor: pointer;font-size: 12px" color="#909399"
              ref="info-icon"/>
      </Poptip>
    </div>
    <vxe-table
      class="dk-table-scrollbar"
      header-row-class-name="header-class"
      :cell-style="cellStyle"
      :footer-cell-style="footCellStyle"
      :cell-class-name="cellClassName"
      :row-class-name="rowClassName"
      align="center"
      size="mini"
      :id="id"
      :border="border"
      :ref="name"
      :tableWidth="width + 'px'"
      :height="autoHeight?'auto':(height +'px')"
      :stripe="false"
      :show-header="showHeader"
      auto-resize
      :scroll-y="{gt:20}"
      :sort-config="{showIcon:sortable}"
      :column-config="{isCurrent: true, isHover: true, resizable: true}"
      :show-footer="showFooter"
      :checkbox-config="{range:checkRange,showHeader:showCheckboxHeader,visibleMethod: checkboxMethod}"
      :footer-method="footerMethod"
      :data="dataFinal"
      :menu-config="{ visibleMethod:visibleMethod,header:header,body:header}"
      @contextmenu.native.prevent
      @scroll="handleScroll"
      @cell-menu="cellMenu"
      @menu-click="menuClick"
      @cell-click="cellClick"
      @checkbox-change="selectChange"
      @checkbox-all="selectAll"
      @current-change="currentChangeEvent"
      @checkbox-range-change="selectRangeChange"
      @cell-mouseenter="handleCellMouseEnter"
      @cell-mouseleave="handleCellMouseLeave"
      @footer-cell-dblclick="handleFooterCopy"
      :tooltip-config="{contentMethod:loadTipContentMethod,enterable: true}"
      :tree-config="treeFlag?{transform: treeFlag, rowField: treeRowField, parentField: parentField,lazy: lazy, hasChild: 'hasChild', loadMethod: loadChildrenMethod, children: treeChildren}:undefined"
      :radio-config="{highlight: true,strict: true,checkField: 'checked',
       trigger: triggerFlag ? 'row' :null ,checkMethod:checkMethodFlag ? checkRadioMethod : null }"
      @radio-change="radioSelectChange"
      :row-config="{isCurrent: true, isHover: true}"
    >
      <DkTableColumn v-if="chooseFlag" :type="(multiple?'checkbox':'radio')" width="50" fixed="left"></DkTableColumn>
      <DkTableColumn type="seq" width="45" fixed="left" :show-tip="showTip" :seq-tip-content="seqTipContent"
                     :chooseDataFlag="chooseDataFlag"
                     :add-flag="addFlag"></DkTableColumn>
      <slot></slot>
      <template #empty>
        <img src="@/assets/images/new-no-data.png" style="width: 110px;height: 72px;" @contextmenu.prevent/>
        <p style="color: rgb(155, 157, 177);margin-top: 10px">{{ vm.$t('noData') }}</p>
      </template>
    </vxe-table>

    <!--设置-->
    <div class="setting-class" v-if="showSettingFlag && settingLeft"
         :style="'top:' + settingTop + ';left:' + settingLeft"
         @click="showSetting">
      <Icon type="md-settings"/>
    </div>
    <!--  全屏  -->
    <div class="setting-class" v-if="showSettingFlag && settingLeft "
         :style="'top:' + settingTop + ';left:' + (parseInt(settingLeft.replace('px', '')) - 20) + 'px'"
         @click="handleMax">
      <icon type="iconfont iconfont icon-max1"></icon>
    </div>
    <!--不能用上面的，因为会根据settingLeft来设置，这个有滞后性-->
    <div ref="setting"></div>

    <div id="pageInfo" v-if="pageTotalFlag || pageFlag || treeFlag"
         class="table-foot-class">
      <div style="display: flex;align-items: center">
        <slot name="foot-button"></slot>
        <div v-if="pageTotalFlag"
             class="table-choose-foot" style="display: flex">
          <!--多选才会体现已选数据-->
          <div v-if="chooseFlag && multiple">
            {{
              selectFlag && batchKeys.length > 0 ? vm.$t('chosedText') + batchKeys.length + vm.$t('items') + ',' : ''
            }}
          </div>
          <div>
            {{ vm.$t('total') + getTotalCount() + vm.$t('items') }}
          </div>
          <Tag style="background:  #2E406B" color="#fff" v-if="clearBtnText && dataFinal.length > 0">{{
              clearBtnText
            }}
          </Tag>
          <span v-if="filterContent.length>0 "> {{
              '【' + vm.$t('filtered') + ' ' + dataFinal.length + vm.$t('items') + '】'
            }} </span>
          <Tag class="filter-button" v-for="(it,index) in filterContent" @click.native="handleClick(it)"
               :key="index" :name="it" closable @on-close="closeTagFilterContent">{{ it }}
          </Tag>
        </div>
        <!--展开收缩按钮-->
        <div style="display: flex;padding-left: 5px" v-if="treeFlag">
          <Button type="default" size="small" @click="expandAll" style="margin-left: 2px">
            {{ vm.$t('expand') }}
          </Button>
          <Button type="default" size="small" @click="unExpandAll" style="margin-left: 2px">
            {{ vm.$t('collapse') }}
          </Button>
        </div>
        <!--提示信息-->
        <div style="margin-left: 10px;display: flex" v-if="noteInfo">
          <div style="color: red;margin-right: 5px;font-weight: bold">※</div>
          {{ noteInfo }}
        </div>
      </div>

      <Page v-if="pageFlag" :page-size="pageSize?pageSize: pageInfo.pageSize" :current="pageInfo.currentPage"
            :page-size-opts="pageSizeOpts" :total="pageInfo.total" size="small"
            show-elevator show-sizer
            @on-change="currentPageChange" @on-page-size-change="pageSizeChange"
      />
      <div v-else></div>
    </div>

  </div>
</template>

<script>
import XEUtils from 'xe-utils'
import {mapActions} from "vuex";

export default {
  name: 'DkTable',
  props: {
    border: {
      type: String,
      default: 'full'
    },
    // 组件的值
    id: {
      type: String,
      default: ''
    },
    //组件的ref
    name: {
      type: String,
      default: 'table'
    },
    // table的高度
    height: {
      type: [String, Number],
      default: 260
    },
    // table的宽度
    width: {
      type: [String, Number],
      default: 260
    },
    divWidth: {
      type: String,
      default: '100%'
    },
    // table的数据源
    data: {
      type: Array,
      default: () => []
    },
    //合计行
    showFooter: {
      type: Boolean,
      default: false
    },
    //是否显示标题
    showHeader: {
      type: Boolean,
      default: true
    },
    // 表头显示checkbox
    showCheckboxHeader: {
      type: Boolean,
      default: true
    },
    //列表数据主键
    primaryKey: {
      type: String,
      default: 'id'
    },
    //列表查询数据主键
    primarySearchKey: {
      type: String,
      default: ''
    },
    // 是否显示分页组件
    pageFlag: {
      type: Boolean,
      default: true
    },
    //是否显示分页条数
    pageTotalFlag: {
      type: Boolean,
      default: true
    },
    //分页条数设置
    pageSizeOpts: {
      type: Array,
      default: () => {
        return [100, 200, 500, 1000]
      }
    },
    //每页行数
    pageSize: {
      type: Number,
      default: null
    },
    // 是否显示已选条数
    selectFlag: {
      type: Boolean,
      default: true
    },
    // 是否重刷选择
    refreshSelect: {
      type: Boolean,
      default: false
    },
    // 是否默认勾选checkbox
    chooseCheckFlag: {
      type: Boolean,
      default: true
    },
    // 选择列是否可以点击
    checkDisable: {
      type: Boolean,
      default: true
    },
    // 点击其他单元格勾选checkbox
    linkClickChecked: {
      type: Boolean,
      default: false
    },
    //是否清除选择数据
    clearCheckFlag: {
      type: Boolean,
      default: true
    },
    //控制radio是否禁用
    checkMethodFlag: {
      type: Boolean,
      default: false
    },
    // 是否是树形结构
    treeFlag: {
      type: Boolean,
      default: false
    },
    // 是否懒加载（树形）
    lazy: {
      type: Boolean,
      default: true
    },
    // 子级数据
    children: {
      type: Array,
      default: () => []
    },
    // 数据类型（用于树形结构展开节点时使用）
    dataType: {
      type: String,
      default: null
    },
    //操作标识是否可见
    operateFlag: {
      type: Boolean,
      default: false
    },
    // 合并处理的字段（比如组合促销的促销Id)
    combinedField: {
      type: String,
      default: ''
    },
    // 树结构中，当前数据子级的字段名
    treeChildren: {
      type: String,
      default: 'children'
    },
    // 树结构中 树节点的字段名
    treeRowField: {
      type: String,
      default: 'id'
    },
    //清空按钮的名称
    clearBtnText: {
      type: String,
      default: ''
    },
    // 是否可以进行导出
    export: {
      type: Boolean,
      default: true
    },
    // 合计的方式（按照总单还是明细:detail(明细）；total(总单)）
    sumTotalType: {
      type: String,
      default: 'detail'
    },
    // 是否按照子级进行统计
    sumChildFlag: {
      type: Boolean,
      default: false
    },
    // 是否展开所有树形
    expandFlag: {
      type: Boolean,
      default: false
    },
    // 传入参数（用于查询时传入特定的查询调价）
    otherSearchParam: {
      type: Object,
      default: null
    },
    // 父级字段名称
    parentField: {
      type: String,
      default: 'parentId'
    },
    //是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    //是否需要选择列
    chooseFlag: {
      type: Boolean,
      default: true
    },
    // 是否显示设置按钮
    showSettingFlag: {
      type: Boolean,
      default: true
    },
    // 子级是否禁用
    childDisableFlag: {
      type: Boolean,
      default: true
    },
    // 是否开启过滤
    filter: {
      type: Boolean,
      default: true
    },
    // 是否开启冻结
    freeze: {
      type: Boolean,
      default: true,
    },
    //是否进行排序
    sortable: {
      type: Boolean,
      default: true
    },
    //总条数
    pageTotal: {
      type: [String, Number],
      default: 0
    },
    // 当前页码
    currentPage: {
      type: Number,
      default: 1,
    },
    // 是否显示序号tip
    showTip: {
      type: Boolean,
      default: false
    },
    // 加载标识
    loading: {
      type: Boolean,
      default: false
    },
    // 新建按钮
    addFlag: {
      type: Boolean,
      default: false
    },
    // 是否能进行透视
    perspectiveFlag: {
      type: Boolean,
      default: true
    },
    // 序号提示信息
    seqTipContent: {
      type: String,
      default: null
    },
    // 自适应列宽
    autoWidthFlag: {
      type: Boolean,
      default: true
    },
    // 是否开启双击行号选择数据的标识
    chooseDataFlag: {
      type: Boolean,
      default: false
    },
    // 提示信息
    noteInfo: {
      type: String,
      default: null
    },
    // 表格标题
    title: {
      type: String,
      default: undefined,
    },
    // 标题说明
    titleInfo: {
      type: String,
      default: undefined,
    },
    // 单元格样式
    cellClassName: {
      type: [String, Function],
      default: null
    },
    // 行样式
    rowClassName: {
      type: [String, Function],
      default: null
    },
    // 是否显示右键菜单
    cellMenuFlag: {
      type: Boolean,
      default: true
    },
    // 是否自动高度
    autoHeight: {
      type: Boolean,
      default: false
    }
  },
  provide() {
    return {
      operateFlag: this.operateFlag,
      treeFlag: this.treeFlag,
      changeTableData: this.changeTableData,
      dkTable: this,
      tableData: () => this.dataFinal,
      tableSocial: () => this.data, // 把原始的列表传递过去，如果只有一个过滤条件，那么需要显示所有的数据
      filterContent: () => this.filterContent,// 过滤
    }
  },
  data() {
    const vm = window.vm
    let self = this
    return {
      vm: vm,
      flag: true,
      existsFlag: true,
      loadingData: false,
      exportCondition: {},
      userTableSetInfo: null,
      header: {
        options: [
          [
            // <!--过滤-->
            {
              code: 'filter', name: vm.$t('filter'), disabled: false, visible: false, children: [
                {code: 'headerFilter', name: vm.$t('headerFreeze'), disabled: false, visible: true},
                {code: 'cellFilter', name: vm.$t('filter'), disabled: false, visible: true},
                {code: 'exceptFilter', name: vm.$t('exceptFilter'), disabled: false, visible: true},
                {code: 'clearTag', name: vm.$t('clearFilter'), disabled: false, visible: false},
              ]
            },
            // <!--冻结-->
            {
              code: 'freeze', name: vm.$t('freeze'), disabled: false, visible: false, children: [
                {code: 'colFreeze', name: vm.$t('freeze'), disabled: false, visible: true},
                {code: 'clearFreeze', name: vm.$t('clearFreeze'), disabled: false, visible: false},
              ]
            },
            // <!--定位-->
            {
              code: 'position', name: vm.$t('positionItem'), disabled: false, visible: true, children: [
                {code: 'rowPosition', name: vm.$t('rowPosition'), disabled: false, visible: true},
                {code: 'colPosition', name: vm.$t('colPosition'), disabled: false, visible: true},
              ]
            },
            // 透视
            {
              code: 'perspective', name: vm.$t('perspective'), disabled: false, visible: self.perspectiveFlag
            },
            // <!--自适应列宽-->
            {
              code: 'adaption', name: vm.$t('adaption'), disabled: false, visible: true, children: [
                {code: 'selfAdaptionOne', name: vm.$t('selfAdaptionOne'), disabled: false, visible: true},
                {code: 'selfAdaption', name: vm.$t('selfAdaption'), disabled: false, visible: true},
              ]
            },
            // <!--导出-->
            {
              code: 'export', name: vm.$t('export'), disabled: false, visible: true, children: [
                {code: 'exportAll', name: vm.$t('exportAll'), disabled: false, visible: true},
              ]
            },
          ]
        ]
      },
      pageInfo: {
        total: 0,
        pageSize: self.pageSize ? self.pageSize : this.$config.pageSize,
        currentPage: 1
      },
      batchKeys: [],
      batchRows: [],
      key: null,
      dataFinal: [], // 记录table,为了改变table，不能直接放在属性中
      dataSocial: [],// 记录原始的table数据，用过恢复过滤
      dataSocialOld: [],// 记录上一次过滤的table数据，用过恢复过滤
      filterContent: [], // 过滤的内容
      filedName: null,
      columns: [],   // 列
      checkRange: true, //鼠标拖动勾选
      //控制raido与checkbox是否联动标识
      triggerFlag: true,
      // 数据源的service
      service: {},
      methodsName: '',     // 查询子级的方法
      freezeFlag: false,     // 是否进行冻结
      settingLeft: null,          // 设置图标居左的位置
      settingTop: null,           // 设置图标居上的位置
      chooseTop: null,             // 全选图标居上的位置
      chooseLeft: null,            // 全选图标居左的位置
      menuFlag: false,// 右键菜单状态
      cellMenuObj: null,// 右键点击的实体
    }
  },
  watch: {
    loading(n, o) {
      this.loadingData = n;
    },
    data(n, o) {
      this.key = null
      this.dataFinal = n
      if (n && n.length > 0) {
        this.dataSocial = [...n]
      }
      // this.HandleComponentInstance(n) // 检查是否可以打开过滤面板
      //只有能清除才能清除选择数据
      if (this.clearCheckFlag) {
        this.clearBatchKeys()       //清除已选
      }
      if (n && n.length > 0) {
        //设置当前行
        this.$refs[this.name].setCurrentRow(n[0])
        if (!this.refreshSelect) {
          this.currentChangeEvent({row: n[0]})
        }
      }
      this.clearAllFilter()// 清理所有表格的条件（过滤，已选）
      if (this.refreshSelect) {
        this.clearAllCondition()
        if (n && n.length > 0) {
          // 默认选中第一行
          this.setCheckedRow(n[0])
        }
      }
      if (this.treeFlag && this.expandFlag) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs[this.name].setAllTreeExpand(true) //展开树形
          }, 100)
        })
      }
      if (this.autoWidthFlag && n && n.length > 0) {
        // 自适应列宽
        this.$nextTick(() => {
          this.autoWidthHandle();
        })
      }
    },
    // 过滤内容
    filterContent(n, o) {
      let visible = (n && n.length > 0) ? true : false;
      let filters = this.header.options[0].filter(it => it.code === 'filter');
      if (filters && filters.length > 0) {
        filters[0].children.update({code: 'clearTag', visible: visible}, 'code', 'visible');
      }
    },
    // 冻结
    freezeFlag(n, o) {
      let filters = this.header.options[0].filter(it => it.code === 'freeze');
      if (filters && filters.length > 0) {
        filters[0].children.update({code: 'clearFreeze', visible: n}, 'code', 'visible');
      }
    },
    // 总条数
    pageTotal(n, o) {
      this.pageInfo.total = n;
    },
    // 当前页码
    currentPage(n, o) {
      this.pageInfo.currentPage = n;
    },
  },
  methods: {
    ...mapActions([
      'setUserTableSettingAfter'
    ]),
    /**
     * @desc   : 合计行的复制
     * @author : 周兴
     * @date   : 2022/8/6 11:15
     */
    handleFooterCopy(e) {
      if (e && e.items && e.items[e.itemIndex]) {
        let value = e.items[e.itemIndex] + '';
        value = value.replaceAll(',', '');
        this.$message.success(vm.$t('copySuccess') + '：' + value);
        //创建一个input框
        const input = document.createElement("input");
        //将指定的DOM节点添加到body的末尾
        document.body.appendChild(input);
        //设置input框的value值为直播地址
        input.setAttribute("value", value);
        //选取文本域中的内容
        input.select();
        //copy的意思是拷贝当前选中内容到剪贴板
        //返回值为一个Boolean，如果是 false 则表示操作不被支持或未被启用
        if (document.execCommand("copy")) {
          document.execCommand("copy");
        }
        //删除这个节点
        document.body.removeChild(input);
      }
    },
    /**
     * @desc   : 获取表格列
     * @author : 周兴
     * @date   : 2023/4/4 15:47
     */
    getTableColumn() {
      return this.$refs[this.name].getTableColumn();
    },
    /**
     * @desc   : 重新加载列
     * @author : 周兴
     * @date   : 2023/4/4 16:24
     */
    loadColumn(columns) {
      return this.$refs[this.name].loadColumn(columns);
    },
    /**
     * @desc   : 冻结左侧的列，要先把其他列都解冻
     * @author : 周兴
     * @date   : 2022/12/1 9:57
     */
    freezeColumn(column) {
      // 先把所有列解冻
      if (!column) return;
      const tableColumns = this.$refs[this.name].getTableColumn()
      if (tableColumns && tableColumns.visibleColumn) {
        tableColumns.visibleColumn.forEach(it => {
          it.fixed = ''
        })
        let columnIndex = 0;
        let hideNum = 0;
        // this.$slots.default.forEach((it, index) => {
        //   if (it && it.componentInstance) {
        //     if (it.componentInstance.field != column.field) {
        //       it.componentInstance.freezeFlag = false;
        //       if (!it.componentInstance.visible) {
        //         hideNum++;
        //       }
        //     } else {
        //       columnIndex = this.chooseFlag ? (index + 2) : (index + 1);
        //     }
        //     console.log('t3',it.componentInstance.field,column.field,it.componentInstance.freezeFlag)
        //   }
        // })
        tableColumns.visibleColumn.forEach((it, index) => {
          if (it.field != column.field) {
            // it.componentInstance.freezeFlag = false;
            // if (!it.componentInstance.visible) {
            //   hideNum++;
            // }
          } else {
            columnIndex = this.chooseFlag ? index + 1 : index;
          }
        })
        // 先把所有的图标去掉
        this.$slots.default.forEach((it, index) => {
          if (it && it.componentInstance) {
            it.componentInstance.freezeFlag = false;
          }
        })
        let filters = this.$slots.default.filter(it => it.componentInstance.field == column.field)
        if (filters && filters.length > 0) {
          filters[0].componentInstance.freezeFlag = true;
        }
        // if (hideNum) {
        //   columnIndex = columnIndex - hideNum;
        // }
        // console.log('t3', hideNum,columnIndex,this.chooseFlag)
        // 冻结该列之前的列，包括这列
        for (let i = 0; i <= columnIndex; i++) {
          tableColumns.visibleColumn[i].fixed = 'left'
        }
        this.$refs[this.name].refreshColumn();
        this.freezeFlag = true;
      }
    },
    /**
     * @desc   : 列冻结
     * @author : 周兴
     * @date   : 2023/2/9 15:20
     */
    handleFreeze(e) {
      if (this.$slots.default && this.$slots.default.length > 0) {
        let columnIndex = e.columnIndex - (this.chooseFlag ? 2 : 1);
        // console.log('rrrr', columnIndex, this.$slots.default[columnIndex].componentInstance.handleFreeze)
        if (this.$slots.default[columnIndex] && this.$slots.default[columnIndex].componentInstance.handleFreeze) {
          // console.log('t1')
          this.$slots.default[columnIndex].componentInstance.handleFreeze(e);
        }
      }
    },
    /**
     * @desc   : 解除冻结
     * @author : 周兴
     * @date   : 2022/12/1 13:30
     */
    unFreeze() {
      const tableColumns = this.$refs[this.name].getTableColumn()
      if (tableColumns && tableColumns.visibleColumn) {
        tableColumns.visibleColumn.forEach(it => {
          if (it.type != 'seq' && it.type != 'radio' && it.type != 'checkbox') {
            it.fixed = ''
          }
        })
        for (let it of this.$slots.default) {
          if (it && it.componentInstance) {
            it.componentInstance.freezeFlag = false;
          }
        }
        this.freezeFlag = false;
        this.$refs[this.name].refreshColumn();
      }
    },
    /**
     * @desc   : 表头过滤
     * @author : 周兴
     * @date   : 2023/2/9 13:51
     */
    headerFilter(e) {
      if (this.$slots.default && this.$slots.default.length > 0) {
        let columnIndex = e.columnIndex - (this.chooseFlag ? 2 : 1);
        if (this.$slots.default[columnIndex] && this.$slots.default[columnIndex].componentInstance.$refs.popTip) {
          setTimeout(() => {
            this.$slots.default[columnIndex].componentInstance.$refs.popTip.visible = true
          }, 100)
        }
      }
    },
    /**
     * @desc   : 根据当前单元格过滤
     * @author : 周兴
     * @date   : 2023/2/9 15:40
     */
    cellFilter(e) {
      if (this.$slots.default && this.$slots.default.length > 0) {
        let columnIndex = e.columnIndex - (this.chooseFlag ? 2 : 1);
        if (this.$slots.default[columnIndex] && this.$slots.default[columnIndex].componentInstance) {
          let component = this.$slots.default[columnIndex].componentInstance;
          component.social = [e.row[e.column.field] ? e.row[e.column.field].toString() : ''];
          component.search();
        }
      }
    },
    /**
     * @desc   : 除外过滤
     * @author : 周兴
     * @date   : 2023/2/9 15:52
     */
    exceptFilter(e) {
      if (this.$slots.default && this.$slots.default.length > 0) {
        let columnIndex = e.columnIndex - (this.chooseFlag ? 2 : 1);
        if (this.$slots.default[columnIndex] && this.$slots.default[columnIndex].componentInstance) {
          let component = this.$slots.default[columnIndex].componentInstance;
          let value = e.row[e.column.field] ? e.row[e.column.field] : '';
          // 过滤出除外数据
          component.social = this.dataFinal?.map(item => item[e.column.field] ? item[e.column.field].toString() : '').filter(it => it != value)
          component.search();
        }
      }
    },
    /**
     * @desc   : 展开所有
     * @author : 周兴
     * @date   : 2023/1/28 10:46
     */
    expandAll() {
      this.$refs[this.name].setAllTreeExpand(true)
    },
    /**
     * @desc   : 清空数据
     * @author : 周兴
     * @date   : 2022/4/21 17:24
     */
    clearTable() {
      this.dataFinal = [];
      this.clearBatchKeys()
    },
    /**
     * @desc   : 收缩所有
     * @author : 周兴
     * @date   : 2023/1/28 10:46
     */
    unExpandAll() {
      this.$refs[this.name].setAllTreeExpand(false)
    },
    /**
     * @desc   : 获取条数
     * @author : 周兴
     * @date   : 2022/8/20 8:42
     */
    getTotalCount() {
      let count = 0;
      if (this.sumChildFlag && this.treeFlag) {
        if (this.dataFinal && this.dataFinal.length > 0) {
          this.dataFinal.forEach(it => {
            if (it.bomItems && it.bomItems.length > 0) {
              count += it.bomItems.length;
            }
          })
        }
      } else {
        count = this.pageInfo.total ? this.pageInfo.total : this.dataFinal?.length;
      }
      return count;
    },
    /**
     *   @author : 寇珊珊
     *   @date   : 2022/3/23 16:29
     *   @desc   : 自适应全部列宽
     */
    autoWidthHandle(e) {
      if (this.dataFinal && this.dataFinal.length > 0) {
        let data = this.dataFinal.copy();
        if (e) {
          if (e.column) {
            // 当前列的自适应
            let columnValues = data.map(it => {
              if (typeof it[e.column.field] == 'boolean') {
                return ''
              } else if (it[e.column.field] == null || it[e.column.field] == undefined) {
                return ''
              } else {
                return it[e.column.field]
              }
            });
            let col = e.column.params
            if (col.type !== 'seq' && col.type !== 'radio' && col.type !== 'checkbox'
              && col.type !== 'operate' && col.type !== 'image' && col.type !== 'button') {
              columnValues.push(e.column.title + '占')  // 把每列的表头也加进去算
              let width = this.getMaxLength(columnValues) + 30 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
              // 取这个宽度和最小宽度的最大值
              let minWidth = e.column.minWidth?.replace('px', '').toNum(0);
              this.$set(e.column, 'width', [width, minWidth].max())
            }
          }
        } else {
          // 全部可见列的自适应
          let columns = this.$refs[this.name].getColumns();
          columns.forEach(col => {
            if (col.type !== 'seq' && col.type !== 'radio' && col.type !== 'checkbox'
              && col.type !== 'operate' && col.type !== 'image' && col.type !== 'button') {
              let columnValues = data.map(it => {
                if (typeof it[col.field] == 'boolean') {
                  return ''
                } else if (it[col.field] == null || it[col.field] == undefined) {
                  return ''
                } else {
                  return it[col.field]
                }
              });
              columnValues.push(col.title + '占')  // 把每列的表头也加进去算
              let width = this.getMaxLength(columnValues) + 30 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
              // 取这个宽度和最小宽度的最大值
              let minWidth = col.minWidth?.replace('px', '').toNum(0);
              this.$set(col, 'width', [width, minWidth].max())
            }
          })
        }
        this.$nextTick(() => {
          this.$refs[this.name]?.resetColumn({resizable: true})
          this.$refs[this.name]?.recalculate()
        })
      }
    },
    /**
     * @desc   : 树形时控制选择框是否能使用
     * @author : 周兴
     * @date   : 2022/5/31 9:34
     */
    checkboxMethod({row}) {
      if (this.treeFlag && row['parentId']) {
        return false;
      }
      return true;
    },
    /**
     * @desc   : 判断是否选择数据
     * @author : 周兴
     * @date   : 2022/12/26 16:11
     */
    checkIsSelectData() {
      if (this.batchKeys && this.batchKeys.length > 0) {
        return true;
      }
      return false;
    },
    /**
     * @desc   : 增加当前行hover
     * @author : 周兴
     * @date   : 2023/5/17 16:39
     */
    addHover(rowIndex) {
      rowIndex = rowIndex ? rowIndex : 0
      if (this.operateFlag && rowIndex >= 0) {
        // 如果行不变，不用执行
        if (rowIndex != this.rowIndex) {
          if (this.dataFinal && this.dataFinal.length > 0) {
            this.dataFinal.forEach(it => {
              this.$set(it, '_hover', false)
            })
          }
        }
        setTimeout(() => {
          if (rowIndex >= 0 && this.dataFinal[rowIndex]) {
            this.$set(this.dataFinal[rowIndex], '_hover', true)
          }
        }, 30)
      }
    },
    /**
     * @desc   : 鼠标移入增加新增和删除按钮
     * @author : 周兴
     * @date   : 2022/4/19 10:56
     */
    handleCellMouseEnter(e) {
      // console.log('bbb',e)
      // this.$refs[this.name].closeTooltip()
      // this.$refs[this.name].openTooltip(e.cell,'tttt')
      // if (this.operateFlag && rowIndex >= 0) {
      //   this.$set(this.$refs[this.name].data[rowIndex], '_hover', true)
      // }
    },
    /**
     * @desc   : 鼠标移出删除新增和删除按钮
     * @author : 周兴
     * @date   : 2022/4/19 10:56
     */
    handleCellMouseLeave({rowIndex}) {
      // if (this.operateFlag && rowIndex >= 0) {
      //   this.$set(this.$refs[this.name].data[rowIndex], '_hover', false)
      // }
    },
    /**
     * @desc   : 设置选中的行
     * @author : 周兴
     * @date   : 2022/4/22 14:14
     */
    setCheckedRow(row) {
      this.$refs[this.name].clearCurrentRow();
      this.$refs[this.name].setCurrentRow(row)
      this.$refs[this.name].toggleCheckboxRow(row)
      this.$refs[this.name].setRadioRow(row)
      this.selectChange({checked: true, row: row})
    },
    /**
     * @desc   : 取消当前行勾选
     * @author : 周兴
     * @date   : 2022/5/3 18:23
     */
    setUnCheckedRow(row) {
      this.$refs[this.name].setCurrentRow(row)
      this.$refs[this.name].setCheckboxRow(row, false)
      this.selectChange({checked: false, row: row})
    },
    /**
     * @desc   : 设置当前行
     * @author : 周兴
     * @date   : 2022/5/3 17:49
     */
    setCurrentRow(row) {
      this.$refs[this.name].setCurrentRow(row);
      this.currentChangeEvent({row})
    },
    /**
     * @desc   : 滚动到当前行
     * @author : 周兴
     * @date   : 2023/2/15 13:01
     */
    scrollToRow(row) {
      this.$refs[this.name].scrollToRow(row);
    },
    /**
     * @desc   : 清空当前行
     * @author : 周兴
     * @date   : 2022/12/2 11:40
     */
    clearCurrentRow() {
      this.$refs[this.name].clearCheckboxRow();
      this.$refs[this.name].clearRadioRow();
      this.$refs[this.name].clearCurrentRow()
    },
    /**
     * @desc   : 获取当前行
     * @author : 周兴
     * @date   : 2022/5/3 17:51
     */
    getCurrentRow() {
      return this.$refs[this.name].getCurrentRecord()
    },
    /**
     * @desc   : 获取当前行号
     * @author : 周兴
     * @date   : 2022/5/3 17:51
     */
    getCurrentRowIndex() {
      let row = this.$refs[this.name].getCurrentRecord()
      if (row) {
        return this.$refs[this.name].getRowIndex(row)
      }
    },
    /**
     * @desc   : desc
     * @author : 周兴
     * @date   : 2022/4/26 16:56
     */
    reloadData(data) {
      if (this.$refs[this.name]) {
        this.$refs[this.name].reloadData(data)
      }
    },
    /**
     * @desc   : 列的动态样式
     * @author : 张潇木
     * @date   : 2022/4/16 15:31
     */
    cellStyle({row, rowIndex, column}) {
      if (column.type === 'seq') {
        return {textAlign: this.treeFlag ? 'left' : "center"}
      }
      if (column.type === 'checkbox' || column.type === 'radio' || column.type === 'switch'
        || column.type === 'image') {
        return {textAlign: "center"}
      }
      if (column.params) {
        if (column.params.align) {
          return {textAlign: column.params.align}
        }
      }

      // column.property===?也可根据列名判断，也可根据column对象的属性灵活配置
      for (let it of this.$slots.default) {
        if (it && it.componentInstance) {
          if (it.componentInstance.field === column.field) {
            // 直接设置为居中
            if (it.componentInstance.centerFlag != null && it.componentInstance.centerFlag) {
              return {textAlign: "center"}
            }
            if (it.componentInstance.columnType === 'number') {
              // console.log('rrr',column.field,it.componentInstance.columnType)
              return {textAlign: 'right'}
            } else if (it.componentInstance.columnType === 'checkbox' || it.componentInstance.columnType === 'date') {
              return {textAlign: 'center'}
            } else {
              return {textAlign: 'left'}
            }
          }
        }
      }
    },

    /**
     * @desc   : 合计行的样式
     * @author : 周兴
     * @date   : 2022/8/3 15:31
     */
    footCellStyle({row, rowIndex, column}) {
      // column.property===?也可根据列名判断，也可根据column对象的属性灵活配置
      for (let it of this.$slots.default) {
        if (it && it.componentInstance) {
          if (it.componentInstance.field === column.property) {
            if (it.componentInstance.columnType === 'number') {
              return {textAlign: 'right', background: '#FFF8E1', cursor: 'pointer'}
            } else {
              return {textAlign: 'left', background: '#FFF8E1'}
            }
          }
        }
      }
    },
    /**
     * @desc   : 隐藏pop弹窗
     * @author : 周兴
     * @date   : 2022/3/31 15:31
     */
    hideAllPop() {
      this.$nextTick(() => {
        if (this.$slots.default) {
          for (let it of this.$slots.default) {
            if (it && it.componentInstance && it.componentInstance.$refs &&
              it.componentInstance.$refs.popTip) {
              it.componentInstance.$refs.popTip.visible = false
            }
          }
        }
      })
    },
    /**
     * @desc   : 清除过滤，清除已选等
     * @author : 周兴
     * @date   : 2022/3/31 14:30
     */
    clearAllCondition() {
      this.clearBatchKeys()       //清除已选
    },
    /**
     * @desc   : 合计行运算
     * @author : 周兴
     * @date   : 2022/3/31 11:28
     */
    footerMethod({columns, data}) {
      //如果不开启合计行，那么就不走该方法
      if (!this.showFooter) return
      let total = vm.$t('totalSum')
      const sums = []
      if (sums.indexOf(total) < 0) {
        sums.push(total)
      }
      // 如果选择框开启
      if (this.chooseFlag) {
        sums.push('')
      }
      let sumCell = null
      this.$nextTick(() => {
        let columnIndex = 0
        //循环各列
        for (let it of this.$slots.default) {
          if (it && it.componentInstance) {
            sumCell = null
            // 开启合计
            if (it.componentInstance.sum) {
              for (let column of columns) {
                if (it.componentInstance.field === column.property) {
                  // console.log('t1',it.componentInstance.columnType)
                  // if (it.componentInstance.columnType === '' && it.componentInstance.getColumnType) {
                  //   it.componentInstance.getColumnType(data)
                  // }
                  // 如果是数值可以进行合计
                  if (it.componentInstance.columnType === this.$config.columnType.number) {
                    // 是否会按照某列去重计算合计金额
                    let sumUniqueField = it.componentInstance.sumUniqueField;
                    let digits = it.componentInstance.digits
                    if (this.sumTotalType === 'detail') {
                      data.forEach(item => {
                        // console.log('ttt',column.property,it.componentInstance.columnType,item.bomItems)
                        // 如果有子级，那么就统计子级的
                        if (item.bomItems && item.bomItems.length > 0) {
                          item.bomItems.forEach(cRow => {
                            sumCell += Number(cRow[column.property] == undefined ? 0 : cRow[column.property])
                          })
                        } else {
                          sumCell += Number(item[column.property] == undefined ? 0 : item[column.property])
                        }
                      })
                    } else if (this.sumTotalType === 'subTotal') {   // 不包括小计
                      data.forEach(item => {
                        if (!item.subTotal) {
                          sumCell += Number(item[column.property] == undefined ? 0 : item[column.property])
                        }
                      })
                    } else {
                      if (!sumUniqueField) {
                        data.forEach(item => {
                          sumCell += Number(item[column.property] == undefined ? 0 : item[column.property])
                        })
                      } else {
                        let map = data.map(it => ({
                          id: it[sumUniqueField],
                          value: it[column.property]
                        }));
                        map = map.unique();
                        if (map && map.length > 0) {
                          sumCell = map.sum('value');
                        }
                      }
                    }
                    //格式化金额
                    if (it.componentInstance.formatThousandth) {
                      sumCell = XEUtils.commafy(Number(sumCell), {digits})
                    }
                  }
                  sums.push(sumCell)
                  break
                }
              }
            } else {
              //其他列也需要插入合计 占位置(首个位置不插入进行站位)
              // if (columnIndex > 0) {
              sums.push(sumCell)
              // }
            }
          }
          columnIndex++
        }
      })
      return [sums]
    },
    /**
     * @desc   : 操作列（过滤面板，合计行）
     * @author : 周兴
     * @date   : 2022/3/30 19:20
     */
    HandleComponentInstance(data) {
      this.$nextTick(() => {
        let noData = !data ? false : data.length === 0
        if (this.$slots.default && this.$slots.default.length > 0) {
          for (let it of this.$slots.default) {
            if (it && it.componentInstance) {
              // 只有开启了表头过滤才会进行
              if (it.componentInstance.filter) {
                it.componentInstance.popDisabled = noData
                // 设置列的类型
                // if (it.componentInstance.getColumnType) {
                //   it.componentInstance.getColumnType(data)
                // }
              }
            }
          }
        }
      })
    },
    /**
     * @desc   : 点击打开过滤 TODO
     * @author : 周兴
     * @date   : 2022/3/29 18:11
     */
    handleClick(item) {
      //打开过滤面板
      if (this.$slots.default && this.$slots.default.length > 0) {
        for (let it of this.$slots.default) {
          if (it && it.componentInstance && it.componentInstance.onPopperShow &&
            it.componentInstance.titleData && it.componentInstance.titleData === item) {
            it.componentInstance.$refs.popTip.visible = true
            break
          }
        }
      }
    },
    /**
     * @desc   : 改变表格的数据源，供外部调用
     * @author : 周兴
     * @date   : 2022/3/19 17:05
     */
    changeTableData(field, title, va) {
      let cond = []
      for (let it of this.$slots.default) {
        if (it.tag && it.tag.includes('DkTableColumn') && it.componentInstance.field &&
          it.componentInstance.social && it.componentInstance.titleData &&
          it.componentInstance.social.length > 0) {
          cond.push({
            field: it.componentInstance.field,
            title: it.componentInstance.titleData,
            val: it.componentInstance.social
          })
        }
      }
      // 如果没有值说明就是清除过滤
      if (cond === null || cond.length === 0) {
        this.dataFinal = [...this.dataSocial]
      } else {
        let data = [...this.dataSocial]
        for (let c of cond) {
          data = data.filter(f => c.val.includes(f[c.field] ? f[c.field].toString() : ''))
        }
        this.dataFinal = data
      }
      //设置过滤内容
      let content = title
      if (!this.filterContent.includes(content) && va && va.length > 0) {
        this.filterContent.push(content)
      } else if (this.filterContent.includes(content) && va && va.length == 0) {
        const index = this.filterContent.indexOf(content)
        this.filterContent.splice(index, 1)
      }
    },
    /**
     *  @desc   : 清除表格下方筛选条件
     *  @author : 寇珊珊
     *  @date   : 2022/3/22 16:53
     */
    closeTagFilterContent(e, name) {
      const index = this.filterContent.indexOf(name)
      if (this.filterContent.includes(name)) {
        this.filterContent.splice(index, 1)
      }
      for (let it of this.$slots.default) {
        if (it && it.componentInstance && it.componentInstance.filter && it.componentInstance.clearFilter &&
          it.componentInstance.titleData && it.componentInstance.titleData == name) {
          it.componentInstance.clearFilter()
          break
        }
      }
      // 根据选择的数据，设置选中框
      this.setCheckboxRowByKeys(this.batchKeys);
    },
    /**
     * @desc   : 清除过滤
     * @author : 周兴
     * @date   : 2022/3/31 14:33
     */
    clearAllFilter() {
      this.$nextTick(() => {
        this.filterContent = []
        if (this.$slots.default && this.$slots.default.length > 0) {
          for (let it of this.$slots.default) {
            if (it && it.componentInstance && it.componentInstance.filter && it.componentInstance.clearFilter) {
              it.componentInstance.clearFilter()
            }
          }
          // 根据选择的数据，设置选中框
          this.setCheckboxRowByKeys(this.batchKeys);
        }
      })
    },
    /**
     * @desc   : 出现右键
     * @author : 周兴
     * @date   : 2023/2/23 13:39
     */
    cellMenu(e) {
      // this.menuFlag = true;
      // console.log('menuFlag', this.menuFlag,e)
      // this.cellMenuObj = {...e};
      this.$emit('cellMenu', e)
    },

    contextMenuClick(e) {
      // if (e.menu.children && e.menu.children.length > 0) {
      //   // this.$refs[this.name].closeMenu()
      //
      //   console.log('ttt', e)
      //   return false;
      // }
      return true;
    },
    /**
     * @desc   : 右键
     * @author : 周兴
     * @date   : 2022/3/30 17:24
     */
    menuClick(e) {
      // e.menu = {...this.cellMenuObj}
      // e.menu.code = e.code
      if (e.menu.code == 'selfAdaption') {
        this.autoWidthHandle()
      } else if (e.menu.code == 'selfAdaptionOne') {
        this.autoWidthHandle(e)
      } else if (e.menu.code == 'exportAll') {  // 导出所有
        this.exportExcel(e)
      } else if (e.menu.code == 'exportOne') {  // 导出当前页
        this.exportExcel()
      } else if (e.menu.code == 'rowPosition') {   // 行定位
        this.showRowPosition(e);
      } else if (e.menu.code == 'colPosition') {   // 列定位
        this.showColPosition(e);
      } else if (e.menu.code == 'headerFilter') { // 表头过滤
        this.headerFilter(e);
      } else if (e.menu.code == 'cellFilter') { // 表头过滤
        this.cellFilter(e);
      } else if (e.menu.code == 'exceptFilter') {     //除外过滤
        this.exceptFilter(e)
      } else if (e.menu.code == 'clearTag') {     //清除过滤条件
        this.clearAllFilter()
      } else if (e.menu.code == 'colFreeze') { // 列冻结
        this.handleFreeze(e);
      } else if (e.menu.code == 'clearFreeze') {  // 解除冻结
        this.unFreeze(e);
      } else if (e.menu.code == 'perspective') { // 透视
        this.handlePerspective(e);
      }
      setTimeout(() => {
      }, 400)
    },
    /**
     * @desc   : 点击菜单
     * @author : 周兴
     * @date   : 2023/12/20 15:47
     */
    clickMenu(e) {

    },
    /**
     * @desc   : 透视
     * @author : 周兴
     * @date   : 2023/3/18 17:44
     */
    handlePerspective(e) {
      let data = this.dataFinal?.copy();
      const tableColumns = this.$refs[this.name].getTableColumn()
      if (tableColumns && tableColumns.visibleColumn && data && data.length > 0) {
        let columns = [...tableColumns.visibleColumn];
        columns = columns.filter(it => it.type != 'seq' && it.type != 'checkbox' && it.type != 'radio').filterColumns(['field', 'title', 'type', 'params'])
        this.$Perspective({
            component: this.$refs[this.name],
            columns: columns,
            tableData: data
          },
          {})
      }
    },
    /**
     * @desc   : 导出excel
     * @author : 周兴
     * @date   : 2023/2/23 12:52
     */
    exportExcel(e) {
      const tableColumns = this.$refs[this.name].getTableColumn()
      if (tableColumns) {
        let columns = tableColumns.visibleColumn
        columns = columns.filter(it => it.type != 'seq' && it.type != 'checkbox' && it.type != 'radio')
        this.$Export({tableData: columns}, {
          ok: (val) => {
            this.handleExportAll(true); // 控制不允许再次点击导出
            console.log('eee', this.exportCondition, JSON.stringify(val))
            let params = {...this.exportCondition}
            // console.log('ttt', Object.assign({'seq': '序号'}, val))
            // 增加序号
            params.condition = Object.assign({'seq': '序号'}, val);
            if (e && params.pageSize) {
              // 默认导出最大设置值
              params.pageSize = this.$config.exportMax;
              params.currentPage = 1;
            }
            this.excute(this.$service.exportService, this.$service.exportService.export, params).then(res => {
              if (res.code === this.$config.SUCCESS_CODE) {
                if (res.data) {
                  window.location.href = this.$config.exportUrl + res.data
                }
              }
              this.handleExportAll(false); // 还原
            })
          }
        })
      }
    },
    /**
     * @desc   : 控制导出excel是否可用，需要导出后，才能再次导出，防止频繁导
     * @author : 周兴
     * @date   : 2023/2/23 15:36
     */
    handleExportAll(disabled) {
      let filters = this.header.options[0].filter(it => it.code === 'export');
      if (filters && filters.length > 0) {
        filters[0].children.update({code: 'exportAll', disabled: disabled}, 'code', 'disabled');
      }
    },
    /**
     * @desc   : 表格设置
     * @author : 周兴
     * @date   : 2022/12/1 15:11
     */
    showSetting(e) {
      // console.log('this.userTableSetInfo',this.userTableSetInfo)
      const tableColumns = this.$refs[this.name].getTableColumn()
      if (tableColumns) {
        let columns = tableColumns.fullColumn
        columns = columns.filter(it => it.type != 'seq' && it.type != 'checkbox' && it.type != 'radio')
        this.$TableFilter({tableData: columns, userTableSetInfo: this.userTableSetInfo},
          {
            ok: (val, userTableSetting) => {
              // 去掉冻结
              this.unFreeze();
              // 去掉选择的标题
              let filterRows = val.filter(it => it.type == 'checkbox' || it.type == 'radio');
              if (filterRows && filterRows.length > 0) {
                filterRows.forEach(it => {
                  it.title = '';
                })
              }
              if (this.chooseFlag) {
                // 加入选择
                val.splice(0, 0, tableColumns.fullColumn[0])
                // 加入序号
                val.splice(1, 0, tableColumns.fullColumn[1])
              } else {
                // 加入序号
                val.splice(0, 0, tableColumns.fullColumn[0])
              }
              // 加载列
              this.$refs[this.name].loadColumn(val);
              // 用户隐藏列
              if (userTableSetting) {
                this.setUserTableSettingAfter(userTableSetting);
              }
            },
          })
      }
    },
    /**
     * @desc   : 显示行定位定位框
     * @author : 周兴
     * @date   : 2022/11/30 13:00
     */
    showRowPosition(e) {
      this.$Position({component: this.$refs[this.name], exchangeFlag: false, title: vm.$t('rowPosition')},
        {
          // 切换查询出的数据
          change: ({field, column, rowIndex, fields, equalFlag, searchText, noSelectAll, type}) => {
            // 没有查出数据
            if (noSelectAll) {
              this.changeFind(fields, equalFlag, searchText, type);// 查找下一条
            } else {
              // 定位当前行
              this.$refs[this.name].setCurrentRow(this.dataFinal[rowIndex]);
              // 定位当前列
              // this.$refs[this.name].setCurrentColumn(column);
              this.$nextTick(() => {
                this.$refs[this.name].scrollToRow(this.dataFinal[rowIndex]);
                this.$refs[this.name].scrollToColumn(column)
              });
            }
          },
        })
    },
    /**
     * @desc   : 显示列定位定位框
     * @author : 周兴
     * @date   : 2022/11/30 13:00
     */
    showColPosition(e) {
      this.$Position({component: this.$refs[this.name], title: '列定位', colPosition: true},
        {
          ok: (searchText) => {
            this.handleColPosition(searchText);   // 执行列定位方法
          },
        })
    },
    /**
     * @desc   : 改变查找的行
     * @author : 周兴
     * @date   : 2023/2/16 13:05
     */
    changeFind(fields, equalFlag, searchText, type) {
      // 获取当前行
      let currentIndex = this.getCurrentRowIndex()
      if (!currentIndex && currentIndex != 0) {
        currentIndex = -1;
      }
      let table = this.dataFinal
      // 向下
      if (type === 'next') {
        for (let i = currentIndex + 1; i < table.length; i++) {
          let flag = this._changeFindItem(table[i], fields, equalFlag, searchText)
          if (flag) {
            return
          }
        }
      } else {
        // 向前
        for (let i = currentIndex - 1; i >= 0; i--) {
          let flag = this._changeFindItem(table[i], fields, equalFlag, searchText)
          if (flag) {
            return
          }
        }
      }
    },
    /**
     * @desc   : desc
     * @author : 周兴
     * @date   : 2023/2/16 13:09
     */
    _changeFindItem(item, fields, equalFlag, searchText) {
      // 模糊查询
      for (let it of fields) {
        // 值等
        if (equalFlag) {
          if ((item[it.field] + '') == searchText) {
            // 定位当前行
            this.$refs[this.name].setCurrentRow(item);
            this.$nextTick(() => {
              this.$refs[this.name].scrollToRow(item);
            });
            return true;
          }
        } else {
          // 模糊
          if ((item[it.field] + '').indexOf(searchText) >= 0) {
            // 定位当前行
            this.$refs[this.name].setCurrentRow(item);
            this.$nextTick(() => {
              this.$refs[this.name].scrollToRow(item);
            });
            return true;
          }
        }
      }
      return false;
    },
    /**
     * @desc   : 右键菜单
     * @author : 沈博
     * @date   : 2022/3/13 10:55
     */
    visibleMethod(e) {
      // 不显示右键菜单
      if (!this.cellMenuFlag) {
        return false;
      }
      // 判断右键菜单是否显示
      if (this.$slots.default && this.$slots.default.length > 0) {
        let columnIndex = e.columnIndex - (this.chooseFlag ? 2 : 1);
        // 表格可以过滤
        if (this.filter) {
          // 列可以过滤
          if (this.$slots.default[columnIndex] && this.$slots.default[columnIndex].componentInstance &&
            this.$slots.default[columnIndex].componentInstance.filterData) {
            this.header.options[0].update({code: 'filter', visible: true}, 'code', 'visible');
          }
        }
        // 表格可以冻结
        if (this.freeze) {
          // 列可以过滤
          if (this.$slots.default[columnIndex] && this.$slots.default[columnIndex].componentInstance &&
            this.$slots.default[columnIndex].componentInstance.freezeData) {
            this.header.options[0].update({code: 'freeze', visible: true}, 'code', 'visible');
          }
        }
      }
      return true
    },
    /**
     * @desc   : 设置选中的行
     * @author : 周兴
     * @date   : 2022/3/21 19:55
     */
    setCheckboxRow(row) {
      this.$refs[this.name].setCheckboxRow(row, true)
      // if(this.batchRows.map(it=>it[this.primaryKey]).filter(it=>it[this.primaryKey] === row[this.primaryKey]).length<=0){
      //   this.batchRows.push(row)
      // }
    },
    /**
     * @desc   : 设置多行选中列（
     * @author : 周兴
     * @date   : 2022/5/6 11:00
     */
    setCheckboxRowByKeys(val) {
      let disableFlag = this.checkDisableData
      if (!this.checkDisableData) {
        this.checkDisableData = true
      }
      //先清空
      this.$refs[this.name].clearCheckboxRow()
      if (val && this.dataFinal) {
        let rows = this.dataFinal.filter(it => val.includes(it[this.primaryKey]))
        //再赋值
        this.$refs[this.name].setCheckboxRow(rows, true)
      }
      this.checkDisableData = disableFlag
    },
    /**
     * @desc   : 清空checkbox数据源
     * @author : 周兴
     * @date   : 2022/5/6 13:01
     */
    clearCheckboxRow() {
      this.$refs[this.name].clearCheckboxRow()
    },
    /**
     * @desc   : 清除已选条数（多选）
     * @author : 周兴
     * @date   : 2022/3/10 11:35
     */
    clearBatchKeys() {
      this.batchKeys = []
      this.batchRows = []
      this.$refs[this.name].reloadData(this.dataFinal)
    },
    /**
     * @desc   : 清除已选条数（单选）
     * @author : 周兴
     * @date   : 2022/3/14 16:02
     */
    clearKey() {
      this.key = null
    },
    /**
     * @author : 沈博
     * @date   : 2022/3/4 9:34
     * @desc   : currentPage改变事件
     */
    pageSizeChange(val) {
      this.pageInfo.pageSize = val
      this.pageInfo.currentPage = 1
      this.$emit('pageChange', this.pageInfo)
    },
    /**
     * @author : 沈博
     * @date   : 2022/3/4 9:34
     * @desc   : currentPage改变事件
     */
    currentPageChange(val) {
      this.pageInfo.currentPage = val
      if (!this.pageInfo.pageSize) {
        this.pageInfo.pageSize = this.pageSize
      }
      this.$emit('pageChange', this.pageInfo)
    },
    /**
     * @author : 沈博
     * @date   : 2022/3/4 9:17
     * @desc   : 鼠标范围选择内的行数发生变化时会触发的事件
     */
    selectRangeChange({records, reserves, $event}) {
      this.batchKeys = []
      this.batchRows = []
      for (let it of records) {
        this.selectChange({checked: true, row: it})
      }
    },
    /**
     * @desc   : 全选
     * @author : 周兴
     * @date   : 2023/2/23 15:27
     */
    checkAll() {
      this.batchKeys = []
      this.batchRows = []
      this.dataFinal.forEach(it => {
        this.batchKeys.push(it[this.primaryKey])
        this.batchRows.push(it);
      })
      this.setCheckboxRowByKeys(this.batchKeys);
    },
    /**
     * @desc   : 数据全选/全不选
     * @author : 周兴
     * @date   : 2022/3/3 18:08
     */
    selectAll({checked}) {
      if (checked) {
        // 循环赋值
        this.dataFinal.forEach(it => {
          this.selectChange({checked: true, row: it, allFlag: true})
        })
      } else {
        // this.batchKeys = []
        // this.batchRows = []
        // this.$emit('select-change', [])
        this.dataFinal.forEach(it => {
          this.selectChange({checked: false, row: it, allFlag: true})
        })
      }
      this.$emit('select-all', checked)
    },
    /**
     * @desc   : 单选框的选择事件
     * @author : 周兴
     * @date   : 2022/3/10 15:03
     */
    radioSelectChange({checked, row, newValue, oldValue, column}) {
      if (!this.chooseFlag) {
        return
      }
      // this.$emit('emit-new-old', {newValue: newValue, oldValue: oldValue})
      // //判断是否有raido
      // let hasRadio = false
      // for (let it of this.$slots.default) {
      //   if (it && it.componentInstance && it.componentInstance.type && it.componentInstance.type === 'radio') {
      //     hasRadio = true
      //     break
      //   }
      // }
      //说明是单选
      if (!this.multiple && this.chooseFlag) {
        this.key = row[this.primaryKey]
        this.$refs[this.name].setCurrentRow(row);
        // 只有点击单选框才会进行行切换
        if (column.type == 'radio') {
          this.currentChangeEvent({row})
          this.$refs[this.name].toggleCheckboxRow(row);
        }
        this.selectChange({checked, row, cellClick: true});
        // this.$emit('radio-change', checked, row)
        this.$emit('radio-change', {checked, row, newValue, oldValue, column})
      }
    },
    /**
     *   @desc   : 当时modalSelect组件引用时控制radio可选范围
     *   @date   : 2022/5/27 9:32
     *   @author : 寇珊珊
     */
    checkRadioMethod({row}) {
      if (this.treeFlag && this.childDisableFlag) {
        return !(row.parentId);
      } else {
        return true;
      }
    },
    /**
     * @desc   : 获取勾选的数据
     * @author : 周兴
     * @date   : 2022/6/13 16:19
     */
    getCheckRows() {
      return this.$refs.table.getCheckboxRecords();
    },
    /**
     * @desc   : 数据选择
     * @author : 周兴
     * @date   : 2022/3/3 18:17
     */
    selectChange({checked, row, allFlag, cellClick}) {
      //不能点击checkbox
      if (!this.checkDisable) {
        this.$refs[this.name].setCheckboxRow(row, !checked)
        return
      }
      //单选要特殊处理
      if (this.key) {
        // 子级不需要选中
        if (this.treeFlag && row['parentId'] && this.childDisableFlag) {
          this.key = null;
          this.batchRows = [];
          this.batchKeys = [];
          this.$refs[this.name].clearRadioRow();
        } else {
          this.batchKeys = []
          this.batchRows = []
          checked = true
        }
      } else {
        if (!this.multiple && this.chooseFlag) {
          this.batchKeys = []
          this.batchRows = []
          checked = true
        }
      }
      if (checked) {
        // 不存在才插入
        if (row && (this.batchKeys.length == 0 || this.batchKeys.indexOf(row[this.primaryKey]) < 0)) {
          this.batchKeys.push(row[this.primaryKey])
          this.batchRows.push(row)
        }
      } else {
        // 删除掉去掉的勾选
        this.batchKeys.splice(this.batchKeys.indexOf(row[this.primaryKey]), 1)
        // this.batchRows.splice(this.batchRows.indexOf(row), 1)
        this.batchRows = this.batchRows.filter(it => it[this.primaryKey] != row[this.primaryKey])
      }
      if (!cellClick && !allFlag) {
        //切换时也需要把当前行移过来
        this.$refs[this.name].setCurrentRow(row);
        this.currentChangeEvent({row})
      }
      this.$emit('select-change', {batchRows: this.batchRows, row, checked, allFlag})
    },
    /**
     * @desc   : 格点击事件
     * @author : 沈博
     * @date   : 2022/3/7 9:35
     */
    cellClick({row, column}) {
      if (column.type === 'seq' && this.chooseDataFlag) {
        return;
      }
      let self = this;
      self.$emit('cell-click', {row, column})
      if (!this.chooseFlag) return;
      // 开启延时器，300ms的间隔区分单击和双击，解决双击时执行两次单击事件
      clearTimeout(self.time)
      self.time = setTimeout(() => {
        if (!column.property && column.type === 'checkbox') {
          return
        }
        if (!column.property && column.type === 'radio') {
          return
        }
        if (column.type === 'switch') {
          return
        }
        //如果false，那么就默认不勾选checkbox
        if (!this.chooseCheckFlag || !this.checkDisable) {
          return
        }
        //(序号、或者单选、或者设置linkClickChecked为true)才能进行联动点击
        if (column.type === 'seq' || this.key || this.linkClickChecked) {
          // 如果该列是树形节点那么就不允许点击，子级也不允许点击
          if (this.treeFlag && (column.treeNode || row['parentId'])) {
            return;
          }
          //行点击添加checkbox
          let flag = !this.batchKeys.includes(row[this.primaryKey])
          if (!this.key) {
            this.$refs[this.name].setCheckboxRow(row, flag)
          }
          this.selectChange({checked: flag, row: row, cellClick: true})
        }
      }, 300)
    },
    /**
     * @desc   : 当前行变化
     * @author : 周兴
     * @date   : 2022/3/7 10:57
     */
    currentChangeEvent(e) {
      // 如果没有勾选框，那么需要把当前行插入bachKeys
      if (!this.chooseFlag && e && e.row) {
        this.batchRows = []
        this.batchKeys = []
        this.batchRows.push({...e.row})
        this.batchKeys.push(e.row[this.primaryKey])
      }
      this.$emit('current-change', e)
      // 给当前行增加hover
      this.addHover(e.rowIndex);
    },
    /**
     * @desc   : 滚动就隐藏pop
     * @author : 周兴
     * @date   : 2022/4/19 9:21
     */
    handleScroll(e) {
      //只有人为滚动时才处理
      this.$refs[this.name].$el.click() //关闭表头的pop
      this.$emit('scroll', e)
    },
    /**
     * @desc   : 根据类型给属性赋值
     * @author : 周兴
     * @date   : 2022/3/16 18:12
     */
    setMagnifierProperty() {
      // 商品档案
      if (this.dataType === this.$config.tableSelectType.goods) {
        this.service = this.$service.commonService
        this.methodsName = 'getGoodsChild' //非组合的都在一起返回，只有组合的需要单独查询
      }
    },
    /**
     * @desc   : 重写提示信息
     * @author : 周兴
     * @date   : 2023/5/25 15:33
     */
    loadTipContentMethod({type, column, row, items, _columnIndex}) {
      // console.log('343',type, row, column.property)
      // // 重写默认的提示内容
      // // if (type === 'header') {
      // //   return '自定义标题提示内容：' + column.title
      // // } else if (type === 'footer') {
      // //   return '自定义表尾提示内容：' + items[_columnIndex]
      // // }
      // if (column.property === 'flgValid') {
      //   console.log(row[column.property] ? '是':'否')
      //   return row[column.property] ? '是':'否'
      // }
    },
    /**
     * @desc   : 懒加载
     * @author : 周兴
     * @date   : 2022/5/26 11:43
     */
    loadChildrenMethod({row}) {
      return new Promise(resolve => {
        // let children = typeof this.children === 'function'?this.children():this.children;
        let children = row['bomItems']
        //如果有值直接显示(用于已选列表展开子级)
        if (children && children.length > 0) {
          // 过滤找到属于自己的子级数据
          resolve(children)
        } else {
          // 没有值进行查询
          let param = {}
          param.cpId = this.$store.state.user.cpId
          if (this.primarySearchKey) {
            param[this.primarySearchKey] = row[this.primarySearchKey]
          } else {
            if (this.primaryKey && row && row[this.primaryKey]) {
              // 根据传入的数据进行检索
              param[this.primaryKey] = row[this.primaryKey]
            }
          }
          // 商品还需要传递类型进行查询
          if (this.dataType === this.$config.tableSelectType.goods) {
            // 查询组合促销
            if (row[this.combinedField]) {
              param[this.combinedField] = [row[this.combinedField]]
              param['searchType'] = 1;  // 查询
              if (this.otherSearchParam) {
                // 拼接参数条件实体
                this.objectMerge(param, this.otherSearchParam)
              }
              this.methodsName = 'getCombinedSkuById'
            }
          }
          this.excute(this.service, this.service[this.methodsName], param).then(res => {
            if (res.code === 200) {
              let childs = res.data.list;
              // //从父级分摊到明细
              childs = this.shareFromParentData(row, childs)
              row.children = childs;
              this.$emit('load-children', childs, row)
              resolve(childs)
            } else {
              this.$Message.warning(res.message)
            }
          })
        }
      })
    },
    /**
     * @desc   : 分摊到子级
     * @author : 周兴
     * @date   : 2022/5/26 17:06
     */
    shareFromParentData(row, child) {
      //展开子级，从父级分摊
      if (row && child) {
        child.forEach(it => {
          it.parentId = row['id']
        })
      }
      return child;
    },
    /**
     * @desc   : 删除一行
     * @author : 周兴
     * @date   : 2022/12/16 15:47
     */
    delRow(rowIndex) {
      this.$emit('delRow', rowIndex)
    },
    /**
     * @desc   : 选择数据
     * @author : 周兴
     * @date   : 2023/2/19 18:58
     */
    chooseData(row, rowIndex) {
      this.$emit('chooseData', row, rowIndex);
    },
    /**
     * @desc   : 全屏
     * @author : 周兴
     * @date   : 2023/12/21 16:37
     */
    handleMax() {
      const tableColumns = this.$refs[this.name].getTableColumn()
      if (tableColumns && tableColumns.visibleColumn) {
        let columnsFull = tableColumns.visibleColumn.filter(it => it.type != 'seq'
          && it.type != 'checkbox' && it.type != 'radio')
          .map(it => {
            let align = 'left';
            if (it.params && it.params.align) {
              align = it.params.align;
            } else {
              let type = it.params?.type;
              if (type === 'date' || type === 'switch' || type === 'checkbox' || it.params?.centerFlag) {
                align = 'center';
              } else if (type === 'number' || it.params?.dataType === 'number') {
                align = 'right';
              }
            }
            // console.log('444', this.$slots.default, this.$parent,this.getParent(this))
            let obj = {
              field: it.field,
              title: it.title,
              type: it.params?.type,
              dataType: it.params?.dataType,
              digits: it.params?.digits,
              align: align,
              instance: this.getParent(this),
              col: this.$slots.default.filter(item => item.componentInstance?.field === it.field)
            }
            return obj;
          });
        this.$TableMax({columns: columnsFull, tableData: this.dataFinal},
          {
            // ok: (searchText) => {
            //   this.handleColPosition(searchText);   // 执行列定位方法
            // },
          })
      }
    },
    /**
     * @desc   : 获取父级页面
     * @author : 周兴
     * @date   : 2023/12/22 14:05
     */
    getParent(obj) {
      if (obj.$parent && obj.$parent.$el.className === 'main-div') {
        return obj.$parent;
      } else {
        return this.getParent(obj.$parent);
      }
    },
    /**
     * @desc   : 改变设置的位置
     * @author : 周兴
     * @date   : 2023/1/29 16:55
     */
    changeSettingLocation() {
      let self = this;
      setTimeout(() => {
        self.settingLeft = self.$refs[self.name] ? (self.$refs[self.name].$el.offsetWidth + self.$refs[self.name].$el.offsetLeft - 26) + 'px' : 0// 设置图标居左的位置
        self.settingTop = self.$refs[self.name] ? (self.$refs[self.name].$el.offsetTop + 1) + 'px' : 0;           // 设置图标居上的位置
      }, 100)
    },
  },
  beforeDestroy() {
    // 销毁
    window.removeEventListener('resize', this.changeSettingLocation)
    window.removeEventListener('scroll', this.hideAllPop)
    this.existsFlag = null;
  },
  mounted() {
    let self = this;
    //监听窗口变化
    window.addEventListener('resize', self.changeSettingLocation)
    setTimeout(() => {
      self.changeSettingLocation();
    }, 1000)
    // 监听滚动
    window.addEventListener('scroll', self.hideAllPop)
    if (this.dataFinal && this.dataFinal.length > 0) {
      // 自适应列宽
      this.$nextTick(() => {
        this.autoWidthHandle();
      })
    }
  },
  created() {
    if (!this.checkDisable) {
      this.checkRange = false
    }
    // 记录原始数据
    this.dataFinal = this.data
    this.dataSocial = this.data?.copy();
    // 如果树形开启那么赋值查询子级节点
    if (this.treeFlag) {
      this.setMagnifierProperty();
    }
    this.loadingData = this.loading;
    // 如果有导出路径才会有导出功能
    // if (this.exportUrl) {
    //   this.header.options[0].push({code: 'export', name: '导出', disabled: false})
    // }
  }
}
</script>
<style scoped>


/deep/ .vxe-header--row .vxe-cell {
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  /*border-left: 1px solid #dcdee2;*/
}


/deep/ .vxe-footer--row .vxe-cell {
  justify-content: left !important;
}


.filter-button {
  border: 1px solid #dcdee2;
  background-color: white;
  cursor: pointer;
  /*width: 60px;*/
  color: #515a6e;
  margin-left: 10px;
}

/deep/ .ivu-btn {
  display: flex;
  align-items: center;
  height: 24px !important;
  line-height: 24px !important;
  margin: 2px 2px;
}

/deep/ .ivu-btn:hover {
  color: #fff;
  background: #2E406B;
  border: #2E406B;
}

.setting-class {
  position: absolute;
  z-index: 300;
  width: 25px;
  height: 28px;
  background: rgba(245, 250, 255, 1);
  justify-content: center;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.choose-all-class {
  width: 100%;
  height: 30px;
  position: absolute;
  z-index: 10;
  display: flex;
}

/deep/ .vxe-button > .vxe-cell {
  padding: 0 !important;
}

.menu-class {
  position: absolute;
  top: 50%;
  left: 50%;
  border: 1px solid #aaa;
  box-shadow: 2px 2px 2px #888888;
}

/deep/ .ivu-dropdown-menu {
  width: 100%;
}

/deep/ .ivu-dropdown {
  width: 100%;
}

/deep/ .ivu-select-selection {
  display: flex;
  align-items: center;
}


/*table-header（无内容部分）背景色*/
/deep/ .vxe-table--render-default.border--full .vxe-table--header-wrapper {
  background: rgba(245, 250, 255, 1);
}

/*合计行（无内容部分）背景色*/
/deep/ .vxe-table--render-default .vxe-table--footer-wrapper {
  background: rgba(255, 248, 225, 1);
  border: unset;
}


/*滚动条样式*/
.dk-table-scrollbar ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

/*滚动条的轨道*/
.dk-table-scrollbar ::-webkit-scrollbar-track {
  /*background-color:  rgba(233, 240, 254, 1);*/
  background-color: #FFFFFF;
  border: unset;
}

/*滚动条里面的小方块，能向上向下移动*/
.dk-table-scrollbar ::-webkit-scrollbar-thumb {
  background-color: #bfbfbf;
  border-radius: 5px;
  border: 1px solid #F1F1F1;
  box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
}

.dk-table-scrollbar ::-webkit-scrollbar-thumb:hover {
  background-color: #A8A8A8;
}

.dk-table-scrollbar ::-webkit-scrollbar-thumb:active {
  background-color: #787878;
}

/*边角，即两个滚动条的交汇处*/
.dk-table-scrollbar ::-webkit-scrollbar-corner {
  background-color: #FFFFFF;
}

/*去掉table底部border*/
/deep/ .vxe-table--border-line {
  border-width: 0;
}

</style>
