<template>
  <div id="DgTable">
    <!-- 表格含有输入框，因此增加表单校验 -->
    <el-form ref="tableRuleFrom" :model="tableRuleFrom" :rules="rules" style="height: 100%" @submit.native.prevent>
      <!-- 表格头部工具 -->
      <!-- <el-form :inline="true" label-width="100px" v-if="titleItems"  style="float: left">
        <template v-for="(item, index) in titleItems">
          <div v-if="item.editer === 'text'" v-html="item.title" :style="item.style"></div>
        </template>
      </el-form> -->
      <!-- <el-form :inline="true" label-width="100px" v-if="toolbarItems" class="toolbar-form clearfix" ref="toolbarForm"> -->
      <el-form
        v-if="toolbarItems"
        ref="toolbarForm"
        :inline="true"
        label-width="100px"
        class="toolbar-form"
        @submit.native.prevent
      >
        <div v-for="(item, index) in titleItems" :key="'toolbar-' + index" class="toolbar-title">
          <div v-if="item.editer === 'text'" :style="item.style" v-html="item.title"></div>
        </div>
        <template v-for="(item, index) in firstToolbarItems">
          <el-form-item
            :key="'firstToolbar' + index + '_' + item.value"
            :style="item.formItemStyle"
            :class="item.editer === 'add' || item.editer === 'down' ? 'add-formItem-class' : ''"
          >
            <el-autocomplete
              v-if="item.editer === 'autocomplete'"
              v-model="toolbarData[item.value]"
              :size="item.size || 'mini'"
              :style="item.style"
              :placeholder="item.placeholder || '请输入'"
              :disabled="item.disabled"
              :clearable="item.clearable || true"
              popper-class="dg-ac-select"
              :fetch-suggestions="
                (queryString, cb) => {
                  autoQuerySearch(queryString, cb, item)
                }
              "
              @select="
                (selItem) => {
                  autoHandleSelect(selItem, item)
                }
              "
            >
              <template slot-scope="{ item }">
                <div>
                  {{ item.title }}<span class="el-autocomplete-option-tip">{{ item.value }}</span>
                </div>
              </template>
            </el-autocomplete>
            <div v-if="item.editer === 'text'" :style="item.style" v-html="item.title"></div>
            <el-date-picker
              v-if="item.editer === 'data' || item.editer === 'date'"
              v-model="toolbarData[item.value]"
              :style="item.style"
              align="right"
              type="date"
              :clearable="item.clearable || true"
              :value-format="item.valueFormat"
              :placeholder="item.placeholder"
              :picker-options="item.pickerOptions"
            >
            </el-date-picker>
            <!-- 日期选择框 -->
            <el-date-picker
              v-if="item.editer === 'datePicker'"
              :key="index"
              v-model="toolbarData[item.value]"
              :label="item.label"
              :prop="item.value"
              :size="item.size || 'mini'"
              :style="item.style"
              :type="item.type || 'date'"
              :disabled="item.disabled"
              :format="item.format || 'yyyy-MM-dd'"
              :clearable="item.clearable || true"
              :value-format="item.valueFormat || 'yyyy-MM-dd'"
              :picker-options="item.pickerOptions"
              :placeholder="item.placeholder || '选择日期'"
              :range-separator="item.rangeSeparator || '至'"
              :default-time="item.defaultTime || ['00:00:00', '23:59:59']"
              :start-placeholder="item.startPlaceholder || '开始日期'"
              :end-placeholder="item.endPlaceholder || '结束日期'"
              @change="handleEvent(item)"
            >
            </el-date-picker>
            <!-- 日期范围选择框 -->
            <el-date-picker
              v-if="item.editer === 'daterange'"
              v-model="toolbarData[item.value]"
              :style="item.style"
              align="right"
              type="daterange"
              :clearable="item.clearable || true"
              :value-format="item.valueFormat"
              range-separator="至"
              :start-placeholder="item.startPlaceholder || '开始日期'"
              :end-placeholder="item.endPlaceholder || '结束日期'"
            >
            </el-date-picker>
            <el-input
              v-if="item.editer === 'input'"
              v-model="toolbarData[item.value]"
              :disabled="item.disabled"
              :style="item.style"
              size="mini"
              :placeholder="item.placeholder"
              @keyup.enter.native="clickHandle(item, initialData, toolbarData)"
            >
              <template v-if="item.prependVal" slot="prepend"
                ><span v-if="item.prependVal">{{ item.prependVal }}</span></template
              >
              <template v-if="item.appendVal" slot="append"
                ><span v-if="item.appendVal">{{ item.appendVal }}</span></template
              >
              <el-button
                v-if="item.appendIcon"
                slot="append"
                :icon="item.appendIcon"
                @click.native="clickHandle(item, initialData, toolbarData)"
              ></el-button>
            </el-input>
            <dg-select
              v-if="item.editer === 'select'"
              v-model="toolbarData[item.value]"
              :collapse-tags="item.collapseTags"
              :disabled="item.disabled"
              :style="item.style"
              :placeholder="item.placeholder"
              :multiple="item.multiple"
              :dim-code="item.dimCode"
              :code-type="item.codeType"
              :api-code="item.apiCode"
              :file-type="item.fileType"
              :filter-val="item.filterVal"
              :filter-limit="item.filterLimit"
              :select-options="item.selectOptions"
              :select-str="item.selectStr"
              :clearable="item.clearable === false ? false : true"
              :query-terms="item.queryTerms"
              :default-val="item.defaultVal || false"
              @change="handleEvent(arguments, item)"
            ></dg-select>
            <el-cascader
              v-if="item.editer === 'cascader'"
              v-model="toolbarData[item.value]"
              :disabled="item.disabled"
              :style="item.style"
              :placeholder="item.placeholder"
              :options="item.options"
              :props="{ expandTrigger: 'hover', checkStrictly: true, emitPath: false }"
              clearable
              filterable
              :show-all-levels="false"
              :size="item.size || 'mini'"
              @change="handleEvent(arguments, item)"
            ></el-cascader>
            <el-button
              v-if="item.editer === 'search'"
              v-monitor="item.monitor && { click: { ...item.monitor.click, params: toolbarData } }"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type || 'info'"
              :size="item.size || 'mini'"
              :plain="item.plain === false ? false : true"
              :round="item.round"
              :circle="item.circle"
              :icon="item.icon || 'el-icon-search'"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              >{{ item.title || '查询' }}
            </el-button>
            <el-button
              v-if="item.editer === 'add'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type || 'primary'"
              :size="item.size || 'mini'"
              :icon="item.icon || 'el-icon-plus'"
              :plain="item.plain === false ? false : true"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              >{{ item.title || '新增' }}
            </el-button>
            <el-button
              v-if="item.editer === 'down'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type || 'primary'"
              :size="item.size || 'mini'"
              :plain="item.plain === false ? false : true"
              :round="item.round"
              :circle="item.circle"
              :icon="item.icon || 'el-icon-download'"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              >{{ item.title || '下载' }}
            </el-button>
            <el-button
              v-if="item.editer === 'del' && item.position !== 'bottom'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type"
              size="mini"
              icon="el-icon-delete"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              ><span v-if="item.title">{{ item.title }}</span>
            </el-button>
            <el-button
              v-if="item.editer === 'draweradd'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type"
              size="mini"
              icon="el-icon-plus"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              ><span v-if="item.title">{{ item.title }}</span>
            </el-button>
            <el-button
              v-if="item.editer === 'button' && item.position != 'bottom'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type || 'primary'"
              :icon="item.icon"
              size="mini"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              ><span v-if="item.title">{{ item.title }}</span>
            </el-button>
            <el-button
              v-if="item.editer === 'moreBtn' && !isMore"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              type="text"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              icon="el-icon-arrow-down"
              @click="changeIsMore"
              >高级搜索
            </el-button>
            <el-button
              v-if="item.editer === 'moreBtn' && isMore"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              type="text"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              icon="el-icon-arrow-up"
              @click="changeIsMore"
              >普通搜索
            </el-button>
            <el-dropdown
              v-if="item.editer === 'dropdown'"
              :style="item.style"
              @command="
                (val) => {
                  selectDropdow(val, item)
                }
              "
            >
              <el-button
                :com-auth="item.comAuth || ''"
                :type="item.type"
                size="mini"
                :icon="item.icon"
                :plain="item.plain"
                :round="item.round"
                :circle="item.circle"
                :disabled="item.disabled"
              >
                {{ item.title }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <template v-for="(list, index) in item.dropdownMenu">
                  <el-dropdown-item :key="'dropdown-' + index" :com-auth="list.comAuth || ''" :command="list.value">{{
                    list.name
                  }}</el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </template>
        <el-form-item v-if="colSet" style="float: right"
          ><el-button size="mini" type="primary" title="设置" icon="el-icon-setting" @click="setup"></el-button
        ></el-form-item>
        <template v-for="(item, index) in thirdToolbarItems">
          <el-form-item
            v-if="!item.judge || item.judge()"
            :key="'thirdToolbar' + index + JSON.stringify(item)"
            :style="item.formItemStyle"
            :class="item.editer === 'add' || item.editer === 'down' ? 'add-formItem-class' : ''"
          >
            <!-- <el-button :title="item.tooltip" v-if="item.editer === 'add'" :style="item.style" :type="item.type" size="mini" icon="el-icon-plus" :plain="item.plain" :round="item.round" :circle="item.circle"
                      @click="clickHandle(item, initialData, toolbarData)" :disabled="item.disabled"><span v-if="item.title">{{item.title}}</span>
            </el-button> -->
            <el-button
              v-if="item.editer === 'add'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type || 'primary'"
              :size="item.size || 'mini'"
              :icon="item.icon || 'el-icon-plus'"
              :plain="item.plain === false ? false : true"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              >{{ item.title || '新增' }}
            </el-button>
            <el-button
              v-if="item.editer === 'down'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type || 'primary'"
              :size="item.size || 'mini'"
              :plain="item.plain === false ? false : true"
              :round="item.round"
              :circle="item.circle"
              :icon="item.icon || 'el-icon-download'"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              >{{ item.title || '下载' }}
            </el-button>
            <el-button
              v-if="item.editer === 'del' && item.position !== 'bottom'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type"
              size="mini"
              icon="el-icon-delete"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              ><span v-if="item.title">{{ item.title }}</span>
            </el-button>
            <el-button
              v-if="item.editer === 'draweradd'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type"
              size="mini"
              icon="el-icon-plus"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              ><span v-if="item.title">{{ item.title }}</span>
            </el-button>
            <el-button
              v-if="item.editer === 'button' && item.position != 'bottom'"
              v-monitor="item.monitor"
              :com-auth="item.comAuth || ''"
              :title="item.tooltip"
              :style="item.style"
              :type="item.type || 'primary'"
              :icon="item.icon"
              size="mini"
              :plain="item.plain"
              :round="item.round"
              :circle="item.circle"
              :disabled="item.disabled"
              @click="clickHandle(item, initialData, toolbarData)"
              ><span v-if="item.title">{{ item.title }}</span>
            </el-button>
            <el-dropdown
              v-if="item.editer === 'dropdown'"
              :style="item.style"
              @command="
                (val) => {
                  selectDropdow(val, item)
                }
              "
            >
              <el-button
                :com-auth="item.comAuth || ''"
                :type="item.type"
                size="mini"
                :icon="item.icon"
                :plain="item.plain"
                :round="item.round"
                :circle="item.circle"
                :disabled="item.disabled"
              >
                {{ item.title }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <template v-for="(list, index) in item.dropdownMenu">
                  <el-dropdown-item :key="'dropdown-' + index" :com-auth="list.comAuth || ''" :command="list.value">{{
                    list.name
                  }}</el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </el-dropdown>
            <!-- 输入框 -->
            <el-input
              v-if="item.editer === 'input'"
              v-model="toolbarData[item.value]"
              :disabled="item.disabled"
              :style="item.style"
              size="mini"
              :placeholder="item.placeholder"
              @keyup.enter.native="clickHandle(item, initialData, toolbarData)"
            >
              <template v-if="item.prependVal" slot="prepend"
                ><span v-if="item.prependVal">{{ item.prependVal }}</span></template
              >
              <template v-if="item.appendVal" slot="append"
                ><span v-if="item.appendVal">{{ item.appendVal }}</span></template
              >
              <el-button
                v-if="item.appendIcon"
                slot="append"
                :icon="item.appendIcon"
                @click.native="clickHandle(item, initialData, toolbarData)"
              ></el-button>
            </el-input>
          </el-form-item>
        </template>
        <div v-show="isMore" class="secondToolbar">
          <template v-for="(item, index) in secondToolbarItems">
            <el-form-item
              :key="'secondToolbar' + index + '_' + item.value"
              :style="item.formItemStyle"
              :class="item.editer === 'add' || item.editer === 'down' ? 'add-formItem-class' : ''"
            >
              <div v-if="item.editer === 'text'" :style="item.style" v-html="item.title"></div>
              <!-- 需要添加其他类型输入框，可添加在这个template中控制显示隐藏 -->
              <template v-if="toolbarOptionsVal.some((val) => val === item.value)">
                <!-- 远程搜索框 -->
                <el-autocomplete
                  v-if="item.editer === 'autocomplete' && toolbarOptionsVal.some((val) => val === item.value)"
                  v-model="toolbarData[item.value]"
                  :size="item.size || 'mini'"
                  :style="item.style"
                  :placeholder="item.placeholder || '请输入'"
                  :disabled="item.disabled"
                  :clearable="item.clearable || true"
                  popper-class="dg-ac-select"
                  :fetch-suggestions="
                    (queryString, cb) => {
                      autoQuerySearch(queryString, cb, item)
                    }
                  "
                  @select="
                    (selItem) => {
                      autoHandleSelect(selItem, item)
                    }
                  "
                >
                  <template slot-scope="{ item }">
                    <div>
                      {{ item.title }}<span class="el-autocomplete-option-tip">{{ item.value }}</span>
                    </div>
                  </template>
                </el-autocomplete>
                <!-- 日期框 -->
                <el-date-picker
                  v-if="item.editer === 'data' || item.editer === 'date'"
                  v-model="toolbarData[item.value]"
                  :style="item.style"
                  align="right"
                  type="date"
                  :clearable="item.clearable || true"
                  :value-format="item.valueFormat"
                  :placeholder="item.placeholder"
                  :picker-options="item.pickerOptions"
                >
                </el-date-picker>
                <!-- 日期范围选择框 -->
                <el-date-picker
                  v-if="item.editer === 'daterange'"
                  v-model="toolbarData[item.value]"
                  :style="item.style"
                  align="right"
                  type="daterange"
                  :clearable="item.clearable || true"
                  :value-format="item.valueFormat"
                  range-separator="至"
                  :default-time="item.defaultTime || ['00:00:00', '23:59:59']"
                  :start-placeholder="item.startPlaceholder || '开始日期'"
                  :end-placeholder="item.endPlaceholder || '结束日期'"
                >
                </el-date-picker>
                <!-- 日期选择框 -->
                <el-date-picker
                  v-if="item.editer === 'datePicker'"
                  :key="index"
                  v-model="toolbarData[item.value]"
                  :label="item.label"
                  :prop="item.value"
                  :size="item.size || 'mini'"
                  :style="item.style"
                  :type="item.type || 'date'"
                  :disabled="item.disabled"
                  :format="item.format || 'yyyy-MM-dd'"
                  :clearable="item.clearable || true"
                  :value-format="item.valueFormat || 'yyyy-MM-dd'"
                  :picker-options="item.pickerOptions"
                  :placeholder="item.placeholder || '选择日期'"
                  :range-separator="item.rangeSeparator || '至'"
                  :default-time="item.defaultTime || ['00:00:00', '23:59:59']"
                  :start-placeholder="item.startPlaceholder || '开始日期'"
                  :end-placeholder="item.endPlaceholder || '结束日期'"
                  @change="handleEvent(item)"
                >
                </el-date-picker>
                <!-- 输入框 -->
                <!-- <el-input v-if="item.editer === 'input'" :disabled="item.disabled" :style="item.style" v-model="toolbarData[item.value]" size="mini"
                          :placeholder="item.placeholder"
                          @keyup.enter.native="clickHandle(item, initialData, toolbarData)"></el-input> -->
                <el-input
                  v-if="item.editer === 'input'"
                  v-model="toolbarData[item.value]"
                  :disabled="item.disabled"
                  :style="item.style"
                  size="mini"
                  :placeholder="item.placeholder"
                  @keyup.enter.native="clickHandle(item, initialData, toolbarData)"
                >
                  <template v-if="item.prependVal" slot="prepend"
                    ><span v-if="item.prependVal">{{ item.prependVal }}</span></template
                  >
                  <template v-if="item.appendVal" slot="append"
                    ><span v-if="item.appendVal">{{ item.appendVal }}</span></template
                  >
                  <el-button
                    v-if="item.appendIcon"
                    slot="append"
                    :icon="item.appendIcon"
                    @click.native="clickHandle(item, initialData, toolbarData)"
                  ></el-button>
                </el-input>
                <!-- 下拉选择框 -->
                <dg-select
                  v-if="item.editer === 'select'"
                  v-model="toolbarData[item.value]"
                  :collapse-tags="item.collapseTags"
                  :disabled="item.disabled"
                  :style="item.style"
                  :placeholder="item.placeholder"
                  :multiple="item.multiple"
                  :dim-code="item.dimCode"
                  :code-type="item.codeType"
                  :api-code="item.apiCode"
                  :file-type="item.fileType"
                  :filter-val="item.filterVal"
                  :filter-limit="item.filterLimit"
                  :select-options="item.selectOptions"
                  :select-str="item.selectStr"
                  :query-terms="item.queryTerms"
                  :clearable="item.clearable || true"
                  :default="item.default"
                  :default-val="item.defaultVal || false"
                  @change="handleEvent(arguments, item)"
                ></dg-select>
              </template>
              <!-- <el-button :title="item.tooltip" v-if="item.editer === 'search'" :style="item.style" :type="item.type" size="mini" :plain="item.plain" :round="item.round" :circle="item.circle"
                        icon="el-icon-search" @click="clickHandle(item, initialData, toolbarData)" :disabled="item.disabled"><span v-if="item.title">{{item.title}}</span>
              </el-button>
              <el-button :title="item.tooltip" v-if="item.editer === 'add'" :style="item.style" :type="item.type" size="mini" icon="el-icon-plus" :plain="item.plain" :round="item.round" :circle="item.circle"
                        @click="clickHandle(item, initialData, toolbarData)" :disabled="item.disabled"><span v-if="item.title">{{item.title || '新增'}}</span>
              </el-button> -->
              <el-button
                v-if="item.editer === 'search'"
                v-monitor="item.monitor && { click: { ...item.monitor.click, params: toolbarData } }"
                :com-auth="item.comAuth || ''"
                :title="item.tooltip"
                :style="item.style"
                :type="item.type || 'info'"
                :size="item.size || 'mini'"
                :plain="item.plain === false ? false : true"
                :round="item.round"
                :circle="item.circle"
                :icon="item.icon || 'el-icon-search'"
                :disabled="item.disabled"
                @click="clickHandle(item, initialData, toolbarData)"
                >{{ item.title || '查询' }}
              </el-button>
              <el-button
                v-if="item.editer === 'add'"
                v-monitor="item.monitor"
                :com-auth="item.comAuth || ''"
                :title="item.tooltip"
                :style="item.style"
                :type="item.type || 'primary'"
                :size="item.size || 'mini'"
                :icon="item.icon || 'el-icon-plus'"
                :plain="item.plain === false ? false : true"
                :round="item.round"
                :circle="item.circle"
                :disabled="item.disabled"
                @click="clickHandle(item, initialData, toolbarData)"
                >{{ item.title || '新增' }}
              </el-button>
              <el-button
                v-if="item.editer === 'down'"
                v-monitor="item.monitor"
                :com-auth="item.comAuth || ''"
                :title="item.tooltip"
                :style="item.style"
                :type="item.type || 'primary'"
                :size="item.size || 'mini'"
                :plain="item.plain === false ? false : true"
                :round="item.round"
                :circle="item.circle"
                :icon="item.icon || 'el-icon-download'"
                :disabled="item.disabled"
                @click="clickHandle(item, initialData, toolbarData)"
                >{{ item.title || '下载' }}
              </el-button>
              <el-button
                v-if="item.editer === 'del' && item.position !== 'bottom'"
                v-monitor="item.monitor"
                :com-auth="item.comAuth || ''"
                :title="item.tooltip"
                :style="item.style"
                :type="item.type"
                size="mini"
                icon="el-icon-delete"
                :plain="item.plain"
                :round="item.round"
                :circle="item.circle"
                :disabled="item.disabled"
                @click="clickHandle(item, initialData, toolbarData)"
                ><span v-if="item.title">{{ item.title }}</span>
              </el-button>
              <el-button
                v-if="item.editer === 'draweradd'"
                v-monitor="item.monitor"
                :com-auth="item.comAuth || ''"
                :title="item.tooltip"
                :style="item.style"
                :type="item.type"
                size="mini"
                icon="el-icon-plus"
                :plain="item.plain"
                :round="item.round"
                :circle="item.circle"
                :disabled="item.disabled"
                @click="clickHandle(item, initialData, toolbarData)"
                ><span v-if="item.title">{{ item.title }}</span>
              </el-button>
              <el-button
                v-if="item.editer === 'button' && item.position != 'bottom'"
                v-monitor="item.monitor"
                :com-auth="item.comAuth || ''"
                :title="item.tooltip"
                :style="item.style"
                :type="item.type || 'primary'"
                :icon="item.icon"
                size="mini"
                :plain="item.plain"
                :round="item.round"
                :circle="item.circle"
                :disabled="item.disabled"
                @click="clickHandle(item, initialData, toolbarData)"
                ><span v-if="item.title">{{ item.title }}</span>
              </el-button>
              <el-dropdown
                v-if="item.editer === 'dropdown'"
                :style="item.style"
                @command="
                  (val) => {
                    selectDropdow(val, item)
                  }
                "
              >
                <el-button
                  :com-auth="item.comAuth || ''"
                  :type="item.type"
                  size="mini"
                  :icon="item.icon"
                  :plain="item.plain"
                  :round="item.round"
                  :circle="item.circle"
                  :disabled="item.disabled"
                >
                  {{ item.title }}<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <template v-for="(list, index) in item.dropdownMenu">
                    <el-dropdown-item :key="'dropdown-' + index" :com-auth="list.comAuth || ''" :command="list.value">{{
                      list.name
                    }}</el-dropdown-item>
                  </template>
                </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
          </template>
        </div>
      </el-form>
      <!-- 表格本身 -->
      <el-table
        ref="DgTable"
        :row-key="rowKey"
        :data="tableRuleFrom.tableData"
        :cell-style="cellStyle"
        :highlight-current-row="highlightCurrentRow"
        :row-class-name="rowClassName"
        :border="border"
        size="small"
        style="width: 100%; border-top: 1px solid #f0f2f5"
        :height="getHeight"
        :stripe="stripe"
        @sort-change="tableSortChange"
        @selection-change="handleSelectionChange"
        @row-click="rowClick"
        @row-dblclick="rowDblclick"
        @cell-click="cellClick"
        @header-dragend="headerDragend"
      >
        <!-- <template v-for="(item, index) in tableItems"> -->
        <template v-for="(item, index) in sonTableItems">
          <el-table-column
            v-if="item.render || item.dimCode || item.apiCode"
            :key="index"
            :class-name="item.field ? 'allowDrop' : ''"
            :fixed="item.fixed"
            :sortable="item.sortable"
            :type="item.type"
            :label="item.title"
            :prop="item.field"
            :width="item.width"
            :show-overflow-tooltip="item.overflow || true"
            :align="item.align ? item.align : 'left'"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
          >
            <template slot-scope="scope">
              <span v-html="renderColContent(scope, item, index)"></span>
            </template>
          </el-table-column>
          <!-- 表格支持tooltip -->
          <el-table-column
            v-else-if="item.tooltip"
            :key="index + '_' + item.field"
            :fixed="item.fixed"
            :label="item.title"
            :width="item.width"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
          >
            <template slot-scope="scope">
              <el-tooltip
                :key="index"
                placement="top"
                effect="light"
                :content="
                  item.renderToolTip
                    ? item.renderToolTip(scope.row, item.renderPara) || scope.row[item.field]
                    : scope.row[item.field]
                "
              >
                <span>{{ scope.row[item.field] }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.actions || item.moreActions"
            :key="index + '_' + item.field"
            :fixed="item.fixed"
            :label="item.title"
            :width="item.width"
            :align="item.align ? item.align : 'left'"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
          >
            <template slot-scope="scope">
              <template v-for="(action, index) in item.actions">
                <el-dropdown
                  v-if="action.editer === 'dropdown'"
                  :key="index"
                  :split-button="action.splitButton || false"
                  size="mini"
                  :type="action.splitButton ? action.type : ''"
                  @click.native="rowAction(action, scope.row, scope.$index, $event)"
                  @command="
                    (val) => {
                      selectTableDropdow(val, action, scope.row)
                    }
                  "
                >
                  <template v-if="action.splitButton">{{
                    action.render ? action.render(scope.row, action.renderPara).title || action.title : action.title
                  }}</template>
                  <template v-else>
                    <el-button
                      v-if="!action.judge || action.judge(scope.row)"
                      :key="index"
                      v-monitor="action.monitor && { click: { ...action.monitor.click, params: scope.row } }"
                      :com-auth="action.comAuth || ''"
                      size="mini"
                      :disabled="action.disabled"
                      :icon="
                        action.render ? action.render(scope.row, action.renderPara).icon || action.icon : action.icon
                      "
                      :style="action.style"
                      :plain="action.plain"
                      :round="action.round"
                      :circle="action.circle"
                      :type="
                        action.render ? action.render(scope.row, action.renderPara).type || action.type : action.type
                      "
                    >
                      <span
                        v-if="
                          action.render
                            ? action.render(scope.row, action.renderPara).title || action.title
                            : action.title
                        "
                      >
                        {{
                          action.render
                            ? action.render(scope.row, action.renderPara).title || action.title
                            : action.title
                        }}<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                    </el-button>
                  </template>
                  <el-dropdown-menu slot="dropdown">
                    <template v-for="(dropItem, index) in action.moreActions">
                      <el-dropdown-item
                        v-if="!dropItem.judge || dropItem.judge(scope.row)"
                        :key="index"
                        :command="index"
                        :icon="dropItem.icon"
                        :disabled="dropItem.disabled"
                        >{{ dropItem.title }}</el-dropdown-item
                      >
                    </template>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-tooltip
                  v-else
                  :key="index"
                  :disabled="
                    action.render
                      ? action.render.tooltip || action.tooltip
                        ? false
                        : true
                      : action.tooltip
                      ? false
                      : true
                  "
                  effect="light"
                  :content="
                    action.render
                      ? action.render(scope.row, action.renderPara).tooltip || action.tooltip
                      : action.tooltip
                  "
                  placement="top"
                >
                  <el-button
                    v-if="!action.judge || action.judge(scope.row)"
                    :key="index"
                    v-monitor="action.monitor && { click: { ...action.monitor.click, params: scope.row } }"
                    :com-auth="action.comAuth || ''"
                    size="mini"
                    :disabled="
                      action.render
                        ? action.render(scope.row, action.renderPara).disabled || action.disabled
                        : action.disabled
                    "
                    :icon="
                      action.render ? action.render(scope.row, action.renderPara).icon || action.icon : action.icon
                    "
                    :style="
                      action.render ? action.render(scope.row, action.renderPara).style || action.style : action.style
                    "
                    :plain="action.plain"
                    :round="action.round"
                    :circle="action.circle"
                    :type="
                      action.render ? action.render(scope.row, action.renderPara).type || action.type : action.type
                    "
                    @click.native="rowAction(action, scope.row, scope.$index, $event)"
                  >
                    <span
                      v-if="
                        action.render ? action.render(scope.row, action.renderPara).title || action.title : action.title
                      "
                    >
                      {{
                        action.render ? action.render(scope.row, action.renderPara).title || action.title : action.title
                      }}
                    </span>
                  </el-button>
                </el-tooltip>
              </template>
              <template>
                <el-dropdown
                  v-if="
                    item.moreActions &&
                    item.moreActions.length &&
                    (!item.moreActionsJudge || item.moreActionsJudge(scope.row))
                  "
                  size="mini"
                  @command="
                    (val) => {
                      selectTableDropdow(val, item, scope.row)
                    }
                  "
                >
                  <span class="el-dropdown-link"> 更多操作<i class="el-icon-arrow-down el-icon--right"></i> </span>
                  <el-dropdown-menu slot="dropdown">
                    <template v-for="(dropItem, index) in item.moreActions">
                      <el-dropdown-item
                        v-if="!dropItem.judge || dropItem.judge(scope.row)"
                        :key="index"
                        :command="index"
                        :icon="dropItem.icon"
                        :disabled="dropItem.disabled"
                        >{{ dropItem.title }}</el-dropdown-item
                      >
                    </template>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </template>
          </el-table-column>
          <!-- 表格支持输入框 -->
          <el-table-column
            v-else-if="item.editer === 'input'"
            :key="index + '_' + item.field"
            :fixed="item.fixed"
            :sortable="item.sortable"
            :type="item.type"
            :label="item.title"
            :prop="item.field"
            :width="item.width"
            :show-overflow-tooltip="item.overflow || true"
            :align="item.align ? item.align : 'left'"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
          >
            <template slot-scope="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.' + item.field" :rules="rules[item.field]">
                <el-input
                  v-model="scope.row[item.field]"
                  size="mini"
                  :disabled="fieldDisabled(item, scope.row)"
                  :placeholder="item.placeholder"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 表格支持下拉框 -->
          <el-table-column
            v-else-if="item.editer === 'select'"
            :key="index + '_' + item.field"
            :fixed="item.fixed"
            :sortable="item.sortable"
            :type="item.type"
            :label="item.title"
            :prop="item.field"
            :width="item.width"
            :show-overflow-tooltip="item.overflow || true"
            :align="item.align ? item.align : 'left'"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
          >
            <template slot-scope="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.' + item.field" :rules="rules[item.field]">
                <dg-select
                  v-model="scope.row[item.field]"
                  size="mini"
                  :collapse-tags="item.collapseTags"
                  :placeholder="item.placeholder"
                  :disabled="fieldDisabled(item, scope.row)"
                  :multiple="item.multiple"
                  :dim-code="item.dimCode"
                  :api-code="item.apiCode"
                  :filter-val="item.filterVal"
                  :select-options="item.selectOptions"
                  :select-str="item.selectStr"
                  :clearable="item.clearable"
                ></dg-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 表格支持开关按钮 -->
          <el-table-column
            v-else-if="item.editer === 'switch'"
            :key="index + '_' + item.field"
            :fixed="item.fixed"
            :sortable="item.sortable"
            :type="item.type"
            :label="item.title"
            :prop="item.field"
            :width="item.width"
            :show-overflow-tooltip="item.overflow || true"
            :align="item.align ? item.align : 'left'"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
          >
            <template slot-scope="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.' + item.field" :rules="rules[item.field]">
                <el-switch
                  v-model="scope.row[item.field]"
                  :style="item.style"
                  :disabled="fieldDisabled(item, scope.row)"
                  :size="item.size || 'mini'"
                  :active-text="item.activeText"
                  :inactive-text="item.inactiveText"
                  :active-value="item.activeValue"
                  :inactive-value="item.inactiveValue"
                  @change="handleEvent(scope.row, item)"
                ></el-switch>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 表格支持带输入建议的输入框 -->
          <el-table-column
            v-else-if="item.editer === 'autocomplete'"
            :key="index + '_' + item.field"
            :fixed="item.fixed"
            :sortable="item.sortable"
            :type="item.type"
            :label="item.title"
            :prop="item.field"
            :width="item.width"
            :show-overflow-tooltip="item.overflow || true"
            :align="item.align ? item.align : 'left'"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
          >
            <template slot-scope="scope">
              <el-form-item :prop="'tableData.' + scope.$index + '.' + item.field" :rules="rules[item.field]">
                <el-autocomplete
                  v-model="scope.row[item.field]"
                  :size="item.size || 'mini'"
                  :style="item.style"
                  :placeholder="item.placeholder || '请输入'"
                  :clearable="item.clearable"
                  :readonly="item.readonly"
                  :disabled="fieldDisabled(item, scope.row)"
                  :fetch-suggestions="
                    (queryString, cb) => {
                      autoQuerySearch(queryString, cb, item, scope.row)
                    }
                  "
                  @select="
                    (selItem) => {
                      autoHandleSelect(selItem, item, scope.row)
                    }
                  "
                >
                  <template slot-scope="{ item }">
                    <div>
                      {{ item.title
                      }}<span style="font-size: 12px; color: rgba(144, 147, 152, 1); float: right">{{
                        item.value
                      }}</span>
                    </div>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            v-else
            :key="index + '_' + item.field"
            :class-name="item.field ? 'allowDrop' : ''"
            :fixed="item.fixed"
            :sortable="item.sortable"
            :type="item.type"
            :label="item.title"
            :prop="item.field"
            :width="item.width"
            :show-overflow-tooltip="item.overflow || true"
            :reserve-selection="item.type === 'selection' && item.reserveSelection"
            :align="item.align ? item.align : 'left'"
            :render-header="
              isCustomFieldHeader(item)
                ? (h, { column, $index }) => customFieldHeader(h, { column, $index }, item)
                : null
            "
            :selectable="(row) => rowCheckSelectable(item, row)"
          >
          </el-table-column>
        </template>
      </el-table>
      <!-- 表格分页 -->
      <div
        v-if="checkboxtion || toolbarItems.some((item) => item.position === 'bottom')"
        class="left-side dg-table-bottom"
      >
        <el-checkbox v-if="checkboxtion" v-model="allCheck" :indeterminate="isIndeterminate" @change="allCheckEvent"
          >全选</el-checkbox
        >
        <template v-for="(item, index) in toolbarItems">
          <el-button
            v-if="item.editer === 'button' && item.position === 'bottom'"
            :key="'footer-tool-' + index"
            v-monitor="item.monitor"
            :com-auth="item.comAuth || ''"
            :title="item.tooltip"
            :style="item.style"
            :type="item.type || 'primary'"
            :icon="item.icon"
            size="mini"
            :plain="item.plain"
            :round="item.round"
            :circle="item.circle"
            :disabled="selectRows.length === 0 || item.disabled"
            @click="clickHandle(item, initialData, toolbarData)"
          >
            <span v-if="item.title">{{ item.title }}</span>
          </el-button>
          <el-button
            v-if="item.editer === 'del' && item.position === 'bottom'"
            :key="'footer-tool-' + index"
            v-monitor="item.monitor"
            :com-auth="item.comAuth || ''"
            :title="item.tooltip"
            :plain="item.plain === false ? false : true"
            :style="item.style"
            :type="item.type || 'danger'"
            :icon="item.icon || 'el-icon-delete'"
            size="mini"
            :round="item.round"
            :circle="item.circle"
            :disabled="selectRows.length === 0 || item.disabled"
            @click="clickHandle(item, initialData, toolbarData)"
          >
            {{ item.title || '批量删除' }}
          </el-button>
        </template>
      </div>
      <div v-if="pagination" class="dg-table-footer dg-pagination-wrap">
        <div id="Pagination" class="dg-pagination">
          <el-pagination
            background
            :current-page="pageNumber"
            :page-sizes="[5, 15, 50, 100, 200]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>
    </el-form>
    <!-- 抽屉 -->
    <el-drawer
      id="DgTableDrawer"
      :wrapper-closable="false"
      :title="dialogTitle"
      :visible.sync="drawer"
      :append-to-body="true"
      :direction="direction"
      :before-close="handleDrawerClose"
      @closed="drawerClosed"
      @confirm="handleDialogForm"
    >
      <div class="drawer-content">
        <dg-form
          v-if="drawer"
          ref="DgTableForm"
          :form-data.sync="formData"
          :rules="rules"
          :form-items="formItems"
          :label-position="labelPosition"
          :label-width="labelWidth"
        >
        </dg-form>
      </div>
      <div class="drawer-footer">
        <div class="drawer-button">
          <el-button v-if="dialogButton" type="primary" @click="handleDialogForm">确 定</el-button>
          <el-button @click="drawer = false">取 消</el-button>
        </div>
      </div>
    </el-drawer>
    <!-- <dg-drawer :wrapperClosable="false"
      id="DgTableDrawer"
      :title="dialogTitle"
      :visible.sync="drawer"
      :append-to-body="true"
      :direction="direction"
      @closed="drawerClosed"
      @confirm="handleDialogForm">
      <div>
        <dg-form
          v-if="drawer"
          ref="DgTableForm"
          :formData.sync="formData"
          :rules="rules"
          :formItems="formItems"
          :labelPosition="labelPosition"
          :labelWidth="labelWidth">
        </dg-form>
      </div>
    </dg-drawer> -->
    <!-- 弹窗 -->
    <el-dialog
      v-if="formItems"
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
      :width="dialogWidth"
      :before-close="handleClose"
    >
      <!-- 调用表单组件 -->
      <dg-form
        :form-data.sync="formData"
        :rules="rules"
        :form-items="formItems"
        :label-position="labelPosition"
        label-width="85px"
      >
      </dg-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDialogForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 表格列设置及查询项设置弹窗 -->
    <el-dialog
      v-if="setUpDialogVisible"
      title="设置"
      :visible.sync="setUpDialogVisible"
      :append-to-body="true"
      :width="dialogWidth"
    >
      <!-- 调用表单组件 -->
      <el-form ref="setUpForm" v-model="setUpFormData" class="setUpForm" label-width="100px" label-position="left">
        <el-form-item label="查询项：" prop="toolbarOptionsVal">
          <el-checkbox-group v-model="setUpFormData.toolbarOptionsVal" :min="1">
            <template v-for="(option, index) in toolbarOptions">
              <el-checkbox
                :key="option.value"
                :label="option.value"
                draggable="true"
                @dragstart.native="drag($event, option, index)"
                @drop.native="drop($event, option, index)"
                @dragover.native="allowDrop($event)"
                >{{ option.name }}</el-checkbox
              >
            </template>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="表格列：" prop="colOptionsVal">
          <el-checkbox-group v-model="setUpFormData.colOptionsVal" :min="3">
            <template v-for="(option, index) in colOptions">
              <el-checkbox :key="option.value" :label="option.value">{{ option.name }}</el-checkbox>
            </template>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setUpDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUpFormSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import $ from 'jquery'

export default {
  name: 'DgTableV1',

  props: {
    height: {
      type: [Number, String],
      default: () => null,
    },
    rules: {
      type: Object,
      default: () => {
        return {}
      },
    },
    dialogWidth: {
      type: String,
      default: () => '50%',
    },
    border: {
      type: Boolean,
      default: () => false,
    },
    stripe: {
      type: Boolean,
      default: () => false,
    },
    tableData: {
      type: Array,
      default: () => [],
    },
    apiCode: {
      type: String,
      default: () => '',
    },
    getDataFn: {
      type: Function,
      default: null,
    },
    labelPosition: {
      type: String,
      default: () => '',
    },
    labelWidth: {
      type: String,
      default: () => '',
    },
    queryTerms: {
      type: String,
      default: () => '',
    },
    toolbarItems: {
      type: Array,
      default: () => [],
    },
    titleItems: {
      type: Array,
      default: () => [],
    },
    tableItems: {
      type: Array,
      default: () => [],
    },
    formItems: {
      type: Array,
      default: () => [],
    },
    pagination: {
      type: Boolean,
      default: () => true,
    },
    // checkboxtion: {
    //   type: Boolean,
    //   default: () => false
    // },
    pageSize: {
      type: Number,
      default: 15,
    },
    getPaginationData: {
      type: Function,
      default: function () {
        return {
          total: this.total,
          pageSize: this.pageSize,
          pageNumber: this.pageNumber,
        }
      },
    },
    colSet: {
      type: Boolean,
      default: () => false,
    },
    cacheSetKey: {
      type: String,
      default: () => '',
    },
    rowKey: {
      type: String,
      default: () => '',
    },
    cellStyle: {
      type: [Function, Object],
      default: () => {},
    },
    highlightCurrentRow: {
      type: Boolean,
      default: () => false,
    },
    rowClassName: {
      type: [Function, String],
      default: () => '',
    },
    isInitData: {
      type: Boolean,
      default: true,
    },
    searchData: {
      // 默认查询参数
      type: Object,
      default: () => ({}),
    },
  },

  data() {
    return {
      dialogTitle: '',
      dialogFormVisible: false,
      dialogButton: true,
      initialData: null,
      total: null,
      // pageSize: 15,
      pageNumber: 1,
      sonTableData: [],
      sonTableItems: [],
      toolbarData: {},
      formData: {},
      // rules: {},
      drawer: false,
      // refresh:true,
      direction: 'rtl',
      selectRows: [],

      multipleSelectionAll: [], // 所有选中的数据包含跨分页数据
      multipleSelectionArr: [], // row是对象的数组
      allCheck: false,
      isIndeterminate: false,
      setUpDialogVisible: false, // 设置表格列及查询项的弹窗
      setUpFormData: {}, // 设置表格列及查询项的表单
      toolbarQueryItems: [], // 所有的查询条件数据
      firstToolbarItems: [], // 默认显示的查询条件数组
      secondToolbarItems: [], // 更多的下拉框中显示的查询条件数组
      thirdToolbarItems: [], // 其余按钮组
      dragItem: {}, // 设置查询项的拖拽项
      dragIndex: 0, // 设置查询项的拖拽项的位置标识
      isMore: false,
      getRowKeys(row) {
        return row.id
      },
      colOptions: [],
      colOptionsVal: [],
      toolbarOptions: [],
      toolbarOptionsVal: [],
      tableHeight: '', // 表格高度
      tableRuleFrom: {
        tableData: [],
      },
      checkboxtion: false,
    }
  },

  computed: {
    getHeight: function () {
      return this.tableHeight
    },
    // isIndeterminate () { // 表示 checkbox 的不确定状态
    //   if (!this.allCheck) {
    //     const selectLength = this.selectRows ? this.selectRows.length : 0
    //     return selectLength > 0 && selectLength < (this.sonTableData || []).length
    //   }
    //   return false
    // }
  },

  watch: {
    tableData: {
      deep: true,
      handler: function (newVal, oldVal) {
        this.sonTableData = newVal
        // this.total = newVal.length
        // this.pageSize = 15
        // this.pageNumber = 1
      },
    },
    sonTableData: {
      deep: true,
      handler: function (newVal, oldVal) {
        this.tableRuleFrom.tableData = newVal
      },
    },
    'tableRuleFrom.tableData': {
      deep: true,
      handler: function (newVal, oldVal) {
        this.$emit('update:tableData', newVal)

        // 不懂这段逻辑有什么意义，并且会影响到分页勾选回显功能暂时先注释
        // if (this.allCheck) {
        //   this.tableRuleFrom.tableData.forEach(row => {
        //     if (row) {
        //       this.$refs.DgTable.toggleRowSelection(row, true)
        //     }
        //   });
        // }
        this.setAllCheck()

        // 表头变更，设置表头高度，防止错行。
        let _this = this
        this.$nextTick(function () {
          if (_this.$refs.DgTable) _this.$refs.DgTable.doLayout()
          // if(_this.tableHeight!='')_this.height = JSON.parse(JSON.stringify(_this.tableHeight)) // 当存在已存储的表格高度时，将表格高度重新赋给表格
          // _this.setTableHeadHeight()
        })
      },
    },
    toolbarItems: {
      deep: true,
      handler: function (newVal, oldVal) {
        this.initToolbarData()
        this.getToolBar()
      },
    },
    tableItems: {
      deep: true,
      handler: function (newVal, oldVal) {
        this.getColOptions()
      },
    },
    queryTerms(newVal, oldVal) {
      this.getData()
    },
  },

  mounted() {
    // this.rowDrop()
    // this.columnDrop()
  },

  created() {
    console.log(498573498579347589)
    this.initToolbarData('created')
    this.initSearchData()
    this.getToolBar()
    this.isInitData && this.getData()

    this.tableData.forEach((item, index) => {
      if (!item.id) item.id = index
    })
    if (this.tableItems.length) this.getColOptions()
    this.tableHeight = this.height
  },

  methods: {
    // 初始化toolbarData
    initToolbarData(type) {
      let needUpdate = false
      this.toolbarItems.forEach((item) => {
        if (item.default) {
          if (this.toolbarData[item.value] !== item.default) {
            this.toolbarData[item.value] = item.default
            needUpdate = true
          }
        }
        if (item.defaultFn) {
          let defaultValue = item.defaultFn(item)
          if (this.toolbarData[item.value] !== defaultValue) {
            this.toolbarData[item.value] = defaultValue
            needUpdate = true
          }
        }
      })
      if (type === 'created') needUpdate = false
      if (needUpdate) this.getData()
    },
    initSearchData() {
      if (Object.keys(this.searchData).length > 0) {
        this.toolbarData = { ...this.toolbarData, ...this.searchData }
      }
    },
    renderColContent(scope, item, index) {
      // 组件内封装将维度编码转换为维度名称
      let code = scope.row[item.field]
      let name = ''
      if (item.dimCode || item.apiCode) {
        let { dimCode, apiCode, filterVal, queryTerms } = item
        let dimKeyArr = [dimCode, apiCode, filterVal, queryTerms].filter((item) => item)
        let dimKey = dimKeyArr.join('_')

        let options = this.$store?.state?.dimData?.[dimKey] || []
        let codeArr = code ? code.split(',') : []
        let nameArr = codeArr.map((code) => {
          let name = ''
          let option = options.find((item) => item.id === code)
          if (option) name = option.name
          return name || code
        })
        name = nameArr.join(',')
      }
      // 外部自定义渲染方式
      if (item.render) return item.render(scope.row, item.renderPara || name, scope.column, index)

      return name || code
    },
    // 判断是否需要自定义表头
    isCustomFieldHeader(item) {
      return item.renderHeader || item.explain
    },
    // 自定义表格表头
    customFieldHeader(sh, { column, $index }, item) {
      let h = this.$createElement
      // 自定义函数渲染表头
      if (item.renderHeader) return item.renderHeader(h, { column, $index }, item)
      else {
        if (item.explain) {
          // 封装好的带问号解释的表头
          let explain = item.explain
          return h(
            'dg-tooltip',
            {
              props: {
                effect: explain.dark,
                content: explain.content,
                primaryKey: explain.primaryKey,
                apiCode: explain.apiCode,
                placement: explain.placement,
              },
            },
            [h('span', {}, [column.label, h('i', { class: 'el-icon-question' })])]
          )
        }
      }
    },
    // 字段是否可编辑
    fieldDisabled(item, row) {
      return item.disabled || (item.disabledFn ? item.disabledFn(row, item) : false)
    },
    // 这一行checkbox是否可以选中
    rowCheckSelectable(item, row) {
      if (item.selectable) {
        return item.selectable(row, item)
      } else {
        return true
      }
    },
    // myEnterClick() {
    //   this.pageNumber = 1
    //   this.getData()
    // },
    tableSortChange({ column, prop, order }) {
      if (column.sortable === 'custom') {
        let orderMap = {
          descending: 'DESC',
          ascending: 'ASC',
        }
        if (order) this.toolbarData['paraOrder'] = `${prop} ${orderMap[order]}`
        else delete this.toolbarData.paraOrder
        this.getData()
      }
    },
    getToolBar() {
      console.log(this.toolbarItems, 'toolbarItems')
      let queryIndex = 0 // 查询按钮所在位置下标
      let queryBtn = {}
      for (var i in this.toolbarItems) {
        if (this.toolbarItems[i].title == '查询' || this.toolbarItems[i].editer === 'search') {
          queryIndex = i
          // queryBtn = JSON.parse(JSON.stringify(this.toolbarItems[i]))
          queryBtn = Object.assign({}, this.toolbarItems[i])
          break
        }
      }
      this.toolbarQueryItems = this.toolbarItems.slice(0, Number(queryIndex))
      console.log(queryIndex, 'queryIndex')
      if (queryIndex < 2) {
        this.firstToolbarItems = this.toolbarItems.slice(0, Number(queryIndex) + 1)
        this.secondToolbarItems = []
      } else if (queryIndex == 2) {
        this.firstToolbarItems = this.toolbarItems.slice(0, 3)
        this.secondToolbarItems = []
      } else {
        this.firstToolbarItems = this.toolbarQueryItems.slice(0, 2)
        this.firstToolbarItems.push(queryBtn)
        this.firstToolbarItems[2].title = ''
        // this.firstToolbarItems[2].fn = this.toolbarItems[queryIndex].fn
        // this.firstToolbarItems[2].befFn = this.toolbarItems[queryIndex].befFn
        this.firstToolbarItems.push({ title: '更多', editer: 'moreBtn' })
        console.log(this.toolbarItems[2], this.secondToolbarItems, 'secondToolbarItems')
        // this.firstToolbarItems[0] = JSON.parse(JSON.stringify(this.toolbarItems[0]))
        // if(this.firstToolbarItems[0].editer==='input'){
        //   this.firstToolbarItems[0].appendIcon = 'el-icon-search'
        //   this.firstToolbarItems[0].fn = this.toolbarItems[queryIndex].fn
        // }else{
        //   if(this.firstToolbarItems.length<3)
        //   this.firstToolbarItems.push(queryBtn)
        //   this.firstToolbarItems[1].title = ''
        // }
        if (this.firstToolbarItems.length < 3) {
          this.firstToolbarItems.push({ title: '高级搜索', editer: 'moreBtn' })
        }
        this.secondToolbarItems = this.toolbarQueryItems.slice(2, Number(queryIndex))
      }
      if (queryIndex == this.toolbarItems.length - 1) {
        this.thirdToolbarItems = []
      } else {
        this.thirdToolbarItems = this.toolbarItems.slice(Number(queryIndex) + 1, this.toolbarItems.length)
      }
      this.getToolbarOptions()
      // console.log(this.firstToolbarItems,this.secondToolbarItems,this.thirdToolbarItems,'123toolbarItems')
    },
    // 获取列设置勾选框选项
    getColOptions() {
      // if (!this.sonTableItems.length) this.sonTableItems = JSON.parse(JSON.stringify(this.tableItems))
      ;[...this.sonTableItems] = this.tableItems
      this.colOptionsVal = []
      this.colOptions = []
      this.checkboxtion = false
      this.tableItems.forEach((item, index) => {
        if (item.field) {
          this.colOptionsVal.push(item.field)
          this.colOptions.push({
            name: item.title,
            value: item.field,
          })
        }
        // 底部全选框与表格中勾选框保持一致，统一配置
        if (item.type === 'selection') this.checkboxtion = true
        // 获取表格使用到的维度数据
        if (item.apiCode || item.dimCode) {
          this.$store?.dispatch('GetDimdataByCode', {
            dimCode: item.dimCode,
            apiCode: item.apiCode,
            filterVal: item.filterVal,
            queryTerms: item.queryTerms,
          })
        }
      })
      if (this.cacheSetKey) {
        if (this.$store?.state?.tableCfgData?.[this.cacheSetKey]) {
          if (this.$store.state.tableCfgData[this.cacheSetKey].length) {
            this.colOptionsVal = this.$store.state.tableCfgData[this.cacheSetKey]
            this.getTableShowItems(this.colOptionsVal)
          }
        }
      }
    },
    // 获取高级查询中的查询框
    getToolbarOptions() {
      this.toolbarOptionsVal = []
      this.toolbarOptions = []
      if (this.cacheSetKey) {
        if (this.$store?.state?.toolbarCfgData?.[this.cacheSetKey]) {
          if (this.$store.state.toolbarCfgData[this.cacheSetKey].length) {
            this.toolbarOptionsVal = this.$store.state.toolbarCfgData[this.cacheSetKey]
          }
        }
      }
      if (
        this.toolbarOptionsVal.length != this.toolbarQueryItems.length &&
        this.toolbarQueryItems.length > 2 &&
        this.toolbarOptionsVal.length > 0
      ) {
        // 如果存在已缓存的查询项设置
        let valueoptions = [],
          noValueOptions = []
        for (var i in this.toolbarQueryItems) {
          if (this.toolbarOptionsVal.indexOf(this.toolbarQueryItems[i].value) > -1) {
            valueoptions.push(this.toolbarQueryItems[i])
          } else {
            noValueOptions.push(this.toolbarQueryItems[i])
          }
        }
        valueoptions.sort((a, b) => {
          return this.toolbarOptionsVal.indexOf(a.value) - this.toolbarOptionsVal.indexOf(b.value)
        })
        this.toolbarQueryItems = valueoptions.concat(noValueOptions)
        this.toolbarQueryItems.forEach((item, index) => {
          if (item.value) {
            this.toolbarOptions.push({
              name: item.title || item.value,
              value: item.value,
            })
          }
        })
        let toolbarOptionsItems = []
        for (var i in this.toolbarQueryItems) {
          if (this.toolbarOptionsVal.some((val) => val === this.toolbarQueryItems[i].value)) {
            toolbarOptionsItems.push(this.toolbarQueryItems[i])
          }
        }
        if (toolbarOptionsItems.length < 2) {
          console.log(this.firstToolbarItems, 'this.firstToolbarItems,toolbarOptionsItems.length < 2')
          if (this.firstToolbarItems.length == 2) this.firstToolbarItems.splice(0, 1, toolbarOptionsItems[0])
          else if (this.firstToolbarItems.length == 3 || this.firstToolbarItems.length == 4) {
            this.firstToolbarItems.splice(0, 2, toolbarOptionsItems[0])
          }
          this.secondToolbarItems = []
          if (this.firstToolbarItems[this.firstToolbarItems.length - 1].editer == 'moreBtn') {
            this.firstToolbarItems.splice(2, 1)
          }
        } else if (toolbarOptionsItems.length == 2) {
          console.log(this.firstToolbarItems, 'this.firstToolbarItems,toolbarOptionsItems.length == 2')
          if (this.firstToolbarItems.length == 2) {
            this.firstToolbarItems.splice(0, 1, toolbarOptionsItems[0], toolbarOptionsItems[1])
          } else if (this.firstToolbarItems.length == 3 || this.firstToolbarItems.length == 4) {
            this.firstToolbarItems.splice(0, 2, toolbarOptionsItems[0], toolbarOptionsItems[1])
          }
          this.secondToolbarItems = []
          if (this.firstToolbarItems[this.firstToolbarItems.length - 1].editer == 'moreBtn') {
            this.firstToolbarItems.splice(3, 1)
          }
        } else {
          let firstOptionsItems = toolbarOptionsItems.slice(0, 2)
          this.firstToolbarItems.splice(0, 2, firstOptionsItems[0], firstOptionsItems[1])
          if (this.firstToolbarItems.length == 3) {
            this.firstToolbarItems.push({ title: '高级搜索', editer: 'moreBtn' })
          }
          this.secondToolbarItems = toolbarOptionsItems.slice(2)
        }
      } else {
        this.toolbarQueryItems.forEach((item, index) => {
          if (item.value) {
            this.toolbarOptionsVal.push(item.value)
            this.toolbarOptions.push({
              name: item.title || item.value,
              value: item.value,
            })
          }
        })
        if (this.cacheSetKey) {
          if (this.$store?.state?.toolbarCfgData?.[this.cacheSetKey]) {
            if (this.$store.state.toolbarCfgData[this.cacheSetKey].length) {
              this.toolbarOptionsVal = this.$store.state.toolbarCfgData[this.cacheSetKey]
            }
          }
        }
      }
    },
    // 处理带建议的输入框中的建议
    async autoQuerySearch(queryString, cb, item, row) {
      let formData = row || this.toolbarData
      let result = [{ value: 'no', title: '无建议' }]
      if (item.searchFn) {
        result = await item.searchFn(`${queryString || ''}`, item, formData)
      }
      console.log(result)
      cb(result)
    },
    // 带建议的输入框选择建议后触发事件
    autoHandleSelect(selectItem, item, row) {
      let formData = row || this.toolbarData
      if (item.aftSelect) {
        item.aftSelect(selectItem, item, formData)
      }
    },
    // 满足条件1和2的情况下，重新计算表头高度。
    setTableHeadHeight() {
      // 1.判断是否有冻结列。
      let isFixed = false
      if ($('#DgTable').find('.el-table__fixed').length > 0) {
        isFixed = true
      } else if ($('#DgTable').find('.el-table__fixed-right').length > 0) {
        isFixed = true
      } else if ($('#DgTable').find('.el-table__fixed-left').length > 0) {
        isFixed = true
      }
      if (isFixed) {
        // 2.判断表头高度是否换行存在，默认一行的高度为40。
        let headHeight = $('#DgTable').find('.el-table__header-wrapper').height()
        if (headHeight > 40) {
          $('#DgTable .el-table__fixed-body-wrapper').css('top', headHeight + 'px')
          let h1 = headHeight - 40
          let h2 = $('#DgTable .el-table__body-wrapper').height() + 17
          $('#DgTable .el-table__body-wrapper').height(h2 - h1 + 'px')
        }
      }
    },
    // 获取表格数据
    async getData() {
      let res = {}
      if (this.getDataFn) {
        res = await this.getDataFn(this.toolbarData, this.pageSize, this.pageNumber)
      } else if (this.apiCode) {
        let toolbarData = {}
        for (var key in this.toolbarData) {
          if (this.toolbarData[key] != null && this.toolbarData[key] != '') {
            toolbarData[key] = this.toolbarData[key]
          }
        }
        let data = {
          apiCode: this.apiCode,
          // params: `command=init&limit=${this.pageSize}&start=${(this.pageNumber - 1) * this.pageSize}`
          params: {
            ...toolbarData,
            command: 'init',
            limit: this.pageSize,
            start: (this.pageNumber - 1) * this.pageSize,
          },
        }
        if (this.queryTerms) data.apiCode += `&${this.queryTerms}`
        // for (let [key, value] of Object.entries(this.toolbarData)) {
        //   if (value) {
        //     data.params += `&${key}=${value}`
        //   }
        // }
        res = await this.$api.DgJsonStore(data)
      }
      this.initialData = res
      this.sonTableData = res.root || this.tableData
      // this.total = res.count || this.tableData.length
      this.total = res.root ? res.count : this.tableData.length
      this.$nextTick(function () {
        if (this.$refs.DgTable) this.$refs.DgTable.doLayout()
      })
      if (((res.root && res.root.length == 0) || (!res.root && this.tableData.length == 0)) && this.pageNumber != 1) {
        this.pageNumber = 1
        this.getData()
      }
    },
    // 更新表格数据
    async update(root) {
      // const res = await DgJsonStore({
      //   apiCode: this.apiCode,
      //   params: `command=update&records=[${JSON.stringify(root)}]`
      // })
      const res = await this.$api.DgJsonStore({
        apiCode: this.apiCode,
        params: {
          command: 'update',
          records: JSON.stringify(root),
        },
      })
      if (res.success) this.$message.success('操作数据成功')
      else this.$message.error('操作数据失败')
      this.getData()
    },
    // 新增表格数据
    async insert(root) {
      // const res = await DgJsonStore({
      //   apiCode: this.apiCode,
      //   params: `command=insert&records=[${JSON.stringify(root)}]`
      // })
      const res = await this.$api.DgJsonStore({
        apiCode: this.apiCode,
        params: {
          command: 'insert',
          records: JSON.stringify(root),
        },
      })
      if (res.success) this.$message.success('操作数据成功')
      else this.$message.error('操作数据失败')
      this.getData()
    },
    // 删除表格数据
    async delete(root) {
      // const res = await DgJsonStore({
      //   apiCode: this.apiCode,
      //   params: `command=delete&records=[${JSON.stringify(root)}]`
      // })
      // let arr = root.map(item => {
      //   let obj = {}
      //   Object.entries(item).forEach(x => {
      //     if (typeof x[1] === 'string') {
      //       obj[x[0]] = encodeURIComponent(x[1])
      //     } else {
      //       obj[x[0]] = x[1]
      //     }
      //     // console.log(x[0], x[1], 999)
      //     // obj[x[0]] = encodeURIComponent(x[1])
      //     // console.log(obj, 111)
      //   })
      //   return obj
      // })
      // console.log(root, 888)
      const res = await this.$api.DgJsonStore({
        apiCode: this.apiCode,
        params: {
          command: 'delete',
          records: JSON.stringify(root),
        },
      })
      if (res.success) this.$message.success('操作数据成功')
      else this.$message.error('操作数据失败')
      this.getData()
    },
    // 表头处理事件，接收父组件传来的函数体
    handleEvent(event, _item) {
      const item = _item || event
      let _this = this
      if (item.handleChange) {
        setTimeout(function () {
          item.handleChange(event, item, _this.toolbarData, _this.toolbarData[item.value])
        }, 0)
      }
      // if (item.helpSelect && item.editer === 'select') {
      //   // item.handleChange(event, item, _this)
      //   eval(item.handleChange)
      // } else if (item.handleChange) {
      //   setTimeout(function () {
      //     item.handleChange(event, item, _this.sonFormData, _this.sonFormData[item.value])
      //   }, 0)
      // } else if (item.handleFocus) {
      //   setTimeout(function () {
      //     item.handleFocus(event, item, _this.sonFormData, _this.sonFormData[item.value])
      //   }, 0)
      // }
      // if (item.handleChange) {
      //   setTimeout(function () {
      //     item.handleChange(event, item, _this.toolbarData, _this.toolbarData[item.value])
      //   }, 0)
      // }
    },
    // 表格头部按钮操作
    clickHandle(item, res, toolbarData) {
      if (item.befFn) item.befFn(item, res, toolbarData)
      switch (item.editer) {
        case 'search': {
          if (item.fn) item.fn(item, res, toolbarData)
          else {
            // this.pageSize = 15
            this.pageNumber = 1
            this.getData()
          }
          break
        }
        //          case 'add': {
        //            this.dialogTitle = '新增'
        //            this.formData = {}
        //            this.dialogFormVisible = true
        //            break
        //          }
        case 'add': {
          // if (item.befFn) item.befFn(item, res, toolbarData)
          if (item.fn) item.fn(item, res, toolbarData)
          else {
            this.dialogTitle = '新增'
            this.formData = {}
            this.formItems.map((item) => {
              if (item.val) {
                this.formData[item.value] = item.val
              }
              if (item.isDisabled) item.disabled = item.isDisabled === 'isAdd' // 判断该表单项在新增时是否禁用
            })
            this.drawer = true
          }
          if (item.aftFn) item.aftFn(item, res, toolbarData)
          break
        }
        case 'del': {
          // if (item.befFn) item.befFn(item, res, toolbarData)
          if (this.multipleSelectionArr.length) {
            this.$confirm('此操作将永久删除当前选中记录, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error',
            })
              .then(() => {
                this.delete(this.multipleSelectionArr)
              })
              .catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除',
                })
              })
          } else {
            this.$message('未选择对象')
          }
          break
        }
        case 'down': {
          if (item.fn) item.fn(item, toolbarData, res)
          else {
            let downParams = ''
            let fileName = ''
            if (Object.prototype.toString.call(item.fileName) === '[object String]') fileName = item.fileName
            else if (Object.prototype.toString.call(item.fileName) === '[object Function]') {
              fileName = item.fileName(item, toolbarData, res)
            }
            Object.keys(this.toolbarData).forEach((key) => {
              downParams += `&${key}=${this.toolbarData[key]}`
            })
            console.log(`通用下载链接 >>> ${this.$api.downUrl(this.apiCode, fileName || '', downParams)}`)
            window.open(this.$api.downUrl(this.apiCode, fileName || '', downParams))
          }
          break
        }
        case 'input': {
          // 输入框回车事件触发方法
          if (item.enterFn) item.enterFn(item, res, toolbarData)
          else {
            // 回车事件默认方法
            this.pageNumber = 1
            this.getData()
          }
          break
        }
        default: {
          // if (item.befFn) item.befFn(item, res, toolbarData)
          if (item.fn) {
            item.fn(item, res, toolbarData)
          }
          // if(item.refresh = true){
          //   this.pageSize = 15
          //   this.pageNumber = 1
          //   this.getData()
          // }
        }
      }
    },
    // 表格头部下拉选项选中事件
    selectDropdow(val, item) {
      if (item.fn) {
        item.fn(val, item)
      }
    },
    // 表格操作中下拉选项事件
    selectTableDropdow(val, item, row) {
      if (item.moreActions[val].fn) {
        item.moreActions[val].fn(row)
      }
    },
    // 表格开启勾选选中事件
    handleSelectionChange(val) {
      this.multipleSelectionArr = val
      this.$emit('selectionChange', val)
      // let total
      // let pageSize
      // let pageNumber
      // if (this.pagination) {
      //   total = this.total
      //   pageSize = this.pageSize
      //   pageNumber = this.pageNumber
      // } else {
      //   let obj = this.getPaginationData()
      //   total = obj.total
      //   pageSize = obj.pageSize
      //   pageNumber = obj.pageNumber
      // }
      // this.$nextTick(() => {
      //   let page = Math.ceil(total / pageSize)
      //   if (page === pageNumber) {
      //     if (val.length === total - pageSize * (pageNumber - 1)) {
      //       this.allCheck = true
      //     } else {
      //       this.allCheck = false
      //     }
      //   } else {
      //     if (val.length === pageSize) {
      //       this.allCheck = true
      //     } else {
      //       this.allCheck = false
      //     }
      //   }
      // })
      this.selectRows = val
      this.multipleSelectionAll = val.map((item) => item.id).toString()
      this.setAllCheck()
    },

    // 分页全选-全选按钮change事件
    allCheckEvent(val) {
      if (val) {
        this.isIndeterminate = false
        this.sonTableData.forEach((row) => {
          if (row) {
            this.$refs.DgTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.sonTableData.forEach((row) => {
          if (row) {
            this.$refs.DgTable.toggleRowSelection(row, false)
          }
        })
      }
      // let _this = this
      // if (_this.allCheck) {
      //   // 全选选中时当前页所有数据选中
      //   _this.sonTableData.forEach(row => {
      //     if (row) {
      //       _this.$refs.DgTable.toggleRowSelection(row, true)
      //     }
      //   })
      // } else {
      //   _this.$refs.DgTable.clearSelection()
      //   this.allCheck = false
      // }
    },
    // 分页全选-全选时禁用选择框
    checkSelectable(row, index) {
      return !this.allCheck
    },
    // 全选按钮状态设置
    setAllCheck() {
      if (this.selectRows.length) {
        let keys = []
        let curPageSelections = this.selectRows
        if (this.rowKey) {
          keys = this.selectRows.map((item) => item[this.rowKey])
          curPageSelections = this.tableRuleFrom.tableData.filter((item) => keys.includes(item[this.rowKey]))
        }
        console.log(curPageSelections.length === this.tableRuleFrom.tableData.length)
        if (curPageSelections.length === this.tableRuleFrom.tableData.length) {
          this.allCheck = true
          this.isIndeterminate = false
        } else {
          this.allCheck = false
          this.isIndeterminate = true
        }
      } else {
        this.allCheck = false
        this.isIndeterminate = false
      }
    },
    // 数组对象去重
    reduceSame: function (arr) {
      let obj = {}
      return arr.reduce(function (prev, item) {
        obj[item.id] ? '' : (obj[item.id] = 1 && prev.push(item))
        return prev
      }, [])
    },

    // 表格中操作事件
    rowAction(action, row, index, $event) {
      switch (action.fn) {
        case 'del': {
          if (action.befFn) action.befFn(action, row, index, $event)
          this.$confirm('此操作将永久删除当前记录, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
          })
            .then(() => {
              let root = []
              root.push(row)
              this.delete(root)
              if (action.aftFn) action.aftFn(action, row, index, $event)
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除',
              })
            })

          break
        }
        // case 'edit': {
        //   this.dialogTitle = '修改'
        //   this.formData = row
        //   this.dialogFormVisible = true
        //   break
        // }
        case 'edit': {
          if (action.befFn) action.befFn(action, row, index, $event)
          this.dialogTitle = '修改'
          this.formItems.map((item) => {
            if (item.isDisabled) item.disabled = item.isDisabled === 'isEdit' // 判断该表单项在编辑时是否禁用
          })
          this.dialogButton = true
          this.formData = JSON.parse(JSON.stringify(row))
          this.drawer = true
          if (action.aftFn) action.aftFn(action, row, index, $event)
          break
        }
        case 'detail': {
          if (action.befFn) action.befFn(action, row, index, $event)
          this.dialogTitle = '详情'
          this.dialogButton = false
          this.formData = JSON.parse(JSON.stringify(row))
          this.drawer = true
          break
        }
        default: {
          if (action.befFn) action.befFn(action, row, index, $event)
          if (action.fn) {
            action.fn(action, row, index, $event)
          }
          break
        }
      }
    },
    // 分页pageSize改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNumber = 1
      this.getData()
    },
    // 分页pageNumber改变时触发
    handleCurrentChange(val) {
      this.pageNumber = val
      this.getData()
    },
    // handleRefresh() {
    //   this.pageNumber = val
    //   this.getData()
    // },
    // 确定提交表单
    handleDialogForm() {
      // let root = this.formData
      let root = []
      root.push(this.formData)
      // console.log(root, 9081)
      this.$refs.DgTableForm.$refs.sonFormData.validate((valid) => {
        // let arr = root.map(item => {
        //   let obj = {}
        //   Object.entries(item).forEach(x => {
        //     if (typeof x[1] === 'string') {
        //       obj[x[0]] = encodeURIComponent(x[1])
        //     } else {
        //       obj[x[0]] = x[1]
        //     }
        //     // console.log(x[0], x[1], 999)
        //     // obj[x[0]] = encodeURIComponent(x[1])
        //     // console.log(obj, 111)
        //   })
        //   return obj
        // })
        // // console.log(arr, 9999)
        // return
        if (valid) {
          this.dialogTitle === '新增' ? this.insert(root) : this.update(root)
          this.drawer = false
          // this.$message.success('操作成功')
        } else {
          this.$message.error('请完善信息后再保存')
          return false
        }
      })
      // this.dialogFormVisible = false
    },
    handleClose() {
      this.getData()
      this.dialogFormVisible = false
    },
    handleDrawerClose() {
      this.getData()
      this.drawer = false
    },
    // 行双击
    rowDblclick(row, column, event) {
      this.$emit('rowDblclick', row, column, event)
    },
    // 行点击事件
    rowClick(row, column, event) {
      this.$emit('rowClick', row, column, event)
    },
    cellClick(row, column, cell, event) {
      this.$emit('cellClick', row, column, cell, event)
    },
    // 滑窗关闭
    drawerClosed() {
      this.getData()
    },
    // 更改更多按钮的状态
    changeIsMore() {
      let w = this.$refs.toolbarForm.$el.clientHeight // 获取搜索栏高度
      let t = this.$refs.DgTable.$el.clientHeight // 获取表格当前高度
      this.isMore = !this.isMore
      this.$nextTick(() => {
        let nw = this.$refs.toolbarForm.$el.clientHeight // 获取搜索栏高度改变后的高度
        this.tableHeight = t - (nw - w) + 'px' // 给表格高度重新赋值
        // this.height=t-(nw-w)+'px' // 给表格高度重新赋值
        // this.tableHeight = JSON.parse(JSON.stringify(this.height)) // 保存一个原来的表格高度用于重新获取数据后的表格高度赋值
      })
    },

    // 行拖拽
    rowDrop() {
      const tbody = document.querySelector('#DgTable tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
        },
      })
    },
    // 列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector('#DgTable tr')
      const _this = this
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        handle: '.allowDrop',
        onEnd: (evt) => {
          const oldItem = _this.sonTableItems[evt.oldIndex]
          _this.sonTableItems.splice(evt.oldIndex, 1)
          _this.$nextTick(() => {
            _this.sonTableItems.splice(evt.newIndex, 0, oldItem)
          })
        },
      })
    },
    // 表头拖动后重新渲染表格
    headerDragend() {
      /*
        此操作如果不在dom渲染完后触发会引发bug
        拖拽表头改变列宽时，内容宽度不会变化，导致表格列中内容无法自适应
        是否现在还有表头拖拽功能？暂时改为dom渲染完后触发
      **/
      // if (this.$refs.DgTable) this.$refs.DgTable.doLayout()
      this.$nextTick(() => {
        if (this.$refs.DgTable) this.$refs.DgTable.doLayout()
      })
    },
    // 表格设置
    setup() {
      this.setUpFormData = {
        colOptionsVal: this.colOptionsVal,
        toolbarOptionsVal: this.toolbarOptionsVal,
      }
      this.setUpDialogVisible = true
      // let formData = {
      //   colOptionsVal: this.colOptionsVal,
      //   toolbarOptionsVal: this.toolbarOptionsVal
      // }
      // let formItems = [
      //   { editer: 'checkbox', label: '查询项：', value: 'toolbarOptionsVal', options: this.toolbarOptions, min: 1 },
      //   { editer: 'checkbox', label: '表格列：', value: 'colOptionsVal', options: this.colOptions, min: 3 }
      // ]
      // this.$msgbox({
      //   title: '设置',
      //   message: this.$createElement('div', null, [
      //     [
      //       this.$createElement(
      //         'dg-form',
      //         {
      //           props: {
      //             formData: formData,
      //             formItems: formItems,
      //             labelPosition: 'left'
      //           }
      //         }
      //       )
      //     ]
      //   ]),
      //   showCancelButton: true,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消'
      // }).then(val => {
      //   // this.getData()
      //   this.colOptionsVal = formData.colOptionsVal
      //   this.toolbarOptionsVal = formData.toolbarOptionsVal
      //   let toolbarOptionsItems=[]
      //   for(var i in this.toolbarQueryItems){
      //     if(this.toolbarOptionsVal.some(val => val === this.toolbarQueryItems[i].value)){
      //       toolbarOptionsItems.push(this.toolbarQueryItems[i])
      //     }
      //   }
      //   if (toolbarOptionsItems.length < 2) {
      //     if(this.firstToolbarItems.length==2) this.firstToolbarItems.splice(0,1,toolbarOptionsItems[0])
      //     else if(this.firstToolbarItems.length==3||this.firstToolbarItems.length==4) this.firstToolbarItems.splice(0,2,toolbarOptionsItems[0])
      //     this.secondToolbarItems = []
      //     if(this.firstToolbarItems[this.firstToolbarItems.length-1].editer=='moreBtn'){
      //       this.firstToolbarItems.splice(2,1)
      //     }
      //   } else if (toolbarOptionsItems.length == 2) {
      //     if(this.firstToolbarItems.length==2) this.firstToolbarItems.splice(0,1,toolbarOptionsItems[0],toolbarOptionsItems[1])
      //     else if(this.firstToolbarItems.length==3||this.firstToolbarItems.length==4) this.firstToolbarItems.splice(0,2,toolbarOptionsItems[0],toolbarOptionsItems[1])
      //     this.secondToolbarItems = []
      //     if(this.firstToolbarItems[this.firstToolbarItems.length-1].editer=='moreBtn'){
      //       this.firstToolbarItems.splice(3,1)
      //     }
      //   } else {
      //     let firstOptionsItems = toolbarOptionsItems.slice(0,2)
      //     if(this.firstToolbarItems.length==2) this.firstToolbarItems.splice(0,1,firstOptionsItems[0],firstOptionsItems[1])
      //     else if(this.firstToolbarItems.length==3||this.firstToolbarItems.length==4) this.firstToolbarItems.splice(0,2,firstOptionsItems[0],firstOptionsItems[1])
      //     if (this.firstToolbarItems.length == 3) {
      //       this.firstToolbarItems.push({ title: '高级搜索', editer: 'moreBtn' })
      //     }
      //     this.secondToolbarItems = toolbarOptionsItems.slice(2)
      //   }
      //   for(var key in this.toolbarData){
      //     if(this.toolbarOptionsVal.indexOf(key)<0){
      //       delete this.toolbarData[key]
      //     }
      //   }
      //   this.clickHandle(this.firstToolbarItems[2],this.initialData,this.toolbarData) //手动触发查询操作，重新获取数据
      //   if (this.cacheSetKey) {
      //     this.$store.commit('SET_COLOPTIONSVAL', {key: this.cacheSetKey, value:formData.colOptionsVal})
      //     this.$store.commit('SET_TOOLBAROPTIONSVAL', {key: this.cacheSetKey, value: formData.toolbarOptionsVal})
      //   }
      //   // this.tableItems.splice(0, 1)
      //   this.getTableShowItems(this.colOptionsVal)
      // }).catch(() => {
      // })
    },
    // 查询项设置拖拽排序
    allowDrop(ev) {
      ev.preventDefault()
    },
    drag(ev, option, index) {
      this.dragItem = option
      this.dragIndex = index
      console.log(ev, 'drapstart', option, index)
      // ev.dataTransfer.setData('Text',ev.target.id);
    },
    drop(ev, option, index) {
      console.log(ev, 'drop', option, index)
      this.toolbarOptions.splice(this.dragIndex, 1)
      this.toolbarOptions.splice(index, 0, this.dragItem)
      let optionsVal = []
      for (var i in this.toolbarOptions) {
        if (this.toolbarOptionsVal.indexOf(this.toolbarOptions[i].value) >= 0) {
          optionsVal.push(this.toolbarOptions[i].value)
        }
      }
      this.setUpFormData.toolbarOptionsVal = optionsVal
      let toolbarQueryoptions = []
      let optionsItems = []
      this.toolbarOptions.forEach((item) => {
        optionsItems.push(item.value)
      })
      this.toolbarQueryItems.sort((a, b) => {
        return optionsItems.indexOf(a.value) - optionsItems.indexOf(b.value)
      })
      ev.preventDefault()
    },
    // 保存查询项和表格列设置
    setUpFormSubmit() {
      this.colOptionsVal = this.setUpFormData.colOptionsVal
      this.toolbarOptionsVal = this.setUpFormData.toolbarOptionsVal
      let toolbarOptionsItems = []
      for (var i in this.toolbarQueryItems) {
        if (this.toolbarOptionsVal.some((val) => val === this.toolbarQueryItems[i].value)) {
          toolbarOptionsItems.push(this.toolbarQueryItems[i])
        }
      }
      if (toolbarOptionsItems.length < 2) {
        if (this.firstToolbarItems.length == 2) this.firstToolbarItems.splice(0, 1, toolbarOptionsItems[0])
        else if (this.firstToolbarItems.length == 3 || this.firstToolbarItems.length == 4) {
          this.firstToolbarItems.splice(0, 2, toolbarOptionsItems[0])
        }
        this.secondToolbarItems = []
        if (this.firstToolbarItems[this.firstToolbarItems.length - 1].editer == 'moreBtn') {
          this.firstToolbarItems.splice(2, 1)
        }
      } else if (toolbarOptionsItems.length == 2) {
        if (this.firstToolbarItems.length == 2) {
          this.firstToolbarItems.splice(0, 1, toolbarOptionsItems[0], toolbarOptionsItems[1])
        } else if (this.firstToolbarItems.length == 3 || this.firstToolbarItems.length == 4) {
          this.firstToolbarItems.splice(0, 2, toolbarOptionsItems[0], toolbarOptionsItems[1])
        }
        this.secondToolbarItems = []
        if (this.firstToolbarItems[this.firstToolbarItems.length - 1].editer == 'moreBtn') {
          this.firstToolbarItems.splice(3, 1)
        }
      } else {
        let firstOptionsItems = toolbarOptionsItems.slice(0, 2)
        if (this.firstToolbarItems.length == 2) {
          this.firstToolbarItems.splice(0, 1, firstOptionsItems[0], firstOptionsItems[1])
        } else if (this.firstToolbarItems.length == 3 || this.firstToolbarItems.length == 4) {
          this.firstToolbarItems.splice(0, 2, firstOptionsItems[0], firstOptionsItems[1])
        }
        if (this.firstToolbarItems.length == 3) {
          this.firstToolbarItems.push({ title: '高级搜索', editer: 'moreBtn' })
        }
        this.secondToolbarItems = toolbarOptionsItems.slice(2)
      }
      for (var key in this.toolbarData) {
        if (this.toolbarOptionsVal.indexOf(key) < 0) {
          delete this.toolbarData[key]
        }
      }
      if (this.firstToolbarItems.length > 2) {
        this.clickHandle(this.firstToolbarItems[2], this.initialData, this.toolbarData)
      }
      // 手动触发查询操作，重新获取数据
      else this.clickHandle(this.firstToolbarItems[1], this.initialData, this.toolbarData) // 手动触发查询操作，重新获取数据
      console.log(this.toolbarOptionsVal, this.setUpFormData, 'this.toolbarOptionsVal,this.setUpFormData')
      if (this.cacheSetKey) {
        this.$store?.commit('SET_COLOPTIONSVAL', { key: this.cacheSetKey, value: this.setUpFormData.colOptionsVal })
        this.$store?.commit('SET_TOOLBAROPTIONSVAL', { key: this.cacheSetKey, value: this.toolbarOptionsVal })
      }
      this.getTableShowItems(this.colOptionsVal)
      this.setUpDialogVisible = false
    },
    // 获取表格显示的列
    getTableShowItems(items) {
      console.log(items)
      let tableShowItems = []
      this.sonTableItems.forEach((item) => {
        if (!item.field) tableShowItems.push(item)
        if (items.some((field) => field === item.field)) tableShowItems.push(item)
      })
      items.forEach((field) => {
        // if (!this.sonTableItems.some(item => item.field === field)) tableShowItems.unshift(this.tableItems.filter(item => item.field === field)[0])
        if (!this.sonTableItems.some((item) => item.field === field)) {
          let tableItemsIndex = ''
          let showItem = this.tableItems.filter((item, index) => {
            if (item.field === field) tableItemsIndex = index
            return item.field === field
          })[0]
          tableShowItems.splice(tableItemsIndex, 0, showItem)
        }
      })
      this.sonTableItems = tableShowItems
      tableShowItems.forEach((item, index) => {
        if (!item.field && item.actions) {
          this.sonTableItems.splice(index, 1)
          this.sonTableItems.push(item)
        }
      })
      this.$nextTick(() => {
        if (this.$refs.DgTable) this.$refs.DgTable.doLayout()
      })
      console.log(this.tableItems)
    },
  },
}
</script>
