<template>
  <div>
    <div style="display: flex;align-items: center;" :class="disabled?'':'no-disabled-class'">
      <InputPop ref="input" :telephone="telephone" v-if="!selectFlag" v-model="selectedValue"
                :readonly="inputReadOnlyData || disabled" :clearable="clearable"
                :magnifierFlag="disabled?false:true"
                :placeholder="placeholderData"
                @click.native="handleClick"
                @on-keydown="handleInputEnter" @on-blur="handleInputBlur" @on-focus="handleInputFocus"
                @on-clear="clearAll"
                @on-change="handleInputChange"/>
      <div class="search-class">
        <Icon slot="prefix" type="md-search" @click.stop="magnifierClick"/>
      </div>
    </div>
    <!--清空-->
    <!--    <div v-if="selectedValue && !disabled" class="close-all-class" :style="'left:' + settingLeft">-->
    <!--      <Icon slot="prefix" type="iconfont iconfont icon-clear" @click.stop="clearAll"/>-->
    <!--    </div>-->
    <DkModal
      :width="modalWidth"
      ref="modal_search"
      v-model="showModal"
      :loading="loading"
      :shortcut-flag="false"
      @modalOk="ok"
      @modalCancel="cancel"
      @on-cancel="cancel"
      @on-visible-change="onVisibleChange"
      class-name="change-class"
      :title="dkFormItem?vm.$t('choose') + dkFormItem.label: vm.$t('chooseData')">
      <BaseIndexButtonGroup>
        <template #left>
          <BaseIndexButton ref="search" name="search" @click="searchData"></BaseIndexButton>
          <BaseIndexButton :finalFlag="true" ref="clear" name="clear" @click="clear"></BaseIndexButton>
        </template>
      </BaseIndexButtonGroup>
      <!--      <div class="split-class"></div>-->
      <!--      <DkForm ref="formName" style="width: 85%; margin-top: 10px;margin-bottom: 10px" v-model="searchTable" :col-count="4">-->
      <!--        <DkFormItem :prop="it2" v-for="(it2, index2) in searchCond" :key="index2">-->
      <!--          <InputPop v-model="searchTable[it2]"/>-->
      <!--        </DkFormItem>-->
      <!--      </DkForm>-->

      <SearchCond id="search-cond-div" class="search-cond-class" :width="modalWidth - 100"
                  v-if="searchContent && searchContent.length > 0"
                  ref="searchCond"
                  v-model="searchCond" :setFlag="false" :searchContent="searchContent"
                  :col-count="colCount"></SearchCond>

      <div v-if="multiple">
        <DkTabs ref="tabs" :options="tabsOptions" @on-click="tabsClick" @on-clear="clearSelected"></DkTabs>

        <DkTable v-show="tabIndex === 0" :primaryKey="selectKey"
                 :clear-check-flag="false" ref="table-select" :id="'table-'+$options.name"
                 name="table" :data="tableData" :height="tableHeight"
                 :radio-flag="!multiple"
                 :multiple="multiple"
                 :choose-flag="multiple"
                 :refreshSelect="false"
                 :linkClickChecked="true"
                 :show-setting-flag="false"
                 :show-tip="true"
                 :choose-data-flag="true"
                 :perspective-flag="false"
                 :export="false"
                 :pageSize="pageInfo.pageSize"
                 :page-size-opts="pageSizeOpts?pageSizeOpts:$config.pageSizeOptsMag"
                 :seq-tip-content="vm.$t('doubleSeq')"
                 :tree-flag="treeFlag"
                 @select-change="handleSelectChange"
                 @pageChange="pageSizeChange"
                 @chooseData="chooseData"
        >
          <DkTableColumn v-for="(item,index) in columns" :key="index" :field="item.field"
                         :title="vm.$t(item.title) ? vm.$t(item.title):vm.$t(item.field)" :width="item.width"
                         :resize-flag="index === columns.length - 1"></DkTableColumn>
        </DkTable>

        <DkTable v-show="tabIndex === 1" ref="table-selected" :pageFlag="false" :pageTotalFlag="false"
                 :primaryKey="selectKey"
                 :id="'table-'+$options.name"
                 :choose-flag="false"
                 :perspective-flag="false"
                 :export="false"
                 :show-setting-flag="false" :data="batchRowsPage" :operateFlag="true" :height="tableHeight"
                 :pageSize="pageInfo.pageSize"
                 :refreshSelect="false"
                 :add-flag="false"
                 @delRow="delItem"
        >
          <!--          <DkTableColumn type="seq" align="center" width="60" min-width="44px" :add-flag="false"-->
          <!--                         @del="delItem"></DkTableColumn>-->
          <DkTableColumn v-for="(item,index) in columns" :key="index" :field="item.field"
                         :title="vm.$t(item.title) ? vm.$t(item.title):vm.$t(item.field)" :width="item.width"
                         :resize-flag="index === columns.length - 1"></DkTableColumn>
        </DkTable>

      </div>

      <DkTable v-else :primaryKey="selectKey" :clear-check-flag="false" ref="table-select" :id="'table-'+$options.name"
               name="table" :data="tableData" :height="tableHeight"
               :radio-flag="!multiple"
               :multiple="multiple"
               :choose-flag="multiple"
               :refreshSelect="false"
               :show-setting-flag="false"
               :show-tip="true"
               :perspective-flag="false"
               :export="false"
               :seq-tip-content="vm.$t('doubleSeq')"
               :choose-data-flag="true"
               :linkClickChecked="true"
               :tree-flag="treeFlag"
               :pageSize="pageInfo.pageSize"
               :page-size-opts="pageSizeOpts?pageSizeOpts:$config.pageSizeOptsMag"
               @pageChange="pageSizeChange"
               @chooseData="chooseData"
      >
        <DkTableColumn v-for="(item,index) in columns" :key="index" :field="item.field"
                       :tree-node="item.treeNode"
                       :title="vm.$t(item.title) ? vm.$t(item.title):vm.$t(item.field)"
                       :width="item.width"
                       :resize-flag="index === columns.length - 1"></DkTableColumn>
      </DkTable>


      <div v-show="false">
        <DkButton type="primary" ref="confirm" @click="ok">{{ vm.$t('confirm') }}</DkButton>
        <DkButton ref="close" @click="cancel">{{ vm.$t('close') }}</DkButton>
      </div>
    </DkModal>
  </div>
