<template>
  <div class="aos-table-form-inline clearfix" ref="aosTableContainer" :class="{'aos-table-form-inline__inline-search': inlineSearch}">
    <div class="aos-table-form-inline__explain" :style="{'justify-content': (!showCrossContainer && showExplainContainer) ? 'flex-end' : 'space-between'}" v-if="showExplain">
      <div class="aos-table-form-inline__cross-container" v-if="showCrossContainer">
        <div
          class="aos-table-form-inline__refresh"
          v-if="showRefresh"
          @click="handleDebounceRefresh">
          <i :style="{'transform': 'rotate(' + rotate+ 'deg)'}" class="el-icon-refresh" title="点击刷新"></i>
          <span class="aos-table-form-inline__refresh-label">刷新</span>
        </div>
        <div>
          <el-button v-if="showInlineAdd" :debounce="300" type="primary" size="mini" @click="handleInlineAdd">新增</el-button>
        </div>
        <div class="aos-table-form-inline__cross-container-main" v-if="showCrossSelection && copyTableTemplate.selection && copyTableTemplate.selection.showSelection">
          <el-checkbox class="aos-table-form-inline__cross-container-checkbox" v-model="crossPageSelect" size="mini" @change="crossPageSelectChange">跨页选择</el-checkbox>
          <el-popover
            placement="right"
            title="跨页已选数据"
            width="600"
            trigger="click">
            <el-table
              :data="currentCrossSelectList"
              ref="AosTable"
              stripe
              highlight-current-row
              height="600"
              style="width: 100%">
              <template v-for="item in copyTableTemplate.tableItem">
                <el-table-column
                  v-if="!item.hide"
                  :key="item.prop"
                  :prop="item.prop"
                  :label="item.label"
                  :width="item.width"
                  :min-width="item.minWidth || '100px'"
                  :show-overflow-tooltip="item.showOverflowTooltip"
                  :sortable="item.sortable"
                  :align="item.align ? item.align : 'left'">
                  <template slot-scope="scope" >
                    <slot v-if="item.showSlot" :name="item.prop + '-slot'" :scope="scope"></slot>
                    <template v-else-if="item.type === 'defdoc'">
                      <aos-defdoc 
                        :value="scope.row[item.prop] || ''"
                        :editable="false"
                        :defCode="item.defCode"
                        :tag="item.tag"
                        :customerUrl="item.customerUrl"
                        :multiple="item.multiple"
                        :no-def-code="item.noDefCode"
                        :orm-code="item.ormCode"
                        :orm-name="item.ormName"
                        :orm-status="item.ormStatus"
                        :orm-data="item.ormData"
                        :outer="item.outer"
                        :outer-options="item.outerOptions">
                      </aos-defdoc>
                    </template>
                    <template v-else-if="item.type === 'rule-defdoc'">
                      <aos-rule-defdoc :value="scope.row[item.prop]" :editable="false" :defCode="item.defCode" :multiple="item.multiple"></aos-rule-defdoc>
                    </template>
                    <template v-else-if="item.type === 'ref'">
                      <aos-ref :value="scope.row[item.prop]" :editable="false" :refCode="item.refCode" :filters="item.filters" :multiple="item.multiple" :onlyTranslate="true" :translateRefValueLable="scope.row[item.prop + 'Label']"></aos-ref>
                    </template>
                    <template v-else-if="item.type === 'money'">
                      <aos-money :editable="false" v-model="scope.row[item.prop]" :decimal="item.decimal || 2" :suffixString="item.suffixString"></aos-money>
                    </template>
                    <template v-else-if="item.type === 'city'">
                      <aos-city :customerUrl="item.customerUrl" :customerMethod="item.customerMethod"  :templateValue="scope.row" :edit="false" :province="item.province" :city="item.city" :county="item.county"></aos-city>
                    </template>
                    <template v-else-if="item.type === 'date-picker'">
                      <span>{{ $time.formatTime(scope.row[item.prop], ((item.attrs && item.attrs.format) || ''))}}</span>
                    </template>
                    <span v-else :title="scope.row[item.prop]">{{scope.row[item.prop]}}</span>
                  </template>
                </el-table-column>
              </template>
              <el-table-column
                fixed="right"
                label="操作"
                width="100px">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleDeleteCrossItem(scope)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button size="mini" type="text" slot="reference">已选择</el-button>
          </el-popover>
        </div>
        <div class="aos-table-form-inline__other-container" v-if="$slots.headerLeft || $slots['header-left']">
          <slot name="headerLeft"></slot>
          <slot name="header-left"></slot>
        </div>
      </div>
      <div class="aos-table-form-inline__explain-container" v-if="showExplainContainer">
        <div v-if="inlineSearch" class="aos-table-form-inline__inline-search-reset-container">
          <span class="aos-table-form-inline__inline-search-reset" @click="handleInlineSearchReset">
            <span class="aos-table-form-inline__inline-search-reset-icon">
              <svg t="1654067782205" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4392" width="12" height="12"><path d="M892.8 320.2H624.6V130.1c0-35.3-28.7-64-64-64h-97.2c-35.3 0-64 28.7-64 64v190.1H129.8c-35.3 0-64 28.7-64 64v97.2c0 35 28 63.4 62.9 64v312.4c0 55.2 44.8 100 100 100h568.4c55.2 0 100-44.8 100-100V545.3c33.3-2.2 59.7-29.9 59.7-63.8v-97.2c0-35.4-28.6-64.1-64-64.1z m-27.7 537.6c0 37.5-30.5 68-68 68h-84.4V781.6c0-8.8-7.2-16-16-16s-16 7.2-16 16v144.2H528.6V781.6c0-8.8-7.2-16-16-16s-16 7.2-16 16v144.2H344.5V781.6c0-8.8-7.2-16-16-16s-16 7.2-16 16v144.2h-83.8c-37.5 0-68-30.5-68-68V545.7h704.4v312.1z m59.7-376.4c0 17.6-14.4 32-32 32h-763c-17.6 0-32-14.4-32-32v-97.2c0-17.6 14.4-32 32-32h301.6V130.1c0-17.6 14.4-32 32-32h97.2c17.6 0 32 14.4 32 32v222.1h300.2c17.6 0 32 14.4 32 32v97.2z" fill="#409EFF" p-id="4393"></path></svg>
            </span>
            <span class="aos-table-form-inline__inline-search-reset-label">重置</span>
          </span>
        </div>
        <div class="aos-table-form-inline__operation" v-if="copyTableTemplate.operationColumn && copyTableTemplate.operationColumn.showOperation && copyTableTemplate.operationColumn.operationType === 'icon' && copyTableTemplate.operationColumn.iconList && copyTableTemplate.operationColumn.iconList.length > 0">
          <span class="aos-table-form-inline__explain-title">操作列图标说明：</span>
          <span v-for="icon in copyTableTemplate.operationColumn.iconList" :key="icon.code" class="aos-table-form-inline__explain-item">
            <i :class="'el-icon-'+icon.icon"></i>
            <span>：{{icon.detail ? icon.detail : icon.title}}</span>
          </span>
        </div>
        <div class="aos-table-form-inline__setting" v-if="showSetting">
          <el-dropdown trigger="click" :hide-on-click="false"  @command="handleSettingItem">
            <i class="el-icon-setting" title="设置操作列的显示/隐藏"></i>
            <el-dropdown-menu slot="dropdown">
              <!-- <el-dropdown-item>
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              </el-dropdown-item> -->
              <!-- <el-checkbox-group v-model="allItem" @change="handleItemChange"> -->
                <el-dropdown-item v-for="(item,index) in copyTableTemplate.tableItem" :key="item.prop">
                  <el-checkbox :value="!item.hide" :checked="!item.hide" :label="item.prop" @change="handleItemTypeChange(index)">{{item.label}}</el-checkbox>
                </el-dropdown-item>
              <!-- </el-checkbox-group> -->
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="aos-table-form-inline__container">
      <el-table
        :data="data"
        ref="AosTable"
        :stripe="stripe"
        highlight-current-row
        :height="tableHeight"
        :border="border"
        :fit="fit"
        :row-class-name="rowClassName"
        :show-summary="showSummary"
        :select-on-indeterminate="selectOnIndeterminate"
        :sum-text="sumText"
        :row-key="rowKey"
        :empty-text="emptyText"
        :default-expand-all="defaultExpandAll"
        :expand-row-keys="expandRowKeys"
        :default-sort="defaultSort"
        :tooltip-effect="tooltipEffect"
        :summary-method="summaryMethod"
        :span-method="spanMethod"
        :indent="indent"
        :lazy="lazy"
        :load="load"
        :tree-props="treeProps"
        style="width: 100%"
        @select="handleSelect"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        @row-click="handleRowClick"
        @row-dblclick="handleRowdbclick"
        @current-change="handleTableCurrentChange"
        @scroll="handleScroll">
        <el-table-column
          v-if="copyTableTemplate.selection && copyTableTemplate.selection.showSelection"
          type="selection"
          :selectable="selectable"
          :min-width="copyTableTemplate.selection.minWidth"
          :width="copyTableTemplate.selection.width || '60'">
        </el-table-column>
        <template v-for="item in copyTableTemplate.tableItem">
          <template v-if="item.children && Array.isArray(item.children) && item.children.length > 0">
            <el-table-column :label="item.label" :key="item.label">
              <aos-table-item 
                v-for="child in item.children"
                :key="child.prop"
                :item="child"
                :inlineEditable="inlineEditable"
                :handleInlineEditAble="handleInlineEditAble"
                :handleInputNumberEmit="handleInputNumberEmit"
                :handleRefEmit="handleRefEmit"
                :formHandleEmit="formHandleEmit"
                :handleInlineSearchChange="handleInlineSearchChange"
                :handleInlineOcr="handleInlineOcr"
                :handleRefLeaseEmit="handleRefLeaseEmit"
                :handleDefdocEmit="handleDefdocEmit"
                :handleMoneydocEmit="handleMoneydocEmit"
                :handleMarkdownEditorEmit="handleMarkdownEditorEmit"
                :handleCityEmit="handleCityEmit"
                :handleUploaderEmit="handleUploaderEmit"
                :handleOcr="handleOcr"
                :formatDatePickerValue="formatDatePickerValue"
                :inlineSearch="inlineSearch"
                :edit="edit"
                >
              </aos-table-item>
            </el-table-column>
          </template>
          <template v-else>
            <aos-table-item 
                :key="item.prop"
                :item="item"
                :edit="edit"
                :inlineEditable="inlineEditable"
                :handleInlineEditAble="handleInlineEditAble"
                :handleInputNumberEmit="handleInputNumberEmit"
                :handleRefEmit="handleRefEmit"
                :formHandleEmit="formHandleEmit"
                :handleInlineSearchChange="handleInlineSearchChange"
                :handleInlineOcr="handleInlineOcr"
                :handleRefLeaseEmit="handleRefLeaseEmit"
                :handleDefdocEmit="handleDefdocEmit"
                :handleMoneydocEmit="handleMoneydocEmit"
                :handleMarkdownEditorEmit="handleMarkdownEditorEmit"
                :handleCityEmit="handleCityEmit"
                :handleUploaderEmit="handleUploaderEmit"
                :handleOcr="handleOcr"
                :formatDatePickerValue="formatDatePickerValue"
                :inlineSearch="inlineSearch"
                >
              </aos-table-item>
          </template>
        </template>
        <el-table-column
          v-if="copyTableTemplate.operationColumn && copyTableTemplate.operationColumn.showOperation"
          :fixed="copyTableTemplate.operationColumn.fixed || 'right'"
          :label="copyTableTemplate.operationColumn.label || '操作'"
          :width="copyTableTemplate.operationColumn.width || operationColumnMinWidth+ 'px'"
          :min-width="copyTableTemplate.operationColumn.minWidth">
          <template v-if="inlineSearch" slot="header">
            <div class="aos-table-form-inline__inline-header">
              <div v-if="copyTableTemplate.operationColumn.label" class="aos-table-form-inline__inline-header-label">{{ copyTableTemplate.operationColumn.label }}</div>
              <div v-else class="aos-table-form-inline__inline-header-label">操作</div>
            </div>
          </template>
          <template slot-scope="scope">
            <div class="aos-table-form-inline__operation">
              <span class="aos-table-form-inline-button" v-if="inlineEditable(scope.row) && handleInlineEditAble(scope.row) && edit">
                <el-button type="text" @click.stop="handleInlineSave(scope)">保存</el-button>
              </span>
              <span class="aos-table-form-inline-button" v-if="inlineEditable(scope.row) && handleInlineEditAble(scope.row) && edit">
                <el-button type="text" @click.stop="handleInlineCancle(scope)">取消</el-button>
              </span>
              <span class="aos-table-form-inline-button" v-if="inlineEditable(scope.row) && !handleInlineEditAble(scope.row) && showInlineDelete">
                <el-button type="text" @click.stop="handleInlineDelete(scope)">删除</el-button>
              </span>
              <slot v-if="copyTableTemplate.operationColumn.showOperationSlot" name="operation-slot" :scope="scope"></slot>
              <template v-if="copyTableTemplate.operationColumn.operationType === 'icon' && copyTableTemplate.operationColumn.iconList && copyTableTemplate.operationColumn.iconList.length > 0">
                <span v-for="icon in copyTableTemplate.operationColumn.iconList" :key="icon.code" v-auth="icon.auth">
                  <i class="aos-table-form-inline-icon"
                    :class="'el-icon-'+icon.icon" 
                    :title="icon.title"
                    v-if="iconable(scope.row, icon.code)"
                    @click="handleIconClick(icon.code,scope)">
                  </i>
                </span>
              </template>
              <template v-else-if="copyTableTemplate.operationColumn.operationType === 'button' && copyTableTemplate.operationColumn.iconList && copyTableTemplate.operationColumn.iconList.length > 0">
                <span v-for="icon in copyTableTemplate.operationColumn.iconList" :key="icon.code">
                  <span v-if="iconable(scope.row, icon.code)">
                    <el-button
                      class="aos-table-form-inline-button"
                      type="text"
                      :text-type="icon.type ? icon.type : 'primary'"
                      v-auth="icon.auth"
                      
                      @click="handleIconClick(icon.code,scope)">{{icon.title}}</el-button>
                  </span>
                </span>
                <el-dropdown trigger="click" v-if="copyTableTemplate.operationColumn.moreIconList" @command="function (command) {handleIconClick(command,scope)}">
                  <el-button type="text">
                    更多<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <span v-for="item in copyTableTemplate.operationColumn.moreIconList" :key="item.code">
                      <span v-if="iconable(scope.row, item.code)">
                        <el-dropdown-item
                          :class="'aos-table-form-inline__operation-button--'+ (item.type ? item.type : 'primary')"
                          :command="item.code"
                          v-auth="item.auth"
                          >{{item.title}}</el-dropdown-item>
                      </span>
                    </span>
                    </el-dropdown-menu>
                </el-dropdown>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          class="aos-table-form-inline-pagination"
          v-if="showPagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
          :current-page="currentPage"
          :page-sizes="[5,10,20,30,40,50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
