<template>
  <div>
    <div style="display: flex;align-items: center;">
      <InputPop ref="input" :value="selectedValue" :class="tableFlag?'input-class':''"
                :clearable="true" :magnifierFlag="true" readonly @on-clear="clearAll" @on-focus="magnifierClick(true)"
                @on-keydown="handleInputKeydown"/>
      <!--      <div class="close-class" v-if="!readonly && selectedValue && selectedValue.length > 0">-->
      <!--        <Icon slot="prefix" type="ios-close-circle" @click.stop="clearAll"/>-->
      <!--      </div>-->
      <div class="search-class">
        <Icon slot="prefix" type="md-search" @click.stop="magnifierClick(false)"/>
      </div>
    </div>
    <DkModal
      width="800"
      ref="modal_search"
      v-model="showModal"
      @modalOk="ok"
      @modalCancel="cancel"
      @on-visible-change="onVisibleChange"
      class-name="multi-class"
      :title="dkFormItem?vm.$t('choose') + dkFormItem.label: vm.$t('chooseData')">
      <BaseIndexButtonGroup #left>
        <BaseIndexButton ref="search" name="search" @click="getDataTable"></BaseIndexButton>
        <BaseIndexButton :finalFlag="true" ref="clear" name="clear"
                         @click="clear"></BaseIndexButton>
      </BaseIndexButtonGroup>
      <!--      <SearchCond id="search-cond-div" width="780px" v-if="searchCond && searchCond.length > 0" ref="searchCond"-->
      <!--                  v-model="searchCond" :setFlag="false" :searchContent="searchCond" :col-count="4"></SearchCond>-->
      <SearchCond id="search-cond-div" class="search-cond-class"  width="700" v-if="searchContent && searchContent.length > 0" ref="searchCond"
                  v-model="searchCond" :setFlag="false" :searchContent="searchContent" :col-count="colCount"></SearchCond>

      <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"
               :checkMethodFlag=true
               :page-flag="pageFlag"
               :page-total="pageInfo.total"
               :current-page="pageInfo.currentPage"
               :link-click-checked="true"
               :refreshSelect="false"
               :show-setting-flag="false"
               :pageSize="pageInfo.pageSize"
               :page-size-opts="pageSizeOpts?pageSizeOpts:$config.pageSizeOptsMag"
               @select-change="selectChange"
               @pageChange="pageSizeChange">
        <!--     :title="vm.$t(item.field)"   -->
        <DkTableColumn v-for="(item,index) in columns" :key="index" :field="item.field" :type="item.type"
                       :width="item.width"
                       :title="vm.$t(item.title?item.title: item.field)"
                       :resize-flag="index === columns.length - 1"
                       :switch-disabled="item.disabled"
                       @on-switch-change="onSwitchChange"></DkTableColumn>
      </DkTable>

      <!--已选列表-->
      <DkTable v-show="tabIndex === 1" :pageFlag="false" :pageTotalFlag="false" :primaryKey="selectKey"
               :id="'table-'+$options.name" ref="table-selected" :data="batchRowsPage" :operateFlag="true"
               :refreshSelect="false" :multiple="false" :show-setting-flag="false" :choose-flag="false"
              @delRow="delItem">
        <DkTableColumn v-for="(item,index) in columns" :key="index" :field="item.field" :type="item.type"
                       :title="vm.$t(item.title?item.title: 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 {request} from "@/api/base";