</template>

<script>

import {button as buttonList} from '@/locale/lang/zh-CN'
import setting from './setting'
import main from '../../../main'
import Vue from "vue";

export default {
  name: 'SelectMagnifier',
  inject: {
    prop: {
      type: String,
      default: null
    },
    dkFormItem: {
      type: Object,
      default: null
    }
  },
  model: {
    prop: 'value',
    event: 'modelOk'
  },
  props: {
    value: {
      type: [Number, String, Array],
      default: null
    },
    // 显示的值
    displayText: {
      type: String,
      default: null
    },
    // 放大镜类型
    type: {
      type: String,
      default: null
    },
    //禁用状态
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    //提示信息
    placeholder: {
      type: String,
      default: ''
    },
    //输入框是否只读
    inputReadOnly: {
      type: Boolean,
      default: true
    },
    // 外部传入的查询条件
    otherCondition: {
      type: Object,
      default: null
    },
    // 主键Id ,传入有值以传入为准
    primaryKey: {
      type: String,
      default: ''
    },
    // 显示内容 ,传入有值以传入为准
    primaryLabel: {
      type: String,
      default: ''
    },
    // 表格高度
    tableHeight: {
      type: Number,
      default: 340
    },
    // 清空标识
    clearable: {
      type: Boolean,
      default: true
    },
    // 是否是联系电话（电话是11位，允许0在首位）
    telephone: {
      type: Boolean,
      default: false
    },
    // 查询条件（传入）
    searchInfo: {
      type: Object
    },
    // 查询条件（值等传入）
    searchInputInfo: {
      type: Object
    },
    // 自定义，如果是自定义，那么就在外部处理
    customFlag: {
      type: Boolean,
      default: false
    },
    // 没有内容点击也打开
    alwaysOpenFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    const vm = window.vm
    let self = this
    return {
      colCount: 4,
      modalWidth: 980,
      loading: false,
      tabIndex: 0,
      treeFlag:false,
      tabsOptions: [
        {label: '选择列表', name: 'name1', index: 0},
        {label: '已选列表', name: 'name2', index: 1, clear: true},
        // { label: self.$t('staffSalesTarget'), name: 'name3' },
      ],
      chooseLabel: (h) => {
        return h('div', [
          h('span', '已选'),
          h('Badge', {
            props: {
              count: self.batchRowsPage ? self.batchRowsPage.length : null
            }
          })
        ])
      },
      vm: vm,
      documentKeyDownContent: Object,
      model: self.value,
      inputReadOnlyData: true,
      selectFlag: false,
      options: [],
      tableData: [],
      showModal: false,
      batchRowsPage: [],
      batchKeysPage: [],
      // 数据源的service
      service: {},
      // 查询方法名字
      methodsName: '',
      // 详细的查询方法
      methodsNameDetail: '',
      // 文本框框值等查询方法
      methodsNameInput: '',
      // 文本框快捷检索的字段
      inputSearchField: '',
      //列设置
      columns: [],
      // 选择的key
      selectKey: '',
      // 选择的label
      selectLabel: '',
      // 查询条件
      searchCond: {},
      searchContent: [],
      // 最大的条数
      // 选择的显示的数据
      selectedValue: self.displayText,
      placeholderData: '',
      showClear: false,
      blurFlag: true,
      pageInfo: {
        total: 0,
        pageSize: this.$config.pageSizeMag,
        currentPage: 1
      },
      otherConditionInner: {},
      initSearchFlag:false,  // 是否打开就查询
      pageSizeOpts:null,
    }
  },
  watch: {
    model(n, o) {
      // 如果为空需要清空batchKeys
      if (!n || n.length === 0) {
        this.clearAll()
      }
      this.$emit('input', n)
      this.$emit('on-change', this.options)
    },
    displayText(n, o) {
      this.selectedValue = n;
    },
    value(n, o) {
      // if (!this.inputReadOnlyData) {
      //   // todo 如果赋值就会产生把id付给selectvalue的情况
      //   // this.selectedValue = n
      // } else {
      //   if (n == null) {
      //     this.selectedValue = null;
      //   }
      // }
      if (n == null) {
        this.selectedValue = null;
        this.$emit('ok', null)
      }
      if (!n) {
        this.batchKeysPage = []
        this.batchRowsPage = []
      }
    },
    searchInfo(n, o) {
      // 根据传入参数给查询条件赋值
      this.setSearchInfo(n);
    },
    selectedValue(n, o) {
      if (n) {
        // 清除提示信息
        this.clearErrMessage();
      }
      // this.$emit('modelOk',n)
    },
    /**
     * @desc   : 监听放大镜是否打开，如果关闭，需要把keydown还原回去
     * @author : 周兴
     * @date   : 2022/5/13 10:12
     */
    showModal(n, o) {
      if (!n) {
        document.onkeydown = this.documentKeyDownContent
      } else {
        this.addKeyBoardEvent() // 增加快捷键
      }
    },
    placeholder(n, o) {
      this.placeholderData = n
    },
    // selectedValue(n,o){
    //   this.model = n;
    // },
    disabled(n, o) {
      if (n) {
        this.placeholderData = null;
        this.inputReadOnlyData = true;
      }
    },
    inputReadOnly(n, o) {
      this.inputReadOnlyData = n;
    },
    batchRowsPage(n, o) {
      //监听选择的数据,改变页签的数量
      if (n && n.length) {
        this.tabsOptions[1].label = '已选列表【' + n.length + '】';
      } else {
        this.tabsOptions[1].label = '已选列表';
      }
    },
  },
  methods: {
    /**
     * @desc   : 切换tab
     * @author : 周兴
     * @date   : 2022/5/28 16:38
     */
    tabsClick(e, option) {
      this.tabIndex = option.index;
      // 如果是已选列表,需要记录查询页面的数据
      if (this.tabIndex === 1) {
      }
    },
    /**
     * @desc   : 删除已选
     * @author : 周兴
     * @date   : 2022/5/31 15:04
     */
    clearSelected() {
      // this.selectedKeys = []
      // this.selectedTable = []
      // this.batchKeysPage = []
      // this.batchRowsPage = []
      // this.$refs['table-select'].clearBatchKeys();
      this.clearAll();
    },

    /**
     * @desc   : 文本改变事件
     * @author : 周兴
     * @date   : 2022/7/21 18:30
     */
    handleInputChange(e) {
      if (this.methodsNameInput) {
        this.batchRowsPage = []
        this.batchKeysPage = []
      }
      this.selectedValue = e;
      this.$emit('modelOk', this.selectedValue)
      this.$emit('ok', null)
      this.$emit('input-change', e, true)
    },
    /**
     * @desc   : 改变值
     * @author : 周兴
     * @date   : 2022/7/18 15:19
     */
    handleChange(e) {
      this.$emit('input', e)
    },
    /**
     * @desc   : 返回整行选择的数据
     * @author : 张潇木
     * @date   : 2022-6-24 13:49
     */
    onSelectLabel(e) {
      this.$emit('on-select-label', e)
    },
    /**
     * @desc   : 用传入的参数给值赋值
     * @author : 周兴
     * @date   : 2023/2/21 10:27
     */
    setSearchInfo(searchInfo) {
      if (searchInfo) {
        this.objectMerge(this.searchCond._value, searchInfo);
      }
    },
    /**
     * @desc   : 输入框失去焦点事件
     * @author : 周兴
     * @date   : 2022/5/26 8:57
     */
    handleInputBlur(e) {
      if (this.disabled || this.inputReadOnlyData) {
        return;
      }
      // 如果主键Id有值就不去检索
      if (this.batchRowsPage && this.batchRowsPage.length > 0 && this.batchRowsPage[0][this.selectKey]) {
        return;
      }
      //根据input进行值等查询
      if (this.methodsNameInput && this.blurFlag) {
        this.getDataByInput()
      }
    },
    /**
     * @desc   : 光标进入之后，没有值就打开
     * @author : 周兴
     * @date   : 2022/6/15 9:19
     */
    handleInputFocus() {
      if (this.disabled || !this.inputReadOnlyData) {
        return;
      }
      // 只要有值就不打开
      if (!this.selectedValue) {
        this.magnifierClick();
      }
    },
    /**
     * @desc   : 鼠标进入
     * @author : 周兴
     * @date   : 2022/6/21 18:32
     */
    handleInputEnter(e) {
      if (this.disabled) {
        return;
      }
      if (e.key === 'Enter') {
        // 点回车进行检索
        if (!this.inputReadOnlyData && this.methodsNameInput) {
          this.handleInputBlur(e);
        } else {
          // 打开窗体
          this.magnifierClick();
        }
      }
    },
    /**
     * @desc   : 根据输入框进行值等查询
     * @author : 周兴
     * @date   : 2022/5/26 9:49
     */
    getDataByInput() {
      //如果没有值就不查直接返回
      if (!this.selectedValue) {
        this.$emit('on-input-blur', [])
        this.$emit('modelOk', this.multiple ? [] : null)
        return
      }
      this.$emit('modelOk', this.selectedValue)
      let param = {}
      if (this.inputSearchField) {
        param[this.inputSearchField] = this.selectedValue.trim()
      }
      // 拼接外部传入的其他参数otherCondition TODO
      if (this.searchInputInfo) {
        if (!this.inputSearchField) {
          param = Object.assign(param, this.searchInputInfo)
          // 第一个属性就是当前
          let keys = Object.keys(this.searchInputInfo)
          if (keys && keys.length > 0) {
            param[keys[0]] = this.selectedValue.trim()
          }
        }
      }
      // console.log('333',this.searchInputInfo,this.inputSearchField)
      // 范围权限
      param['purview'] = true;
      param.userId = this.$store.state.user.id
      param.cpId = this.$store.state.user.cpId
      param.currentPage = 1;
      param.pageSize = 10;
      // 查询数据
      this.excute(this.service, this.service[this.methodsNameInput], param).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          let arr = [];
          if (res.data && res.data.list && res.data.list.length > 0) {
            arr = [...res.data.list];
          }
          if ((!arr || arr.length === 0) && res.data && res.data.length > 0) {
            arr = [...res.data];
          }
          // 如果值等查询查到多条，那么弹出查询页面
          if (arr && arr.length > 1) {
            this.blurFlag = false;
            setTimeout(() => {
              this.blurFlag = true
            }, 1000)
            this.showModal = true;
            return;
          }
          //查询的数据存在
          this.batchKeysPage = []
          this.batchRowsPage = []
          if (arr && arr.length > 0) {
            arr.forEach(it => {
              this.batchKeysPage.push(it[this.selectKey])
            })
          }
          if (this.multiple) {
            arr.forEach(it => {
              this.$refs['table-select'].$refs['table'].setCheckboxRow(it, this.batchKeysPage.includes(it[this.selectKey]))
            })
          } else {
            arr.forEach(it => {
              if (it[this.selectKey] && this.batchKeysPage && this.batchKeysPage.includes(it[this.selectKey])) {
                // this.$set(it, 'radio', this.batchKeysPage.includes(it[this.selectKey]))
                if (this.$refs['table-select'] && this.$refs['table-select'].$refs['table']) {
                  this.$refs['table-select'].$refs['table'].setRadioRow(it)
                }
              }
            })
          }
          this.tableData = arr
          if (this.batchKeysPage && this.batchKeysPage.length > 0) {
            this.batchRowsPage = this.tableData.filter(it => this.batchKeysPage.includes(it[this.selectKey])).map(m => m)
            if (this.$refs['table-select']) {
              this.$refs['table-select'].batchRows = this.batchRowsPage
            }
            this.$emit('on-input-blur', this.batchRowsPage)
            this.$emit('ok', this.batchRowsPage)
          } else {
            this.$Message.warning(this.$t('W_006'))
            this.$emit('on-input-blur', [])
            this.$emit('ok', [])
          }
        } else {
          this.$emit('on-input-blur', [])
          this.$emit('ok', [])
          this.$Message.warning(res.message)
        }
      })
    },
    /**
     * @desc   : 点击
     * @author : 周兴
     * @date   : 2022/5/24 16:23
     */
    handleClick() {
      if (this.disabled || !this.inputReadOnlyData) {
        return;
      }
      if (this.alwaysOpenFlag || !this.selectedValue) {
        this.magnifierClick()
      }
    },
    /**
     * @desc   : 键盘事件
     * @author : 周兴
     * @date   : 2022/4/15 20:38
     */
    handleKeydown(e) {
      if (e.key === 'Enter') {
        //如果下拉没有开启才会弹出
        if (this.multiple) {
          this.magnifierClick()
        } else {
          //单选时，如果下拉开启，不能点开放大镜
          if (!this.$refs.select.$refs.selectSingle.openFlag) {
            this.magnifierClick();
          }
        }
      }
    },
    selectChange() {
      this.$nextTick(() => {
        this.batchRowsPage = this.$refs['table-select'].batchRows
      })
    },
    /**
     * @desc   : 删除已选
     * @author : 周兴
     * @date   : 2022/9/26 16:39
     */
    delItem(rowIndex) {
      let row = this.batchRowsPage[rowIndex]
      // 如果存在就删除
      if (row) {
        let key = row[this.selectKey];
        this.batchRowsPage = this.batchRowsPage.filter(it => it[this.selectKey] !== row[this.selectKey])
        this.batchKeysPage = this.batchKeysPage.filter(it => it !== row[this.selectKey])
        let tRow = this.tableData.filter(it => it[this.selectKey] === key);
        // 删除掉去掉的勾选
        if (tRow && tRow.length > 0) {
          // 删除掉去掉的勾选
          this.$refs['table-select'].setUnCheckedRow(tRow[0]);
        }
        // else {
        //   // 删除掉去掉的勾选
        //   if (this.batchKeysPage) {
        //     this.batchKeysPage.splice(this.batchKeysPage.indexOf(key), 1)
        //     let filterRows = this.$refs['table-select'].batchRows.filter(it => it[this.selectKey] == key)
        //     if (filterRows && filterRows.length > 0) {
        //       this.$refs['table-select'].batchRows.splice(this.$refs['table-select'].batchRows.indexOf(filterRows[0]), 1)
        //     }
        //     this.$refs['table-select'].batchKeys = this.batchKeysPage?.copy();
        //     console.log('3342',tRow,this.tableData, this.batchRowsPage,JSON.stringify(this.batchKeysPage) )
        //   }
        // }
      }
    },
    /**
     * @desc   : 选择数据
     * @author : 周兴
     * @date   : 2023/2/19 18:46
     */
    chooseData(row) {
      this.batchRowsPage = [row]
      this.batchKeysPage = [row[this.selectKey]]
      // 不显示下拉时
      if (!this.selectFlag) {
        let display = []
        for (let i = 0; i < this.batchRowsPage.length; i++) {
          display.push(this.batchRowsPage[i][this.selectLabel])
        }
        this.selectedValue = display.join(' | ')
      }
      this.model = this.multiple ? this.batchKeysPage : row[this.selectKey]
      this.$emit('input-change', this.multiple ? this.batchKeysPage : this.batchKeysPage[0])
      this.$emit('modelOk', this.telephone?this.selectedValue:(this.multiple ? this.batchKeysPage : this.batchKeysPage[0]) )
      this.$emit('ok', this.batchRowsPage)
      this.$emit('on-ok', this.multiple ? this.batchRowsPage : this.batchRowsPage[0])
      this.focus();  // 聚焦
      this.showModal = false;
    },
    /**
     * @desc   : 勾选数据
     * @author : 周兴
     * @date   : 2022/5/28 17:00
     */
    handleSelectChange({batchRows, row, checked}) {
      if (row) {
        this.batchKeysPage = [...this.$refs['table-select'].batchKeys]
        if (!this.batchRowsPage) {
          this.batchRowsPage = [...this.$refs['table-select'].batchRows]
        }
        if (this.batchKeysPage && this.batchKeysPage.length > 0) {
          let dataFinal = this.$refs['table-select'].dataFinal
          let filters = []
          this.batchKeysPage.forEach(it => {
            filters = this.batchRowsPage.filter(item => item[this.selectKey] === it);
            if (checked) {
              if (!filters || filters.length === 0) {
                // 获取列
                filters = dataFinal?.filter(item => item[this.selectKey] === it);
                if (filters && filters.length > 0) {
                  this.batchRowsPage.push({...filters[0]})
                }
              }
            }
          })
          // 如果取消勾选，需要删除掉勾选
          this.batchRowsPage = this.batchRowsPage.filter(t => this.batchKeysPage.includes(t[this.selectKey]))
          // // 根据id获取row
          // this.batchRowsPage = this.$refs['table-select'].dataFinal?.filter(it => this.batchKeysPage.includes(it[this.selectKey]))
        } else {
          this.batchRowsPage = []
        }
        this.$refs['table-select'].batchRows = [...this.batchRowsPage]
        // this.batchRowsPage = [...this.$refs['table-select'].batchRows]
      }
    },
    /**
     * @desc   : 翻页
     * @author : 周兴
     * @date   : 2022/3/17 14:57
     */
    pageSizeChange(pageInfo) {
      this.pageInfo = pageInfo
      this.getDataTable() // 查询数据
    }
    ,
    /**
     * @desc   : 查询，从第一页开始
     * @author : 周兴
     * @date   : 2023/2/24 10:45
     */
    searchData() {
      this.pageInfo.currentPage = 1;
      this.getDataTable();
    }
    ,
    /**
     * @desc   : 焦点进入事件
     * @author : 周兴
     * @date   : 2022/3/22 12:54
     */
    focus() {
      this.$nextTick(() => {
        this.$refs['input'].focus();
      })
    }
    ,
    /**
     * @desc   : 清空事件
     * @author : 周兴
     * @date   : 2022/3/4 8:19
     */
    clear() {
      this.searchList = {}
      this.searchCond._value = {}
      if (this.$refs.searchCond) {
        this.$refs.searchCond.clearCondition();
      }
      // this.searchData() // 重新查询
    }
    ,
    /**
     * @desc   : 校验是否可以做查询
     * @author : 周兴
     * @date   : 2022/3/17 13:03
     */
    check() {
      // // 如果是标签 docType必须传递
      // if (this.type === this.$config.MagnifierType.customTags && this.docCode === '') {
      //   return false
      // }
      // // 如果是商品属性，需要传类型
      // if (this.type === this.$config.MagnifierType.goodsAttribute && this.attributeType === '') {
      //   return false
      // }
      // // 如果是商品，需要传分页
      // if (this.type === this.$config.MagnifierType.goods && !this.showModal) {
      //   return false
      // }
      return true
    }
    ,
    /**
     * @desc   : 获取表格数据
     * @author : 沈博
     * @date   : 2022/3/7 16:59
     */
    getDataTable() {
      // 校验是否可以查询
      if (!this.check()) {
        return
      }
      this.loading = true;
      let param = {...this.$refs['table-select'].pageInfo}
      param.currentPage = this.pageInfo.currentPage ? this.pageInfo.currentPage : 1
      param.pageSize = this.pageInfo.pageSize
      param.userId = this.$store.state.user.id
      param.cpId = this.$store.state.user.cpId
      param.cpId = this.$store.state.user.cpId
      // 拼接外部传入的其他参数otherCondition
      if (this.otherCondition) {
        param = Object.assign(param, this.otherCondition)
      }
      if (this.otherConditionInner) {
        param = Object.assign(param, this.otherConditionInner)
      }
      if (this.searchCond) {
        param = Object.assign(param, this.searchCond._value)
      }
      // console.log('bbb', this.service, this.methodsNameDetail)
      this.excute(this.service, this.service[this.methodsNameDetail], param).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          let arr = []
          if (res.data && res.data.list) {
            arr = [...res.data.list]
          }
          if (arr.length === 0 && res.data && Array.isArray(res.data)) {
            arr = [...res.data]
          }
          if (arr && arr.length > 0) {
            if (this.multiple) {
              if (this.$refs['table-select'].batchKeys && this.$refs['table-select'].batchRows.length > 0) {
                arr.forEach(it => {
                  let batchKeysMuti = this.$refs['table-select'].batchKeys;
                  if (batchKeysMuti.filter(it => it === it[this.selectKey]).length > 0) {
                    this.$refs['table-select'].setCheckboxRow(it);
                  }
                })
              }
            } else {
              if (this.batchKeysPage && this.batchKeysPage.length > 0) {
                let keyName = this.telephone ? 'customerPhone' : this.selectKey;
                this.batchRowsPage = []
                arr.forEach(it => {
                  if (it[this.selectKey] && this.batchKeysPage && this.batchKeysPage.includes(it[keyName])) {
                    // this.$set(it, 'radio', this.batchKeysPage.includes(it[this.selectKey]))
                    this.batchRowsPage.push(it);
                    // this.$refs['table-select'].$refs['table'].setRadioRow(it)
                  }
                })
              }
            }
            this.tableData = arr
            // 单选需要设置当前行状态
            if (!this.multiple && this.batchRowsPage && this.batchRowsPage.length > 0) {
              this.$nextTick(() => {
                this.$refs['table-select'].setCurrentRow(this.batchRowsPage[0]);
              })
            }
            // if (this.batchKeysPage) {
            //   this.batchRowsPage = this.tableData.filter(it => this.batchKeysPage.includes(it[this.selectKey])).map(m => m)
            //   this.$refs['table-select'].batchRows = this.batchRowsPage
            // }
            this.$refs['table-select'].pageInfo.total = res.data.total
          }
          this.loading = false;
        } else {
          this.$Message.warning(res.message)
          this.loading = false;
        }
      })
    }
    ,
    /**
     * @desc   : 放大镜点击事件
     * @author : 沈博
     * @date   : 2022/3/7 14:21
     */
    magnifierClick() {
      if (this.disabled) {
        return;
      }
      // 自定义的方式在外部自己处理
      if (this.customFlag) {
        this.$emit('on-click')
        return;
      }
      this.showModal = true
      this.$nextTick(() => {
        // 文本不可输入时（大多数放大镜组件使用）
        if (this.inputReadOnlyData) {
          if (this.multiple) {
            this.batchKeysPage = []
            this.$refs['table-select'].batchKeys = []
            if (this.value && Array.isArray(this.value)) {
              this.$refs['table-select'].batchKeys = [...this.value]
              this.batchKeysPage = [...this.value]
              this.model = [...this.value]
            } else {
              if (this.value) {
                this.$refs['table-select'].batchKeys = [this.value]
                this.batchKeysPage = [this.value]
                this.model = [this.value]
              }
            }
          } else {
            if (this.value && Array.isArray(this.value)) {
              this.$refs['table-select'].batchKeys = this.value
              this.batchKeysPage = this.value
              this.model = this.value
            } else if (this.value && !Array.isArray(this.value)) {
              this.$refs['table-select'].batchKeys = [this.value]
              this.batchKeysPage = [this.value]
              this.model = [this.value]
            }
          }
        } else {
          // 文本能输入（客户电话使用）
          if (this.multiple) {
            if (this.value) {
              this.$refs['table-select'].batchKeys = [...this.value]
              this.batchKeysPage = [...this.value]
            } else {
              this.model = []
            }
          } else {
            if (this.value) {
              this.$refs['table-select'].batchKeys = [this.value]
              this.batchKeysPage = [this.value]
            } else {
              this.model = []
            }
          }
        }
        // 如果多选，页签回到第一个
        if (this.multiple) {
          this.tabIndex = 0;
        }
        // 查询数据
        // this.getDataTable();
      })
    }
    ,
    /**
     * @desc   : 清空数据
     * @author : 周兴
     * @date   : 2022/3/17 17:29
     */
    clearAll() {
      this.showClear = false
      this.selectedValue = ''
      this.$refs['table-select']?.clearBatchKeys() //清空选择
      this.model = null;
      this.batchKeysPage = null
      this.batchRowsPage = null
      if (this.multiple) {
        this.$emit('input-change', [])
        this.$emit('ok', [])
        this.$emit('modelOk', [])
      } else {
        this.$emit('input-change', null)
        this.$emit('ok', null)
        this.$emit('modelOk', null)
      }
    }
    ,
    /**
     * @desc   : modal变化事件
     * @author : 沈博
     * @date   : 2022/3/7 14:28
     */
    onVisibleChange(val) {
      if (val) {
        if(this.initSearchFlag){
          // 查询
          this.getDataTable()
        }
        // this.batchRowsPage = this.$refs['table-select'].batchRows
      } else {
        this.searchTable = {} // 关闭选择画面需要清空条件
      }
    }
    ,
    /**
     * @desc   : 校验是否选择
     * @author : 沈博
     * @date   : 2022/3/7 15:44
     */
    checkBatch() {
      if (!this.batchKeysPage || this.batchKeysPage.length === 0) {
        // if (this.$refs['table-select'].batchKeys.length <= 0) {
        this.$Message.warning('请先选择数据')
        return false
      }
      return true
    }
    ,
    /**
     * @desc   : 确定点击事件
     * @author : 沈博
     * @date   : 2022/3/7 15:43
     */
    ok() {
      // 如果是单选，需要给batchKey赋值
      if (!this.multiple) {
        this.batchKeysPage = [...this.$refs['table-select'].batchKeys]
        this.batchRowsPage = [...this.$refs['table-select'].batchRows]
      }
      if (this.checkBatch()) {
        this.showModal = false
        // 重新去keys，考虑到可能会有无效的数据
        // this.batchKeysPage = [...this.$refs['table-select'].batchKeys]
        // this.batchRowsPage = [...this.$refs['table-select'].batchRows]
        // // 判断放大镜获取的数据是否在下拉里有，如果没有就增加
        // this.batchRowsPage.forEach(it => {
        //   if (this.multiple) {
        //     let filter = this.options.filter(opt => opt[this.selectKey] == it[this.selectKey])
        //     if (!filter || filter.length === 0) {
        //       this.options.push(it);
        //     }
        //   }
        // })
        // 不显示下拉时

        if (!this.selectFlag) {
          let display = []
          // for (let i = 0; i < this.$refs['table-select'].batchRows.length; i++) {
          //   display.push(this.$refs['table-select'].batchRows[i][this.selectLabel])
          // }
          for (let i = 0; i < this.batchRowsPage.length; i++) {
            display.push(this.batchRowsPage[i][this.selectLabel])
          }
          this.selectedValue = display.join(' | ')
        }
        // this.model = this.multiple ? this.$refs['table-select'].batchKeys : this.$refs['table-select'].batchKeys[0]
        this.model = this.multiple ? this.batchKeysPage : this.batchKeysPage[0]
        //光标切回select组件
        if (this.selectFlag) {
          this.$refs['select'].focus()
        } else {
          this.$refs['input'].$refs.input.focus = true
        }
        // 选择数据
        this.batchKeysPage = this.batchKeysPage.filter(it => it != null); // 过滤掉null数据
        this.$emit('input-change', this.multiple ? this.batchKeysPage : this.batchKeysPage[0])
        this.$emit('ok', this.batchRowsPage)
        this.$emit('modelOk', this.telephone?this.selectedValue:(this.multiple ? this.batchKeysPage : this.batchKeysPage[0]) )
        // this.$emit('on-ok', this.multiple ? this.$refs['table-select'].batchRows : this.$refs['table-select'].batchRows[0])
        this.$emit('on-ok', this.multiple ? this.batchRowsPage : this.batchRowsPage[0])
        // 清空查询条件
        this.$refs['searchCond'].clearCondition();
        // 清空表格
        this.clearTable();
        this.focus();  // 聚焦
      }
    }
    ,
    /**
     * @desc   : 清空表格数据
     * @author : 周兴
     * @date   : 2023/5/8 13:43
     */
    clearTable() {
      this.tableData = []
      // // 清空列表
      // this.$refs['table-select'].clearTable();
    }
    ,
    /**
     * @desc   : 关闭点击事件
     * @author : 沈博
     * @date   : 2022/3/7 15:43
     */
    cancel() {
      // 清空查询条件
      this.$refs['searchCond'].clearCondition();
      // 清空表格
      this.clearTable();
      this.showModal = false
    }
    ,
    /**
     * @desc   : desc
     * @author : 沈博
     * @date   : 2022/3/7 15:50
     */
    iviewSelectChange(val) {
      if (!this.multiple) {
        this.$refs['table-select'].batchKeys = [val]

        this.batchKeysPage = [val]
        this.$refs['table-select'].batchRows = this.options.filter(it => {
          return this.model == it[this.selectKey]
        }).map(it => {
          return it
        })
        this.batchRowsPage = [...this.$refs['table-select'].batchRows]
      }
      this.model = val
      this.$emit('ok', this.batchRowsPage)
    }
    ,
    /**
     * @desc   : 监听全局键盘按钮按下的事件
     * @author : 周兴
     * @date   : 2022/3/4 16:57
     */
    addKeyBoardEvent() {
      let code = 0
      let self = this
      this.documentKeyDownContent = document.onkeydown
      document.onkeydown = function (e) {
        const evn = e || event
        const key = evn.keyCode || evn.which || evn.charCode
        // alt：code = 18
        if (key === 18) {
          code = 18
        }
        //只有modal弹出才能可见
        if (self.$refs.modal_search.showModal) {
          // Q：code = 81 查询
          let btList = Object.values(self.$config.button);
          btList.forEach(forIt => {
            if (code === 18 && forIt.hotKey?.toLowerCase() === e.key.toLowerCase()) {
              e.returnValue = false
              if (self.$refs.modal_search.$refs[forIt.name]) {
                self.$refs.modal_search.$refs[forIt.name].$el.click()
              } else if (self.$refs[forIt.name]) {
                self.$refs[forIt.name].$el.click()
              }
            }
          })
        }
      }
      // 监听全局键盘按钮松开的事件
      document.onkeyup = function (e) {
        const evn = e || event
        const key = evn.keyCode || evn.which || evn.charCode
        if (key === 18) {
          code = 0
        }
        // 一秒钟失效，避免因为按了alt+tab之后再回来，按其他什么英文字母都不好使了的问题
        setTimeout(() => {
          code = 0
        }, 1000)
      }
    }
    ,
    /**
     * @desc   : 根据类型给属性赋值
     * @author : 周兴
     * @date   : 2022/3/16 18:12
     */
    setMagnifierProperty() {
      let self = this
      // 设置接口相关信息
      let set = setting.setSetting(this.$service, self.type);
      // console.log('ff',set,self.type)
      self = this.objectMerge(self, set)
      if(self.pageSize){
        self.pageInfo.pageSize = self.pageSize;
      }
    }
  },
  mounted() {
    if (this.dkFormItem) {
      this.dkFormItem.setItems(this);   // 把当前组件赋值给formItem
    }
  }
  ,
  created() {
    this.setMagnifierProperty() // 根据类型给属性赋值
    if (!this.disabled && !this.placeholderData) {
      if (!this.placeholder) {
        this.placeholderData = vm.$t('inputWords', {'search-name': (this.dkFormItem && this.dkFormItem.label) ? this.dkFormItem.label : vm.$t(this.prop)})
      } else {
        this.placeholderData = this.placeholder;
      }
    }
    this.inputReadOnlyData = this.inputReadOnly;
  }
}
</script>
<style scoped>
/deep/ .ivu-modal-body {
  padding: 0 10px 10px 10px;
}

/deep/ .btn-div {
  position: relative;
  background: #EAEDF7 !important;
}

/deep/ .btn-div + div {
  height: 0 !important;
}

/deep/ .ivu-select-arrow {
  display: none;
}

/deep/ .ivu-icon-ios-arrow-down {
  display: none !important;
}

/deep/ .no-disabled-class .readonly-input > .ivu-input {
  background-color: #fff !important;
}

/deep/ .ivu-input {
  padding-right: 20px !important;
}

/deep/ .ivu-modal-body {
  background: #EAEDF7 !important;
}

</style>