</div>
</template>
<script>
import ElTable from '../../table';
import ElPagination from '../../pagination';
import AosForm from '../../aos-form'
import {addResizeListener,removeResizeListener} from 'aos-element/src/utils/resize-event.js'
import isEqual from 'lodash/isEqual';
import cloneDeep from 'lodash/cloneDeep';
import debounce from 'throttle-debounce/debounce';
import findIndex from 'lodash/findIndex'
import InlineDate from 'aos-element/packages/aos-table/src/inline-date'
import InlineInput from 'aos-element/packages/aos-table/src/inline-input.vue'
import InlineNumberRange from 'aos-element/packages/aos-table/src/inline-number-range'
import AosTableItem from './table-item.vue'
import {
  idCard,
  email,
  cellPhone,
  phoneNoRequired,
  phone,
  number,
  numberDecimal,
  vin,
  businessLicence,
  nameType,
  postalCode,
  money
} from './rules.js'
export default {
  name: 'AosTableFormInline',
  components: {
    ElTable,
    ElPagination,
    AosForm,
    InlineDate,
    InlineNumberRange,
    InlineInput,
    AosTableItem
  },
  props:{
    // table绑定的数据
    data: {
      type: Array,
      required: true,
      default: function(){
        return []
      }
    },
    // table构成列属性
    tableTemplate: {
      type: Object,
      required: true
    },
    // 是否显示分页
    showPagination: {
      type: Boolean,
      default: true
    },
    // 分页的当前页
    currentPage: {
      type: Number,
      default: 1
    },
    // 分页的页的数量
    pageSize: {
      type: Number,
      default: 10
    },
    // 当前table数据总共的数量
    total: {
      type: Number,
      default: 0
    },
    showType: {
      type: String,
      default: 'table'
    },
    fixedHead: {
      type: Boolean,
      default: false
    },
    maxTableHeight: {
      type: Number
    },
    // 当使用复选框是设置复选框是否可选
    selectable: {
      type: Function,
      default: function () {
        return function () { return true }
      }
    },
    // 根据条件设置icon显示或者隐藏
    iconable: {
      type: Function,
      default: function () {
        return function () {
          return true
        }
      }
    },
    // 是否开启行内搜索
    inlineSearch: {
      type: Boolean,
      default: false
    },
    // 是否显示设置列操作
    showSetting: {
      type: Boolean,
      default: true
    },
    fit: {
      type: Boolean,
      default: true
    },

    border: Boolean,
    stripe: {
      type: Boolean,
      default: true
    },

    rowKey: [String, Function],

    context: {},

    showHeader: {
      type: Boolean,
      default: true
    },

    showSummary: Boolean,

    sumText: String,

    summaryMethod: Function,

    rowClassName: [String, Function],

    rowStyle: [Object, Function],

    cellClassName: [String, Function],

    cellStyle: [Object, Function],

    headerRowClassName: [String, Function],

    headerRowStyle: [Object, Function],

    headerCellClassName: [String, Function],

    headerCellStyle: [Object, Function],

    highlightCurrentRow: Boolean,

    currentRowKey: [String, Number],

    emptyText: String,

    expandRowKeys: Array,

    defaultExpandAll: Boolean,

    defaultSort: Object,

    tooltipEffect: String,

    spanMethod: Function,

    selectOnIndeterminate: {
      type: Boolean,
      default: true
    },

    indent: {
      type: Number,
      default: 16
    },

    treeProps: {
      type: Object,
      default() {
        return {
          hasChildren: 'hasChildren',
          children: 'children'
        };
      }
    },

    lazy: Boolean,

    load: Function,
    showRefresh: {
      type: Boolean,
      default: false
    },
    showCrossSelection: {
      type: Boolean,
      default: false
    },
    inlineSearchData: {},
    // 行内编辑类型
    editMode: {
      type: String,
      default: 'row',
      validator: function (val) {
        return ['row', 'cell'].includes(val)
      }
    },
    // 行内编辑触发方式
    editTrigger: {
      type: String,
      default: 'click',
      validator: function (val) {
        return ['click', 'dbclick'].includes(val)
      }
    },
    // 行内保存方法
    inlineSave: {
      type: Function
    },
    // 是否显示复制
    showInlineCopy: {
      type: Boolean,
      default: false
    },
    showInlineAdd: {
      type: Boolean,
      default: true
    },
    showInlineDelete: {
      type: Boolean,
      default: false
    },
    inlineDelete: {
      type: Function
    },
    // 整个表单是否可编辑
    editable: {
      type: Boolean,
      default: false
    },
    inlineEditable: {
      type: Function,
      default: function () {
        return true
      }
    },
    // 会产生副作用的字段以及初始值，主要用于复制功能
    sideEffectData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data(){
    return {
      tableHeight: null,
      refLableList: [],
      refValueDataListObject: {},
      copyData: [],
      checkAll: false,
      copyTableTemplate: {},
      isIndeterminate: false,
      allItem: [],
      currentTableTemplate: [],
      crossPageSelect: false,
      currentCrossSelectList: [],
      currentSelectionList: [],
      rotate: 0,
      handleDebounceRefresh: '', 
      copySearchData: {},
      copyTableItemObject: {},
      handleInlineSearchChangeEmit: '',
      lastCondition: '',
      operationColumnMinWidth: 120,
      currentStringData: '',
      currentData: {},
      currentScope: {
        index: null,
        data: null
      },
      edit: false,
      operationType: '',
      copyIndex: '',
      inlineFormData: {},
      formRules: [],
      flag: true,
      idCard,
      email,
      cellPhone,
      phoneNoRequired,
      phone,
      number,
      numberDecimal,
      vin,
      businessLicence,
      nameType,
      postalCode,
      money,
      currentTemplate: '',
      defdocEmitChangeDebounce: '',
      refEmitChangeDebounce: '',
      inputNumberEmitDebounce: '',
      ocrEmitSuccessDebounce: '',
      ocrEmitErrorDebounce: '',
      moneyEmitChangeDebounce: '',
      cityEmitChangeDebounce: '',
      scrollLeft: 0,
      scrollTop: 0,
      canGetScroll: true
    };
  },
  computed: {
    // copyTableTemplate() {
    //   return this.tableTemplate;
    // },
    // refPropList () {
    //   let refPropList = []
    //   if (this.tableTemplate && this.tableTemplate.tableItem) {
    //     this.tableTemplate.tableItem.forEach(item => {
    //       if (item.type === 'ref') {
    //         refPropList.push(item)
    //       }
    //     });
    //   }
    //   return refPropList
    // },
    showCrossContainer () {
      return this.showRefresh || this.showCrossSelection || this.$slots.headerLeft || this.$slots['header-left']
    },
    showExplainContainer () {
      return this.inlineSearch || this.showSetting || (this.copyTableTemplate.operationColumn && this.copyTableTemplate.operationColumn.showOperation && this.copyTableTemplate.operationColumn.operationType === 'icon' && this.copyTableTemplate.operationColumn.iconList && this.copyTableTemplate.operationColumn.iconList.length > 0)
    },
    showExplain () {
      return this.showCrossContainer || this.showExplainContainer
    }
  },
  watch: {
    fixedHead(val, oldVal) {
      if (val && !this.$_.isEqual(val, oldVal)) {
        if (this.maxTableHeight) {
          this.tableHeight = this.maxTableHeight;
        } else {
          addResizeListener(this.$refs.aosTableContainer.parentElement.parentElement, this.resizeTableHeight);
        }
      }
    },
    // data: {
    //   handler: function(val, oldVal) {
    //     if (val && Array.isArray(val) && !this.$_.isEqual(val, oldVal)) {
    //       this.translateRef(val)
    //     }
    //   },
    //   deep: true,
    //   immediate: true
    // },
    tableTemplate: {
      handler: function (val, oldVal) {
        if (val && !this.$_.isEqual(val, oldVal)) {
          this.currentTemplate = this.$_.cloneDeep(val);
          this.getCopyTableFormInlineTemplate(val)
        }
      },
      deep: true,
      immediate: true
    },
    currentData: {
      handler: function (val) {
        this.currentStringData = JSON.stringify(val)
      },
      deep: true
    }
  },
  methods: {
    getCopyTableFormInlineTemplate (val) {
      const setProp = (item) => {
        const prop = item.searchProp ? item.searchProp : item.prop
        this.$set(this.inlineFormData, item.prop, '')
        this.$set(this.copySearchData, prop, '')
        this.$set(this.copyTableItemObject, prop, item)
        if (item.prop && item.rules && Array.isArray(item.rules)) {
          this.formRules.push({
            prop: item.prop,
            rules: item.rules
          })
        }
      }
      this.copyTableTemplate = this.$_.cloneDeep(val);
      this.copyTableTemplate.tableItem.forEach(item => {
        if (!item.hasOwnProperty('hide')) {
          this.$set(item, 'hide', false)
        }
        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
          item.children.forEach(child => {
            setProp(child)
          })
        } else {
          setProp(item)
        }
      })
      if (this.copyTableTemplate.operationColumn && !this.copyTableTemplate.operationColumn.operationType) {
        this.copyTableTemplate.operationColumn.operationType = 'icon'
      }
      if (this.copyTableTemplate.operationColumn && this.copyTableTemplate.operationColumn.operationType === 'button' && this.copyTableTemplate.operationColumn.iconList) {
        const iconList = this.copyTableTemplate.operationColumn.iconList
        
        if (iconList.length > 3) {
          this.copyTableTemplate.operationColumn.moreIconList = iconList.splice(3)
          let allTitle = ''
          iconList.forEach(item  => {
            allTitle += item.title
          })
          this.operationColumnMinWidth = (allTitle.length + 4) * 12 + 82 + 24
        } else {
          let allTitle = ''
          iconList.forEach(item  => {
            allTitle += item.title
          })
          this.operationColumnMinWidth = (allTitle.length + 4) * 12 + (iconList.length+3) * 8 
        }
      }
    },
    validateFunction (flag) {
      if (typeof flag === 'string') {
        this.$message({
          type: 'warning',
          message: flag
        })
        this.flag = this.flag && false
      } else {
        this.flag = this.flag && true
      }
    },
    validate () {
      this.flag = true
      for (let i = 0; i < this.formRules.length; i++) {
        if (this.formRules[i]) {
          for (let j = 0; j < this.formRules[i].rules.length; j++) {
            let prop = this.formRules[i].prop
            if (this.formRules[i].rules[j].required) {
              if (this.currentData[prop] !== 0 && !this.currentData[prop]) {
                this.$message({
                  type: 'warning',
                  message: this.formRules[i].rules[j].message
                })
                this.flag = false
                return this.flag
              }
            }
            if (this.formRules[i].rules[j].validator) {
              switch (this.formRules[i].rules[j].validator) {
                case 'idCard':
                  this.idCard(this.currentData[prop], this.validateFunction)
                  break
                case 'email':
                  this.email(this.currentData[prop], this.validateFunction)
                  break
                case 'phone':
                  this.phone(this.currentData[prop], this.validateFunction)
                  break
                case 'cellPhone':
                  this.cellPhone(this.currentData[prop], this.validateFunction)
                  break
                case 'phoneNoRequired':
                  this.phoneNoRequired(
                    this.currentData[prop],
                    this.validateFunction
                  )
                  break
                case 'number':
                  this.number(this.currentData[prop], this.validateFunction)
                  break
                case 'name':
                  this.nameType(this.currentData[prop], this.validateFunction)
                  break
                case 'vin':
                  this.vin(this.currentData[prop], this.validateFunction)
                  break
                case 'numberDecimalType':
                  this.numberDecimal(
                    this.currentData[prop],
                    this.validateFunction
                  )
                  break
                case 'businessLicence':
                  this.businessLicence(
                    this.currentData[prop],
                    this.validateFunction
                  )
                  break
                case 'postalCode':
                  this.postalCode(
                    this.currentData[prop],
                    this.validateFunction
                  )
                  break
                case 'money':
                  this.money(
                    this.currentData[prop],
                    this.validateFunction
                  )
                  break
                default:
                  break
              }
            }
          }
        }
      }
      return this.flag
    },
    handleInlineEditAble (rowData) {
      return this.currentStringData === JSON.stringify(rowData)
    },
    handleInlineAdd () {
      const index = findIndex(this.data, this.currentData)
      if (this.operationType === 'add' && Object.keys(this.currentData).length > 0) return
      if (this.currentScope.data && !isEqual(this.currentData, this.currentScope.data)) {
        this.$confirm('当前行数据已经发生改变，是否保存', '提示').then(async () => {
          try {
            await this.inlineSaveFunction(this.currentData)
            this.handleInlineEdit(this.currentData)
          } catch (error) {
          }
        }).catch(() => {
          if (this.operationType === 'edit') {
            this.resetScopeData()
          } else if (this.operationType === 'copy' || this.operationType === 'add') {
            this.handleInlineCancle()
            this.currentScope = {}
          }
          this.addInlineData()
        })
      } else {
        if (this.operationType === 'edit') {
          this.resetScopeData()
        } else if (this.operationType === 'copy' || this.operationType === 'add') {
          this.handleInlineCancle()
          this.currentScope = {}
        }
        this.addInlineData()
      }
    },
    addInlineData () {
      this.operationType = 'add'
      const addData = cloneDeep(this.inlineFormData)
      this.data.unshift(addData)
      this.currentStringData = JSON.stringify(addData)
      this.edit = true
      const scopeData = {
        index: 0,
        data: cloneDeep(addData)
      }
      this.copyIndex = 0
      this.currentScope = cloneDeep(scopeData)
      this.currentData = {}
      this.currentData = addData
      this.$emit('inline-edit', addData)
    },
    handleInlineEdit (rowData) {
      this.operationType = 'edit'
      this.currentStringData = JSON.stringify(rowData)
      const index = findIndex(this.data, rowData)
      const scopeData = {
        index: index,
        data: cloneDeep(rowData)
      }
      this.currentScope = cloneDeep(scopeData)
      this.currentData = {}
      this.currentData = rowData
      this.edit = true
      this.$emit('inline-edit', rowData)
    },
    handleInlineCopy (rowData) {
      if (this.operationType === 'copy' && Object.keys(this.currentData).length > 0) return
      if (this.currentScope.data && !isEqual(this.currentData, this.currentScope.data)) {
        this.$confirm('当前行数据已经发生改变，是否保存', '提示').then(async () => {
          try {
            await this.inlineSaveFunction(this.currentData)
            this.inlineCopy(rowData)
          } catch (error) {
          }
        }).catch(() => {
          if (this.operationType === 'edit') {
            this.resetScopeData()
          } else if (this.operationType === 'copy' || this.operationType === 'add') {
            this.handleInlineCancle()
            this.currentScope = {}
          }
          this.inlineCopy(rowData)
        })
      } else {
        if (this.operationType === 'edit') {
          this.resetScopeData()
        } else if (this.operationType === 'copy' || this.operationType === 'add') {
          this.handleInlineCancle()
          this.currentScope = {}
        }
        this.inlineCopy(rowData)
      }
    },
    inlineCopy (rowData) {
      const index = findIndex(this.data, rowData)
      this.operationType = 'copy'
      const data = cloneDeep(rowData);
      this.copyIndex = index + 1
      if (data.id) {
        data.id = ''
      }
      if (this.sideEffectData && Object.keys(this.sideEffectData).length > 0) {
        Object.keys(this.sideEffectData).forEach(key => {
          if (data.hasOwnProperty(key)) {
            data[key] = this.sideEffectData[key]
          }
        })
      }
      const scopeData = {
        index: this.copyIndex,
        data: cloneDeep(data)
      }
      this.currentScope = cloneDeep(scopeData)
      this.data.splice(this.copyIndex, 0, data)
      this.currentStringData = JSON.stringify(data)
      this.currentData = this.data[this.copyIndex]
      this.edit = true
      this.$emit('inline-edit', data)
    },
    async inlineSaveFunction (nextRow) {
      return new Promise(async (resolve, reject) => {
        try {
          if (this.inlineSave) {
            if (this.validate()) {
              const newData = await this.inlineSave(cloneDeep(this.currentData))
              const index = this.currentScope.index
              this.data.splice(index, 1, newData)
              this.handleInlineEdit(nextRow)
              this.$emit('inline-save-success',  cloneDeep(this.currentData))
              resolve(newData)
            }
          } else {
            this.$emit('inline-save', cloneDeep(this.currentData))
            resolve()
          }
        } catch (error) {
          this.$emit('inline-save-fail', cloneDeep(this.currentData))
          reject()
        }
      })
    },
    async handleInlineSave (scope) {
      if (this.validate()) {
        // this.$confirm('确认保存', '提示').then(async () => {
          await this.inlineSaveFunction(this.data[scope.$index])
          this.currentStringData = ''
          this.edit = false
          this.currentScope = {}
          this.operationType = ''
        // })
      }
    },
    handleInlineDelete (scope) {
      if (this.inlineDelete && this.inlineDelete.then) {}
      return new Promise((resolve, reject) => {
        this.$confirm('确认删除', '提示').then(async () => {
          try {
            await this.inlineDelete(scope.row)
            const index = scope.$index
            this.data.splice(index, 1)
            resolve(true)
            this.$emit('inline-delete-success', scope)
          } catch (error) {
            this.$emit('inline-delete-error',scope, error)
            reject(error)
          }
        })
      })
    },
    inlineDeleteFunction () {},
    handleInlineCancle () {
      if (this.operationType === 'edit') {
        this.resetScopeData()
      } else if (this.operationType === 'copy' || this.operationType === 'add') {
        this.data.splice(this.copyIndex, 1)
      }
      this.currentStringData = ''
      this.edit = false
      this.currentScope = {}
      this.operationType = ''
    },
    resetInlineStatus () {
      this.currentStringData = ''
      this.edit = false
      this.currentScope = {}
      this.currentData = {}
    },
    resetScopeData () {
      if (this.currentScope) {
        const index = this.currentScope.index
        this.data.splice(index, 1, cloneDeep(this.currentScope.data))
        this.currentData = {}
      }
    },
    setCurrentDataString () {
      this.currentStringData = JSON.stringify(this.currentData)
    },
    handleInlineSearchReset () {
      Object.keys(this.copySearchData).forEach(item => {
        this.copySearchData[item] = ''
        const refsList = this.$refs[item + '-inline-search']
        if (refsList && Array.isArray(refsList) && refsList.length > 0) {
          refsList.forEach(refsItem => {
            if (refsItem.reset) {
              refsItem.reset()
            }
          })
        }
      })
      this.handleInlineSearchChangeEmit()
    },
    inlineSearchEmit () {
      let conditionStr = this.buildSearchCondition()
      const condition = conditionStr ? conditionStr : ''
      if (this.lastCondition === condition) {
        return
        // this.handleInlineSearchChangeEmit(condition)
      }
      this.lastCondition = condition
      this.$emit('inline-search', conditionStr, cloneDeep(this.copySearchData))
    },
    handleInlineSearchChange (data, item) {
      const prop = item.searchProp ? item.searchProp : item.prop
      this.copySearchData[prop] = data
      this.handleInlineSearchChangeEmit()
    },
    buildSearchCondition () {
      let sqlList = []
      let type = ''
      Object.keys(this.copySearchData).forEach(item => {
        if (this.copyTableItemObject[item]) {
          type = this.copyTableItemObject[item].searchType || (this.copyTableItemObject[item].type ? this.copyTableItemObject[item].type : 'default')
        }
        if (this.copySearchData[item]) {
          const sql = this.sqlMaker(type,this.copyTableItemObject[item],this.copySearchData[item])
          if (Array.isArray(sql)) {
            sqlList = sqlList.concat(sql)
          } else {
            sqlList.push(sql)
          }
        }
      })
      if (sqlList.length <= 0) {
        return ''
      } else {
        const condition = JSON.stringify(sqlList)
        return condition;
      }
    },
    sqlMaker (type, item, value) {
      const prop = item.searchProp ? item.searchProp : item.prop
      let searchData = {
        fieldName: prop,
        value: '',
        connector: ''
      }
      switch (type) {
        case 'defdoc':
          if (item.multiple) {
            const data = value.split(',')
            searchData.value = data
          } else {
            searchData.value = [value]
          }
          searchData.connector = 'in'
          break;
        case 'ref':
          if (item.multiple) {
            const data = value.split(',')
            searchData.value = data
          } else {
            searchData.value = value
          }
          searchData.connector = 'in'
          break;
        case 'date':
          const dateData = cloneDeep(searchData)
          searchData = []
          if (value[0]) {
            const data = cloneDeep(dateData)
            data.value = value[0]
            data.connector = '>='
            data.format = item.format || 'yyyy-mm-dd hh24:mi:ss'
            searchData.push(data)
          }
          if (value[1]) {
            const data = cloneDeep(dateData)
            data.value = value[1]
            data.connector = '<='
            data.format = item.format || 'yyyy-mm-dd hh24:mi:ss'
            searchData.push(data)
          }
          break;
        case 'number-range':
        case 'money':
          const numberData = cloneDeep(searchData)
          searchData = []
          if (value[0]) {
            const data = cloneDeep(numberData)
            data.value = value[0]
            data.connector = '>='
            searchData.push(data)
          }
          if (value[1]) {
            const data = cloneDeep(numberData)
            data.value = value[1]
            data.connector = '<='
            searchData.push(data)
          }
          break;
        case 'input':
          searchData.value = value
          searchData.connector = 'like'
          break;
        default:
          searchData.value = value
          searchData.connector = 'like'
          break;
      }
      return searchData;
    },
    handleDeleteCrossItem (scope) {
      this.$confirm('确认删除当前数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.currentCrossSelectList.splice(scope.$index, 1)
      })
    },
    handleSettingItem () {},
    crossPageSelectChange (value) {
      if (!value) {
        this.currentCrossSelectList = []
      }
    },
    handleCheckAllChange (val) {
      const propList = []
      this.copyTableTemplate.tableItem.forEach(item => {
        item.hide = !item.hide
        propList.push(item.prop)
      })
      this.allItem = val ? propList : []
      this.isIndeterminate = false;
    },
    handleItemTypeChange(index) {
      this.copyTableTemplate.tableItem[index].hide = !this.copyTableTemplate.tableItem[index].hide
    },
    handleItemChange (value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.copyTableTemplate.tableItem.length
      this.isIndeterminate = checkedCount > 0 && checkedCount === this.copyTableTemplate.tableItem.length
    },
    handleSelect(selection, row) {
      // console.log('select', selection, row)
    },
    // 多选框选择事件TODO:翻页触发事件问题
    handleSelectionChange(data){
      this.currentSelectionList = cloneDeep(data)
      const selectionList = cloneDeep(data)
      if (this.crossPageSelect) {
        const list = cloneDeep(this.currentCrossSelectList)
        selectionList.forEach(item => {
          let flag = true
          for (let index = 0; index < this.currentCrossSelectList.length; index++) {
            const element = this.currentCrossSelectList[index];
            if (isEqual(element, item)) {
              flag = false
              break
            }
          }
          if (flag) {
            list.push(item)
          }
        })
        this.$emit('table-selection-change', list);
      } else {
        this.$emit('table-selection-change', data);
      }
    },
    handleSortChange (data) {
      this.$emit('sort-change', data)
    },
    handleCheckData (row) {
      const index = findIndex(this.data, row)
      if (this.currentScope.data && index !== this.currentScope.index) {
        if (!isEqual(this.currentData, this.currentScope.data)) {
          this.$confirm('当前行数据已经发生改变，是否保存', '提示').then(async () => {
            try {
              await this.inlineSaveFunction(row)
              this.handleInlineEdit(row)
            } catch (error) {
            }
          }).catch(() => {
            if (this.operationType === 'edit') {
              this.resetScopeData()
            } else if (this.operationType === 'copy' || this.operationType === 'add') {
              this.handleInlineCancle()
              this.currentScope = {}
            }
            this.handleInlineEdit(row)
          })
        } else {
          if (this.operationType === 'edit') {
            this.resetScopeData()
            this.handleInlineEdit(row)
          } else if (this.operationType === 'copy' || this.operationType === 'add') {
            this.handleInlineCancle()
            this.currentScope = {}
          }
          this.handleInlineEdit(row)
        }
      } else {
        this.handleInlineEdit(row)
      }
    },
    handleRowClick(row,column,event, $index){
      if (this.editable) {
        if (this.editMode === 'row' && this.editTrigger === 'click') {
          if (this.currentScope && this.currentScope.index === $index) {
            return
          }
          this.handleCheckData(row)
        }
      }
      this.$emit('table-row-click',row,column,event);
    },
    handleRowdbclick (row, column, event, $index) {
      if (this.editable) {
        if (this.editMode === 'row' && this.editTrigger === 'dbclick') {
          if (this.currentScope && this.currentScope.index === $index) {
            return
          }
          this.handleCheckData(row)
        }
      }
      this.$emit('row-dblclick', row, column, event)
    },
    handleTableCurrentChange (currentRow, oldCurrentRow) {
      this.$emit('current-change', currentRow, oldCurrentRow)
    },
    handleScroll (scrollLeft, scrollTop) {
      if (this.canGetScroll) {
        this.scrollLeft = scrollLeft
        this.scrollTop = scrollTop
      }
    },
     formatDatePickerValue (value, item) {
      if (!value) return ''
      let valueFormat = item.attrs && item.attrs['value-format']
      if (!valueFormat) {
        valueFormat = 'yyyy-MM-dd hh:mm:ss'
      }
      if (item.attrs && item.attrs.type === 'date') {
        valueFormat = 'yyyy-MM-dd'
      }
      return this.$time.formatTime(value, valueFormat)
    },
    formatDate (date) {
      let formatDate = date
      if (date === '长期' || date === '无' || date === '长期') {
        formatDate = '2099-12-31'
      } else {
        formatDate = date.substring(0,4) + '-' + date.substring(4,6) + '-' + date.substring(6)
      }
      return formatDate
    },
    formatBusinessLicenseDate (date) {
      let formatDate = date
      if (date === '长期' || date === '无' || date === '长期') {
        formatDate = '2099-12-31'
      } else {
        formatDate = date.substring(0,4) + '-' + date.substring(5,7) + '-' + date.substring(8,10)
      }
      return formatDate
    },
    handleInlineOcr (item, type, response, file, fileList) {
      const data = response.data
      if (!response) {
        this.$message({
          type: 'error',
          message: this.ocrObject[item.attrs.ocrType]+'OCR识别出错'
        })
      }
      if (item.attrs.ocrType === 'idCardFront') {
        data.birth = this.formatDate(data.birth)
      }
      if (item.attrs.ocrType === 'idCardBack') {
        data.expiryDate = this.formatDate(data.expiryDate)
        data.issuingDate = this.formatDate(data.issuingDate)
      }
      if (item.attrs.ocrType === 'bank') {
        data.bankCardNumber = data.bankCardNumber.split(' ').join('')
      }
      if (item.attrs.ocrType === 'businessLicense') {
        data.approvalDate = this.formatBusinessLicenseDate(data.approvalDate)
        data.dateOfEstablishment = this.formatBusinessLicenseDate(data.dateOfEstablishment)
        data.inDate = this.formatBusinessLicenseDate(data.inDate)
        data.registeredCapital = data.registeredCapital.slice(0, -2)
      }
      if (item.methods && item.methods[type]) {
        this.$emit(
          "form-" + item.prop + "-ocr-" + item.methods[type],response,
          cloneDeep(this.currentData),
          item.prop,
          file,
          fileList
        );
      }
    },
    formHandleEmit(item, type) {
      if (item.methods && item.methods[type]) {
        this.$emit(
          "form-" + item.prop + "-" + item.methods[type],
          cloneDeep(this.currentData),
          item.prop
        );
      } else {
        }
      this.setCurrentDataString()
      this.$emit(type, cloneDeep(this.currentData), item.prop)
    },
    /**
     * @description: 设置表单对应项的属性值
     * @param {type} prop prop属性, attes 属性, value 属性值, type 是否是列item为列,默认为attrs属性值attrsItem为attrs里面的对象属性
     * @return: 
     */
    setItemProp(prop,attrs,value,type){
      let length = this.copyTableTemplate.tableItem.length;
      for(let i = 0;i<length;i++){
        if(this.copyTableTemplate.tableItem[i].prop === prop){
          if(!type || type === 'attrs'){
            if(!this.copyTableTemplate.tableItem[i].attrs){
              this.$set(this.copyTableTemplate.tableItem[i],'attrs',{});
            }
            this.$set(this.copyTableTemplate.tableItem[i].attrs,attrs,value);
          } else if(type === 'item'){
            this.$set(this.copyTableTemplate.tableItem[i],attrs,value);
          } else if(type === 'attrsItem'){
            let key = value.key;
            let values = value.value;
            let attrsItem = value.attrsItem;
            if (this.copyTableTemplate.tableItem[i].attrs && this.copyTableTemplate.tableItem[i].attrs[attrsItem] && this.copyTableTemplate.tableItem[i].attrs[attrsItem][key]) {
              this.copyTableTemplate.tableItem[i].attrs[attrsItem][key] = values
            } else {
              this.$set(this.copyTableTemplate.tableItem[i].attrs[attrsItem],key,values);
            }
          }
          break;
        }
      }
    },
    // 设置form规则
    setItemRules(prop,rule,type){
      let length = this.currentTemplate.length;
      for(let i = 0;i<length;i++){
        if(this.currentTemplate[i].prop === prop){
          if(type){
            if(!this.currentTemplate[i].rules){
              this.$set(this.currentTemplate[i],'rules',[]);
            }
            if(Object.prototype.toString.call(rule) === '[object Array]'){
              let addRulesIdList = [];
              let rules = this.currentTemplate[i].rules;
              let ruleLength = rules.length;
              rule.forEach((item) => {
                addRulesIdList.push(item.id);
              });
              if(addRulesIdList.length > 0){
                for(let j = 0;j<ruleLength;j++){
                  if(addRulesIdList.indexOf(rules.id)> -1){
                    rules.splice(j,1);
                  }
                }
              }
              this.currentTemplate[i].rules = this.currentTemplate[i].rules.concat(rule);
            } else if(Object.prototype.toString.call(rule) === '[object Object]'){
              const copyRules = cloneDeep(this.currentTemplate[i].rules)
              this.currentTemplate[i].rules = copyRules.filter(item => {
                return item.id !== rule.id
              })
              // let rules = this.currentTemplate[i].rules;
              // let ruleLength = rules.length;
              // for(let j = 0;j<ruleLength;j++){
              //   if(rules[j].id && rules[j].id === rule.id){
              //     rules.splice(j,1);
              //     break;
              //   }
              // }
              this.currentTemplate[i].rules.push(rule);
            }
          } else {
            if(this.currentTemplate[i].rules && this.currentTemplate[i].rules.length > 0){
              if(Object.prototype.toString.call(rule) === '[object Array]'){
                let removeRulesIdList = [];
                let rules = this.currentTemplate[i].rules;
                let ruleLength = rules.length;
                rule.forEach((item) => {
                  removeRulesIdList.push(item.id);
                });
                if(removeRulesIdList.length > 0){
                  for(let j = 0;j<ruleLength;j++){
                    if(removeRulesIdList.indexOf(rules.id)> -1){
                      rules.splice(j,1);
                    }
                  }
                }
              } else if(Object.prototype.toString.call(rule) === '[object Object]'){
                let rules = this.currentTemplate[i].rules;
                let ruleLength = rules.length;
                for(let j = 0;j<ruleLength;j++){
                  if(rules[j].id && rules[j].id === rule.id){
                    rules.splice(j,1);
                    break;
                  }
                }
              }
            }
          }
          break;
        }
      }
      const sourceTemplate = cloneDeep(this.copyTableTemplate.tableItem)
      for (let index = 0; index < sourceTemplate.length; index++) {
        const element = sourceTemplate[index];
        if (element.prop === prop) {
          const sourceRules = element.rules ? element.rules : []
          let newSourceRules = []
          if (isArray(rule)) {
            if (type) {
              newSourceRules = sourceRules.filter(sourceItem => {
                let flag = true
                if (sourceItem.id) {
                  rule.forEach(targetItem => {
                    if (targetItem.id === sourceItem.id) {}
                    flag = false
                  })
                }
                return flag
              })
              const targetRules = newSourceRules.concat(rule)
              this.$set(element, 'rules', targetRules)
            } else {
              const newRules = sourceRules.filter(sourceItem => {
                let flag = true
                if (sourceItem.id) {
                  rule.forEach(targetItem => {
                    if (targetItem.id === sourceItem.id) {}
                    flag = false
                  })
                }
                return flag
              })
              this.$set(element, 'rules', newRules)
            }
          } else if (typeof rule === 'object') {
            if (type) {
              const newSourceRules = sourceRules.filter(item => {
                return !item.id || (item.id && item.id !== rule.id)
              })
              newSourceRules.push(rule)
              this.$set(element, 'rules', newSourceRules)
            } else {
               const newRules = sourceRules.filter(item => {
                return !item.id || item.id !== rule.id
              })
              this.$set(element, 'rules', newRules)
            }
          }
          break;
        }
      }
     this.getCopyTableFormInlineTemplate(sourceTemplate);
    },
    /**
     * 设置字段显示隐藏
     * prop: 字段
     * value: 值
     */
    setItemShow(prop,value){
      if(prop && value !== null && value !== undefined && value !== ''){
        let flag = false;
        if(!value){
          let length = this.copyTableTemplate.tableItem.length;
          for(let i = 0;i<length;i++){
            if(this.copyTableTemplate.tableItem[i].prop === prop){
              this.copyTableTemplate.tableItem[i].showItem = false
              this.copyTableTemplate.tableItem.splice(i,1);
              flag = true;
              break;
            }
          }
        } else {
          const currentTemplatelength = this.currentTemplate.length;
          const copyTemplatelength = this.copyTableTemplate.tableItem.length;
          let hasProp = false;
          for(let i = 0;i<copyTemplatelength;i++){
            if(this.copyTableTemplate.tableItem[i].prop === prop){
              hasProp = true;
              flag = true
              break;
            }
          }
          if (!hasProp) {
            for(let i = 0;i<currentTemplatelength;i++){
              if(this.currentTemplate[i].prop === prop){
                const item = cloneDeep(this.currentTemplate[i])
                item.showItem = true
                this.copyTableTemplate.tableItem.splice(i,0,item);
                flag = true;
                break;
              }
            }
          }
        }
        if(!flag){
          console.log("setFormItemShow方法,当前Form表单没有传入的属性:",prop)
        }
      } else {
        console.log("setFormItemShow方法,请传入prop和value")
      }
    },
    handleInputNumberEmit (item, type, data, oldValue) {
      if(type === 'change'){
        this.currentData[item.prop] = data;
        this.setCurrentDataString()
      }
      if(item.methods && item.methods[type]){
        if (type === 'change') {
          this.inputNumberEmitDebounce(item, type, data, oldValue)
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData), item.prop, data, oldValue);
        }
      }
      this.$emit(type, cloneDeep(this.currentData), item.prop)
    },
    inputNumberEmit(item, type, data, oldValue) {
      this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData), item.prop, data, oldValue);
    },
    /**
     * 参照选择之后触发
     * refData: 获取到的参照的数据
     * item: 当前组件数据
     * type: 当前方法
     * 返回事件: 
     */
    handleRefEmit(data,item,type,emitFullData){
      if(type === 'change'){
        this.currentData[item.prop] = data;
        this.setCurrentDataString()
      }
      if(item.methods && item.methods[type]){
        if (type === 'change') {
          this.refEmitChangeDebounce(data,item,type,emitFullData)
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,data,emitFullData);
        }
      }
        this.$emit(type, cloneDeep(this.currentData), item.prop,emitFullData)
    },
    refEmit (data,item,type,emitFullData) {
      this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,data,emitFullData);
    },
    handleRefLeaseEmit (data, item, type) {
      if(type === 'change'){
        this.currentData[item.prop] = data;
        this.setCurrentDataString()
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,data);
      }
    },
    // 设置倒计时停止
    handleStopCountTime(prop){
      this.$refs[prop + '-count-time-ref'][0].stopCount();
    },
    // 设置倒计时开始
    handleStartCountTime(prop){
      this.$refs[prop + '-count-time-ref'][0].startCount();
    },
    handleOcr (item, type, data) {
      if (type === 'success') {
        this.$set(this.currentData, [item.prop],data.fileId)
        this.setCurrentDataString()
      }
      if(item.methods && item.methods[type]){
        if (type === 'success') {
          this.ocrEmitSuccessDebounce(item, type, data)
        } else if (type === 'error') {
          this.ocrEmitErrorDebounce(item, type, data)
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type], cloneDeep(this.currentData),item.prop, data);
        }
      }
      this.$emit(type, cloneDeep(this.currentData), item.prop, data)
    },
    ocrEmit (item, type, data) {
      this.$emit('form-' + item.prop + '-' + item.methods[type], cloneDeep(this.currentData),item.prop, data);
    },
    /**
     * 字典事件
     */
    handleDefdocEmit(data,item,type,emitFullData){
      if(type === 'change'){
        this.currentData[item.prop] = data;
        this.setCurrentDataString()
      }
      if(item.methods && item.methods[type]){
        if (type === 'change') {
          this.defdocEmitChangeDebounce(data,item,type,emitFullData)
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,data,emitFullData);
        }
      }
      this.$emit(type, cloneDeep(this.currentData), item.prop,emitFullData)
    },
    defdocEmitChange (data,item,type,emitFullData) {
      this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,data,emitFullData);
    },
    // money事件
    handleMoneydocEmit(data,item,type, iconActive){
      if(type === 'change' || type === 'blur'){
        this.currentData[item.prop] = data;
        this.setCurrentDataString()
      }
      if(item.methods && item.methods[type]){
        if (type === 'change') {
          this.moneyEmitChangeDebounce(data,item,type, iconActive)
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,data, iconActive);
        }
      }
      this.$emit(type, cloneDeep(this.currentData), item.prop, data, iconActive)
    },
    moneyEmitChange (data,item,type, iconActive) {
      this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,data, iconActive);
    },
    // markdown事件
    handleMarkdownEditorEmit(event,item,value,type){
      if(type === 'change'){
        this.currentData[item.prop] = value;
        this.setCurrentDataString()
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,value);
      }
      this.$emit(type, cloneDeep(this.currentData), item.prop)
    },
    handleCityEmit(item,value,type){
      if(item.methods && item.methods[type]){
        if (type === 'change') {
          this.cityEmitChangeDebounce(item,value,type)
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,value);
        }
      }
      this.setCurrentDataString()
    },
    cityEmitChange (item,value,type) {
      this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.currentData),item.prop,value);
    },
    // 上传事件
    handleUploaderEmit(item,type,response,file,fileList){
      if(item.methods && item.methods[type]){
        if (type === 'before-upload' || type === 'on-preview') {
          this.$emit('form-' + item.prop + '-' + item.methods[type],response,cloneDeep(this.currentData))
        } else if (type === 'on-remove' || type === 'on-change' || type === 'before-remove') {
          this.$emit('form-' + item.prop + '-' + item.methods[type],response,file,cloneDeep(this.currentData))
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type],response,file,fileList,cloneDeep(this.currentData))
        }
      }
      this.setCurrentDataString()
    },
    // 抛出操作列点击按钮
    handleIconClick(type,scope){
      this.$emit('table-'+type+'-click',scope)
    },
    // 当前数量改变
    handleSizeChange(size){
      this.$emit('table-size-change',size);
      this.resetInlineStatus()
    },
    // 当前页数改变
    handleCurrentChange(page){
      if (this.crossPageSelect) {
        const currentCrossSelectList = this.currentCrossSelectList.concat(this.currentSelectionList)
        for (let index = 0; index < currentCrossSelectList.length; index++) {
          const element = currentCrossSelectList[index];
          for (let j = index + 1; j < currentCrossSelectList.length; j++) {
            const childElement = currentCrossSelectList[j];
            if (isEqual(element, childElement)) {
              currentCrossSelectList.splice(j, 1)
            }
          }
        }
        this.currentCrossSelectList = cloneDeep(currentCrossSelectList)
      }
      this.$emit('table-current-change',page);
      this.resetInlineStatus()
    },
    // 点击上一页
    handlePrevClick(page){
      this.$emit('table-prev-click',page);
      this.resetInlineStatus()
    },
    // 点击下一页
    handleNextClick(page){
      this.$emit('table-next-click',page);
      this.resetInlineStatus()
    },
    resizeTableHeight(){
      const self = this;
      this.$nextTick(() => {
        let boxHeight
        if (self.$refs && self.$refs.aosTableContainer && self.$refs.aosTableContainer.parentElement && self.$refs.aosTableContainer.parentElement.parentElement) {
          boxHeight = self.$refs.aosTableContainer.parentElement.parentElement.offsetHeight;
        }
        if(boxHeight < 400){
          self.tableHeight = 400
        } if (boxHeight > 1200) {
          self.tableHeight = 1200
        } else {
          if (self.showPagination) {
            self.tableHeight  = boxHeight - 136;
          } else {
            self.tableHeight = boxHeight - 71;
          }
        }
      });
    },
    setRefObject (val, item) {
      val.forEach((dataItem) => {
        if (dataItem && !dataItem[item.prop + 'Label']) {
          this.$set(dataItem, item.prop + 'Label', '');
        }
        if (!this.refValueDataListObject[item.prop].valueList) {
          this.$set(this.refValueDataListObject[item.prop], 'valueList', [])
        }
        if (!this.refValueDataListObject[item.prop].labelValueList) {
          this.$set(this.refValueDataListObject[item.prop], 'labelValueList', [])
        }
        if (!this.refValueDataListObject[item.prop].labelValueObject) {
          this.$set(this.refValueDataListObject[item.prop], 'labelValueObject', {})
        }
        if (dataItem[item.prop]) {
          if (this.refValueDataListObject[item.prop].valueList.indexOf(dataItem[item.prop]) === -1) {
            this.refValueDataListObject[item.prop].valueList.push(dataItem[item.prop])
          }
        }
        if (this.treeProps && dataItem[this.treeProps.children]) {
          this.setRefObject(dataItem[this.treeProps.children], item)
        }
      });
    },
    setRefLabel (val, item) {
      val.forEach((dataItem) => {
        if (this.refValueDataListObject[item.prop].labelValueObject[dataItem[item.prop]]) {
          dataItem[item.prop + 'Label'] = this.refValueDataListObject[item.prop].labelValueObject[dataItem[item.prop]]
        } else {
          dataItem[item.prop + 'Label'] = dataItem[item.prop]
        }
        if (this.treeProps && dataItem[this.treeProps.children]) {
          this.setRefLabel(dataItem[this.treeProps.children], item)
        }
      });
    },
    translateRef (val) {
      if (val.length > 0 && this.refPropList.length > 0) {
        // 拿到对应prop列的值
        this.refPropList.forEach(item => {
          this.$set(this.refValueDataListObject, item.prop, {})
          this.setRefObject(val, item)
        });
        let allGetLabel = []
        this.refPropList.forEach(item => {
          // this.getRefLabel(item.refCode, this.refValueDataListObject[item.prop])
          allGetLabel.push(this.getRefLabel(item.refCode, this.refValueDataListObject[item.prop]))
        })
        window.Promise.allSettled(allGetLabel).then(() => {
          this.refPropList.forEach(item => {
            this.setRefLabel(val, item)
          });
          this.$emit('update: data', val)
        }).catch(error => {
          console.log('error===>', error)
        })
      }
    },
    getRefLabel(refCode, refValueDataListObject) {
      if (!refCode) {
        this.$message({
          type: 'error',
          message: '参照对应的 refCode 不能为空.'
        });
        return;
      }
      const paramsData = refValueDataListObject.valueList.join(',')
      if (!paramsData) {
        return;
      }
      return this.$optimizeHttp({
        url: '/core/api/ref/translate/' + refCode,
        method: 'get',
        params: {
          code: paramsData
        }
      }).then(res => {
        refValueDataListObject.labelValueList = cloneDeep(res.data);
        refValueDataListObject.labelValueObject = this.arrayToObject(refValueDataListObject.labelValueList)
      })
    },
    arrayToObject (array) {
      if (!array && !Array.isArray(array))  return {}
      let object = {}
      array.forEach(item => {
        object[item.code] = item.value
      })
      return object
    },
    refreshClick() {
      this.rotate += 180
      this.$emit('refresh')
      this.resetInlineStatus()
    },
    getCopySearchData () {
      if (this.inlineSearchData && Object.prototype.toString.call(this.inlineSearchData) === '[object Object]') {
        const keyList = Object.keys(this.inlineSearchData)
        if (keyList.length > 0) {
          keyList.forEach(key => {
            this.$set(this.copySearchData, key, this.inlineSearchData[key])
          })
        }
      }
    }
  },
  created () {
    this.handleDebounceRefresh = debounce(50,this.refreshClick)
    this.handleInlineSearchChangeEmit = debounce(800, this.inlineSearchEmit)
    this.defdocEmitChangeDebounce = debounce(50, this.defdocEmitChange)
    this.refEmitChangeDebounce = debounce(50, this.refEmit)
    this.inputNumberEmitDebounce = debounce(50, this.inputNumberEmit)
    this.ocrEmitSuccessDebounce = debounce(50, this.ocrEmit)
    this.ocrEmitErrorDebounce = debounce(50, this.ocrEmit)
    this.moneyEmitChangeDebounce = debounce(50, this.moneyEmitChange)
    this.cityEmitChangeDebounce = debounce(50, this.cityEmitChange)
    this.getCopySearchData()
  },
  mounted(){
    if(this.fixedHead){
      if (this.maxTableHeight) {
        this.tableHeight = this.maxTableHeight
      } else {
        addResizeListener(this.$refs.aosTableContainer.parentElement.parentElement,this.resizeTableHeight);
      }
    }
  },
  beforeDestroy(){
    if(this.fixedHead && !this.maxTableHeight){
      removeResizeListener(this.$refs.aosTableContainer.parentElement.parentElement,this.resizeTableHeight);
    }
  },
  activated () {
    this.$refs.AosTable.setBodyWrapperScroll(this.scrollLeft, this.scrollTop)
    this.canGetScroll = true
  },
  deactivated () {
    this.canGetScroll = false
  }

};
</script>