export default {
  name: 'multi-select',
  inject: {
    prop: {
      type: String,
      default: null
    },
    dkFormItem: {
      type: Object,
      default: null
    }
  },
  props: {
    value: {
      type: Array,
      default: null
    },
    //默认值
    defaultValue: {
      type: [Number, String],
      default: null
    },
    //主业务列名
    mainField: {
      type: String,
      default: null,
    },
    // 放大镜类型
    type: {
      type: String,
      default: null
    },
    // 最末级节点
    leafFlag: {
      type: Boolean,
      default: false
    },
    // 单据
    docCode: {
      type: String,
      default: ''
    },
    // 属性类型
    attributeType: {
      type: String,
      default: ''
    },
    //提示信息
    placeholder: {
      type: String,
      default: ''
    },
    // 比例的字段
    rateField: {
      type: String,
      default: '',
    },
    // 订单ID
    orderId: {
      type: Number,
      default: 0
    },
    //是否只读
    readonly: {
      type: Boolean,
      default: false
    },
    // 外部传入的查询条件
    otherCondition: {
      type: Object,
      default: null
    },
    // 是否是新建部门时使用
    organizationFlag: {
      type: Boolean,
      default: false
    },
    // 是否从表格中调用的
    tableFlag: {
      type: Boolean,
      default: false
    },
    // 选中是否自动设置主业务列为默认
    checkAutoSetMainField:{
      type: Boolean,
      default: true
    },
    // 主业务列显示文本
    mainFieldText:{
      type: String,
      default: '【主】'
    },
    // 主业务列默认id
    mainFieldId: {
      type: Number,
      default: undefined
    },
    // 页条数
    pageSize:{
      type:Number,
      default:null
    },
    // 是否开启分页
    pageFlag:{
      type:Boolean,
      default:false
    }
  },
  data() {
    const vm = window.vm
    let self = this
    return {
      vm: vm,
      colCount: 4,
      modalWidth: 600,
      // 选择的显示的数据
      selectedValue: '',
      documentKeyDownContent: Object,
      model: null,
      options: [],
      tableData: [],
      showModal: false,
      batchRowsPage: [],
      batchKeysPage: [],
      batchRowsPageSocial: [],
      batchKeysPageSocial: [],
      // 数据源的service
      service: {},
      // 详细的查询方法
      methodsNameDetail: '',
      //列设置
      columns: [],
      selectFlag: 'selectFlag',// 选择列的列名
      // 选择的key
      selectKey: '',
      // 选择的label
      selectLabel: '',
      // 查询条件
      searchCond: {},
      searchContent: [],
      searchTable: {},
      // 最大的条数
      maxTagCount: 1,
      placeholderData: '',
      clearFlag: false, // 是否点击清空按钮
      tabIndex: 0,
      tabsOptions: [
        {label: '选择列表', name: 'name1', index: 0},
        {label: '已选列表', name: 'name2', index: 1, clear: true},
      ],
      pageInfo: {
        total: 0,
        pageSize: self.pageSize?self.pageSize: this.$config.pageSize,
        currentPage: 1
      },
      pageSizeOpts:null,
    }
  },
  watch: {
    /**
     * @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
    },
    defaultValue(n, o) {
      //赋默认值
      this.setDefaultValue();
    },
    value(n, o) {
      if (!n || n.length == 0) {
        this.selectedValue = null;
      }
    },
    batchRowsPage(n, o) {
      //监听选择的数据,改变页签的数量
      if (n && n.length) {
        this.tabsOptions[1].label = '已选列表【' + n.length + '】';
      } else {
        this.tabsOptions[1].label = '已选列表';
      }
    },
    orderId(n, o) {
      // 如果Id改变，需要重新查询数据库
      // this.getDataTable();
    }
  },
  methods: {
    /**
     * @desc   : 切换tab
     * @author : 周兴
     * @date   : 2022/5/28 16:38
     */
    tabsClick(e, option) {
      this.tabIndex = option.index;
    },
    /**
     * @desc   : 删除已选
     * @author : 周兴
     * @date   : 2022/5/31 15:04
     */
    clearSelected() {
      this.clearAll();
    },
    /**
     * @desc   : 翻页
     * @author : 周兴
     * @date   : 2023/12/20 16:54
     */
    pageSizeChange(pageInfo){
      this.getDataTable(pageInfo.currentPage);
    },
    /**
     * @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;
          }
        }
      }
    },
    /**
     * @desc   : 点回车打开放大镜
     * @author : 周兴
     * @date   : 2022/12/14 11:32
     */
    handleInputKeydown(e) {
      if (e.key === 'Enter') {
        this.magnifierClick();
      }
    },
    /**
     *   @desc   : 监控checkbox值
     *   @date   : 2022/5/27 11:36
     *   @author : 寇珊珊
     */
    selectChange({batchRows, row, checked}) {
      //获取当前选中的checkbox
      let batchKeys = this.$refs['table-select'].batchKeys;
      this.batchKeysPage = [...batchKeys]
      if (this.rateField) {
        //定义每行数据中的百分比
        let allocationRatio = (100 / batchKeys.length).toFixed(2)
        //定义一个每个选中后的百分比相加的变量，用来给最后一个元素赋值
        let allocationRatioTotal = 0
        if (batchKeys && batchKeys.length > 0) {
          let rows = this.tableData.filter(it => batchKeys.includes(it[this.selectKey]));
          if (rows && rows.length > 0) {
            //数据取余2为0
            if (100 % rows.length == 0) {
              //循环将计算好的百分比放入数据中
              for (let i in rows) {
                this.$set(rows[i], this.rateField, parseFloat(allocationRatio))
              }
            } else { //数据取余2不为0
              //获取最后选中checkbox数组中最后一个元素
              let endList = rows.splice(-1)
              for (let i = 0; i < rows.length; i++) {
                allocationRatioTotal = allocationRatioTotal + parseFloat(allocationRatio)
                this.$set(rows[i], this.rateField, allocationRatio)
              }
              this.$set(endList[0], this.rateField, 100 - allocationRatioTotal)
            }
          }
        }
      }
      //根据勾选状态进行控制主业务标识列的状态
      this.setMain(row, checked);
      this.$nextTick(() => {
        this.batchRowsPage = this.tableData.filter(it => this.batchKeysPage.includes(it[this.selectKey])).map(m => m);
      })
    },
    /**
     * @desc   : 设置主业务信息
     * @author : 周兴
     * @date   : 2022/6/13 9:24
     */
    setMain(row, checked) {
      if (!this.mainField) return;
      //选中状态
      if (checked) {
        let filterRows = this.tableData.filter(it => it[this.mainField])
        if ((!filterRows || filterRows.length === 0)&&this.checkAutoSetMainField) {
          this.$set(row, this.mainField, true);
        }
      } else {
        //当前这行如果是true,就要把其他行的主业务标识置为true,从上往下
        if (this.rateField) {
          this.$set(row, this.rateField, 100);
        }
        if (row[this.mainField]) {
          this.$set(row, this.mainField, false);
          let batchKeys = this.$refs['table-select'].batchKeys;
          for (let i in this.tableData) {
            if (row.id != this.tableData[i].id && batchKeys.includes(this.tableData[i][this.selectKey])) {
              this.$set(this.tableData[i], this.mainField, true);
              break;
            }
          }
        }
      }
    },
    /**
     * @desc   : 开关开启后处理
     * @author : 周兴
     * @date   : 2022/6/13 10:34
     */
    onSwitchChange(e) {
      let batchKeys = this.$refs['table-select'].batchKeys;
      if (e.checked) {
        // 如果选中，需要增加前面的checkbox的勾选，并且去掉其他的主业务的勾选
        for (let i in this.tableData) {
          if (e.id !== this.tableData[i].id) {
            this.$set(this.tableData[i], this.mainField, false);
          }
        }
        // 如果没有勾选上，才会进行勾选
        if (!batchKeys.includes(e[this.selectKey])) {
          this.$refs['table-select'].setCheckedRow(e)
        }
      } else {
        // 如果去掉勾选，需要勾选下一个
        for (let i in this.tableData) {
          if (e.id != this.tableData[i].id && batchKeys.includes(this.tableData[i][this.selectKey])) {
            this.$set(this.tableData[i], this.mainField, true);
            break;
          }
        }
      }
    },
    /**
     * @desc   : 键盘事件
     * @author : 周兴
     * @date   : 2022/4/15 20:38
     */
    handleKeydown(e) {
      if (e.key === 'Enter') {
        this.magnifierClick()
      }
    },
    /**
     * @desc   : 清空事件
     * @author : 周兴
     * @date   : 2022/3/4 8:19
     */
    clear() {
      this.searchList = {}
      this.searchTable = {}
    },
    /**
     * @desc   : 获取表格数据
     * @author : 沈博
     * @date   : 2022/3/7 16:59
     */
    getDataTable(currentPage = 1) {
      let param = {...this.$refs['table-select'].pageInfo}
      param.docCode = this.docCode
      // 如果是最末级节点需要传递到后台
      param.leafFlag = this.leafFlag
      // 不分页 todo
      if(this.pageFlag){
        param.pageSize = this.pageSize?this.pageSize: this.$config.maxPageSize;
        param.currentPage = currentPage
      }
      param.ftyId = this.$store.state.user.ftyId
      // 拼接外部传入的其他参数otherCondition
      if (this.otherCondition) {
        param = Object.assign(param, this.otherCondition)
      }
      this.excute(this.service, this.service[this.methodsNameDetail], Object.assign(param, this.searchTable)).then(res => {
        if (res.code === 200) {
          this.batchKeysPage = []
          this.batchRowsPage = []
          let arr = []
          if (res.data && res.data.list) {
            arr = res.data.list;
          }
          if (!arr && res.data) {
            arr = res.data;
          }
          this.tableData = arr;
          if (param.currentPage == 1) {
            this.pageInfo.total = res.data.total
            this.pageInfo.currentPage = 1;
          }
          // console.log('value', this.value)
          // 根据传入的数据进行数据处理
          if (this.value && this.value.length > 0) {
            let filterRows = []
            let firstRow = null;
            // 如果value传递的不是数组，那么需要处理成数组
            this.value.forEach(it => {
              filterRows = arr.filter(row => row[this.selectKey] === it[this.selectKey] ||row[this.selectKey] === it )
              if (filterRows && filterRows.length > 0) {
                //给第一个行赋值 为了滚动定位 TODO
                // if(!firstRow){
                //   firstRow = filterRows[0];
                // }
                if (this.rateField) {
                  filterRows[0][this.rateField] = it[this.rateField]
                }
                filterRows[0][this.mainField] = it[this.mainField];
                if( it[this.selectLabel]){
                  it[this.selectLabel] = filterRows[0][this.selectLabel];
                }
                //设置勾选
                this.setCheckRow(it, filterRows[0]);
                //如果传入值只是id的数组，并且传入了主业务id，将此id的行选中
                if(this.mainFieldId&&filterRows[0][this.selectKey]===this.mainFieldId){
                  this.$set(filterRows[0], this.mainField, true);
                }
              }
            })
            // console.log('first',firstRow,this.value)
            //滚动到对应的行
            // this.$refs['table-select'].$refs['table'].scrollTo(0,500);
            //设置显示的名称
            this.setDisplayText();
          } else {
            // 没有点清空就根据传入的orderId进行查询
            if (!this.clearFlag) {
              // 要先处理下数据，兼容编辑
              if (this.orderId && this.orderId > 0) {
                this.tableData.forEach(row => {
                  // 设置勾选
                  if (row[this.selectFlag]) {
                    this.setCheckRow(row, row);
                  }
                })
                //设置显示的名称
                this.setDisplayText();
              }
            }
          }
        } else {
          this.$Message.warning(res.message)
        }
      })
    },
    /**
     * @desc   : 设置勾选
     * @author : 周兴
     * @date   : 2022/6/21 16:16
     */
    setCheckRow(it, row) {
      //传入值只有id的情况
      if(typeof it !== 'object'){
        if (!this.batchKeysPage.includes(it)) {
          this.batchKeysPage.push(it);
          this.batchRowsPage.push(row)
          this.$refs['table-select'].batchKeys = this.batchKeysPage;
          this.$refs['table-select'].batchRows = [...this.batchRowsPage];
        }
        this.$refs['table-select'].setCheckboxRow(row);
      }else{
        //传入行的情况
        if (!this.batchKeysPage.includes(it[this.selectKey])) {
          this.batchKeysPage.push(it[this.selectKey]);
          this.batchRowsPage.push(row)
          this.$refs['table-select'].batchKeys = this.batchKeysPage;
          this.$refs['table-select'].batchRows = [...this.batchRowsPage];
        }
        this.$refs['table-select'].setCheckboxRow(row);
      }
      // console.log('it',it,row,this.batchKeysPage,this.batchRowsPage)
    },
    /**
     * @desc   : 放大镜点击事件
     * @author : 沈博
     * @date   : 2022/3/7 14:21
     */
    magnifierClick(type) {
      if (this.readonly) {
        return;
      }
      // 如果focus,并且数据为空才会弹出选择框
      if (type && this.selectedValue) {
        return;
      }
      //打开从第一页开始
      // this.$refs['table-select'].pageInfo.currentPage = 1
      this.showModal = true
      if (this.model) {
        this.$refs['table-select'].batchKeys = [this.model]
        this.batchKeysPage = [this.model]
      }else if(this.value && this.value.length > 0){
        let batchKeys = this.value.map(it=>it[this.selectKey])
        if(this.$refs['table-select']){
          this.$refs['table-select'].batchKeys = batchKeys
          this.batchKeysPage = batchKeys
          // 查询已选数据
          this.getDataTableSelected();
        }
      }
    },
    /**
     * @desc   : 清空数据
     * @author : 周兴
     * @date   : 2022/3/17 17:29
     */
    clearAll() {
      this.clearFlag = true;
      this.showClear = false
      this.selectedValue = ''
      this.$refs['table-select']?.clearBatchKeys() //清空选择
      this.batchKeysPage = null
      this.batchRowsPage = null;
      this.$emit('ok', {rows: [], display: null});
    },
    /**
     * @desc   : modal变化事件
     * @author : 沈博
     * @date   : 2022/3/7 14:28
     */
    onVisibleChange(val) {
      if (val) {
        // this.getDataTable()
      } else {
        this.searchTable = {} // 关闭选择画面需要清空条件
      }
    },
    /**
     * @desc   : 通过已选的id获取数据
     * @author : 周兴
     * @date   : 2022/11/22 16:48
     */
    getDataTableSelected() {
      let batchKeys = this.$refs['table-select'].batchKeys;
      if (batchKeys && batchKeys.length > 0) {
        let param = {};
        param.currentPage = 1;
        param.pageSize = 10000;
        param.idList = batchKeys;
        param.userId = this.$store.state.user.id
        param.ftyId = this.$store.state.user.ftyId
        // 拼接外部传入的其他参数otherCondition
        if (this.otherCondition) {
          param = Object.assign(param, this.otherCondition)
        }
        this.excute(this.service, this.service[this.methodsNameDetail], param).then(res => {
          if (res.code === 200) {
            this.batchRowsPage = []
            if (res.data && res.data.list) {
              res.data.list.forEach(it => {
                this.batchRowsPage.push(it)
              })
              this.$refs['table-select'].batchRows = this.batchRowsPage;
            }
          }
        });
      }
    },
    /**
     * @desc   : 校验是否选择
     * @author : 沈博
     * @date   : 2022/3/7 15:44
     */
    checkBatch() {
      if (this.batchKeysPage.length <= 0) {
        this.$Message.warning('请先选择数据')
        return false
      }
      return true
    },
    /**
     * @desc   : 恢复数据
     * @author : 周兴
     * @date   : 2022/9/1 12:03
     */
    restore() {
      this.batchRowsPage = JSON.parse(JSON.stringify(this.batchRowsPageSocial))
      this.batchKeysPage = JSON.parse(JSON.stringify(this.batchKeysPageSocial))
      //设置显示的名称
      this.setDisplayText();
    },
    /**
     * @desc   : 确定点击事件
     * @author : 沈博
     * @date   : 2022/3/7 15:43
     */
    ok() {
      this.batchKeysPageSocial = JSON.parse(JSON.stringify(this.batchKeysPage))
      this.batchKeysPage = this.$refs['table-select'].batchKeys
      this.batchRowsPageSocial = JSON.parse(JSON.stringify(this.batchRowsPage))
      // 不用用batchRows，switch的数据不会变
      this.batchRowsPage = this.$refs['table-select'].getCheckRows();
      if (this.checkBatch()) {
        //主业务部门必须是门店
        // if (this.type === this.$config.MagnifierType.organization &&
        // this.batchRowsPage.some(s => s.ownerFlag && !s.flgStore)) {
        //   this.$Message.warning(this.$t('W_052'))
        //   return
        // }
        this.showModal = false
        let isShowOkEventFlag = true;
        //设置显示的名称
        this.setDisplayText(isShowOkEventFlag);
        //光标切回select组件
        this.$refs['input'].$refs.input.focus = true
        this.clearFlag = false;
        this.$emit('ok', {rows: this.batchRowsPage, display: this.selectedValue})
        // 清空查询条件
        this.$refs['searchCond']?.clearCondition();
        // 清空表格
        this.tableData = []
      }
    },
    /**
     * @desc   : 设置显示的名称
     * @author : 周兴
     * @date   : 2022/6/14 8:17
     */
    setDisplayText(isShowOkEventFlag) {
      //判断已选数据是否有
      if (this.batchRowsPage && this.batchRowsPage.length > 0) {
        // 把选择的数据显示出来，主的显示在第一位
        let display = ''
        let list = this.batchRowsPage.filter(it => it[this.mainField])
        // if (list && list.length > 0) {
        //   display = list[0][this.selectLabel] + this.mainFieldText
        // }
        // 从业务数据
        let subList = this.batchRowsPage.filter(it => !it[this.mainField])
        if(this.checkAutoSetMainField){
          if (subList && subList.length > 0) {
            display = list[0][this.selectLabel] + this.mainFieldText
            display += ' | ';
            subList.forEach(it => {
              display += it[this.selectLabel] + ' | '
            })
            display = display.substring(0, display.length - 2)
          } else {
            display = list[0][this.selectLabel]
          }
        }else{
          display=list.length>0?list[0][this.selectLabel] + this.mainFieldText + ' | ':''
          subList.forEach(it => {
            display += it[this.selectLabel] + ' | '
          })
          display = display.substring(0, display.length - 2)
        }
        this.selectedValue = display;
      } else {
        this.selectedValue = null;
      }
      if (!isShowOkEventFlag) {
        this.$emit('ok', {rows: this.batchRowsPage, display: this.selectedValue})
      }
    },
    /**
     * @desc   : 关闭点击事件
     * @author : 沈博
     * @date   : 2022/3/7 15:43
     */
    cancel() {
      // 清空查询条件
      this.$refs['searchCond']?.clearCondition();
      // 清空表格
      this.tableData = []
      this.showModal = false
    },
    /**
     * @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 && self.$refs.modal_search.showModal) {
          let btList = Object.values(self.$config.button);
          // Q：code = 81 查询
          btList.forEach(forIt => {
            if (code === 18 && forIt.hotKey?.toLowerCase() === e.key.toLowerCase()) {
              e.returnValue = false
              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/6/15 15:48
     */
    setDefaultValue() {
      if (this.defaultValue) {
        this.selectedValue = this.defaultValue
      }
    },
    /**
     * @desc   : 根据类型给属性赋值
     * @author : 周兴
     * @date   : 2022/3/16 18:12
     */
    setMagnifierProperty() {
      let self = this
      // 员工
      if (self.type === self.$config.MagnifierType.user) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'selectMultiStaff'
        self.searchCond = ['userCode', 'userName']
        self.selectKey = 'staffId'
        self.selectLabel = 'userName'
        self.columns = [
          {field: this.rateField, width: '150'},
          {field: 'userCode', width: '200'},
          {field: 'userName', width: '200'},
          {field: 'organizationName', width: '200'},
          {field: 'ownerFlag', width: '40', type: 'switch', disabled: false},
        ]
      }
      // 产品
      else if (self.type === this.$config.MagnifierType.product) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'getModelProductByPage'
        // 查询条件
        self.searchContent = [
          {
            valueFormat: {code: 'modelCode'},
          },
          {
            valueFormat: {code: 'modelName'},
          },
        ]
        self.modalWidth = 600
        self.colCount = 2
        self.selectKey = 'modelId'
        self.selectLabel = 'modelName'
        self.columns = [
          {field: 'codeName', width: '150',title:self.$t('pdtModel')},
          {field: 'categoryName', width: '150'},
          {field: 'ownerFlag', width: '100', type: 'switch', disabled: false},
          {field: 'remarks', width: 'auto'},
        ]
      }
      // 部门
      else if (self.type === self.$config.MagnifierType.org) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'selectMultiOrg'
        self.searchCond = ['orgName', 'orgCode']
        self.selectKey = 'orgId'
        self.selectLabel = 'orgName'
        self.columns = [
          {field: this.rateField, width: '150'},
          {field: 'orgName', width: '200'},
          {field: 'orgCode', width: '200'},
          {field: 'ownerFlag', width: '40', type: 'switch', disabled: false},
        ]
      }
      // 结算方式
      else if (self.type === self.$config.MagnifierType.settlementType) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'selectSettlementTypeByOrgId'
        self.selectKey = 'typeId'
        self.selectLabel = 'typeName'
        self.columns = [
          {field: 'typeName', width: 'auto'},
          {field: 'settlementTypesFlgDefault', width: '40', type: 'switch', disabled: false},
        ]
      }
        // 仓库
        /*else if (self.type === self.$config.MagnifierType.warehouse) {
          self.service = this.$service.commonService
          self.methodsNameDetail = 'getWarehouse'
          self.searchCond = ['warehouseName']
          self.selectKey = 'whId'
          self.selectLabel = 'warehouseName'
          self.columns = [
            {field: 'warehouseName', minWidth: 'auto'},
            {field: 'warehouseFlgDefault', width: '40', type: 'switch', disabled: false},
          ]
        }*/
      // 仓库
      else if (self.type === self.$config.MagnifierType.warehouse) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'getWarehouseByPage' //详细函数名称,目前对应后台的查询接口名称
        self.searchCond = [
          {itemCode: 'whName'},                       //查询条件
          {itemCode: 'whCode'},
        ]
        self.selectKey = 'whId'                       //主键
        self.selectLabel = 'whName'                   //显示的列
        self.modalWidth = 700
        self.colCount = 2
        self.columns = [
          {field: 'whName', width: '100'},          //查询出来的字段以及宽度
          {field: 'whCode', width: '100'},
          {field: 'mmCode', width: '100'},
          {field: 'directorName', width: '100'},
          {field: 'contactsName', width: '100'},
          {field: 'contactNo', width: '100'},
          {field: 'cpName', width: '100'},
          {field: 'remarks', width: '100'},
          {field: 'flgDefault', title: "flgDefaultWh", width: '100', type: 'switch', disabled: false},
        ]
      }
      //资金账号
      else if (self.type === self.$config.MagnifierType.capitalAccount) {
        self.service = this.$service.commonService
        self.methodsName = 'getCapitalAccount'
        self.methodsNameDetail = 'getCapitalAccountByPage'
        self.searchCond = [
          {itemCode: 'capitalName'},
          {itemCode: 'capitalType'},
        ]
        self.selectKey = 'capitalId'
        self.selectLabel = 'capitalName'
        self.modalWidth = 700
        self.colCount = 2
        self.columns = [
          {field: 'capitalName', width: '100'},
          {field: 'mmCode', width: '100'},
          {field: 'capitalType', width: '100'},
          {field: 'cpName', width: '100'},
          {field: 'openingCompany', width: '100'},
          {field: 'openingBank', width: '100'},
          {field: 'bankAccount', width: '100'},
          {field: 'remarks', width: '100'},
          {field: 'flgDefault', title: 'flgDefaultCa', width: '100', type: 'switch', disabled: false},
        ]
      }
      //可判定分级
      else if (self.type === self.$config.MagnifierType.judgeGrade) {
        self.service = this.$service.productGradeService
        self.methodsNameDetail = 'selectByCond'
        self.selectKey = 'gradeId'
        self.selectLabel = 'gradeName'
        self.columns = [
          {field: 'gradeName', width: '100'},
          {field: 'defGradeId', title: 'defGradeId', width: '100', type: 'switch', disabled: false},
        ]
      }
      // 载具
      else if (self.type === this.$config.MagnifierType.modelCarrier) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'getModelCarrierByPage'
        // 查询条件
        self.searchContent = [
          {
            valueFormat: {code: 'modelCode'},
          },
          {
            valueFormat: {code: 'modelName'},
          },
        ]
        self.otherCondition
        self.modalWidth = 600
        self.colCount = 2
        self.selectKey = 'modelId'
        self.selectLabel = 'modelName'
        self.columns = [
          {field: 'modelCodeName', width: '150',title:self.$t('carModelCode')},
          {field: 'modelCategoryLevelName', width: '150', title:self.$t('modelCategoryItemName')},
          {field: 'ownerFlag', width: '100', type: 'switch', disabled: false},
          {field: 'remarks', width: 'auto'},
        ]
      }
    }
  },
  created() {
    this.setMagnifierProperty() // 根据类型给属性赋值
    if (!this.placeholderData) {
      this.placeholderData = vm.$t('inputWords', {'search-name': vm.$t(this.prop)})
    }
    //赋默认值
    this.setDefaultValue();
  },
  mounted() {
    // this.getDataTable()
  }
}
</script>
<style scoped>
/deep/ .ivu-modal-body {
  padding: 0 10px 10px 10px;
  background: #eaedf7 !important;
}

/deep/ .btn-div {
  position: relative;
}

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

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

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

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

.input-class {
  height: 30px;
  line-height: 30px;
}


</style>

