<template>
  <div>
    <div style="display: flex;align-items: center;">
      <InputPop ref="input" :value="selectedValue" :clearable="true" @on-focus="magnifierClick(true)" @on-keydown="handleInputKeydown"
                readonly @on-clear="clearAll"/>
<!--      <div class="close-class"-->
<!--           v-if="!readonly && selectedValue && selectedValue.length > 0 && type !== $config.MagnifierType.warehouseForOrg">-->
<!--        <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="change-class"
      :title="vm.$t('chooseData')">
      <BaseIndexButtonGroup #left>
        <BaseIndexButton ref="search" name="search" @click="getDataTable" v-if="type != $config.MagnifierType.user &&
          type != $config.MagnifierType.organization && type != $config.MagnifierType.warehouseForOrg &&
          type != $config.MagnifierType.settlementType"></BaseIndexButton>
        <BaseIndexButton ref="position" name="position" @click="positionDataTable" v-if="type == $config.MagnifierType.user ||
          type == $config.MagnifierType.organization || type == $config.MagnifierType.warehouseForOrg ||
          type == $config.MagnifierType.settlementType"></BaseIndexButton>
        <BaseIndexButton :finalFlag="true" ref="clear" name="clear"
                         @click="clear"></BaseIndexButton>
      </BaseIndexButtonGroup>
      <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(true)"></DkTabs>

      <DkTable v-show="tabIndex === 0" :primaryKey="selectKey" :clear-check-flag="false" ref="table-select"
               :id="'table-'+$options.name" :data="tableData"
               name="table"
               @select-change="selectChange" :checkMethodFlag=true
               :page-flag="false"
               :show-setting-flag="false"
               :link-click-checked="!this.rateField" :refreshSelect="false"
               :checkMethod="(({row}) => !row.disabled)"
               @select-all="selectAll"
      >
        <div v-for="(item,index) in columns" :key="index">
          <DkTableColumn v-if="!item.flgCanInput" :field="item.field" :type="item.type"
                         :width="item.width"
                         :title="item.title ? item.title :vm.$t(item.field)" :resize-flag="index === columns.length - 1"
                         :disabled="item.disabled"
                         @on-switch-change="onSwitchChange"></DkTableColumn>
          <vxe-column v-else :field="item.field" :type="item.type"
                      :width="item.width"
                      class-name="input-class"
                      :title="vm.$t(item.field)" :resize-flag="index === columns.length - 1" :disabled="item.disabled"
                      @on-switch-change="onSwitchChange">
            <template #default="{ row }">
              <vxe-input size="mini" :min="0" :max="100"
                         type="number" v-model="row[item.field]" @change="onNumberChange"></vxe-input>
            </template>
          </vxe-column>
        </div>

        <!--        <DkTableColumn width="80" type="radio" :title="title" :radio-right="true" ></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">
        <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" :type="item.type"
                       :title="item.title ? 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'

export default {
  name: 'multi-select',
  inject: {
    prop: {
      type: String,
      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: ''
    },
    // 是否需要公司Id
    cpId: {
      type: Boolean,
      default: true
    },
    // 是否需要系统id
    sysId: {
      type: Boolean,
      default: true
    },
    // 比例的字段
    rateField: {
      type: String,
      default: '',
    },
    // 订单ID
    orderId: {
      type: String,
    },
    //是否只读
    readonly: {
      type: Boolean,
      default: false
    },
    // 外部传入的查询条件
    otherCondition: {
      type: Object,
      default: null
    },
    // 是否是新建部门时使用
    organizationFlag: {
      type: Boolean,
      default: false
    },
    // 是否显示主字
    zhuFlag: {
      type: Boolean,
      default: true
    },
    // 是否校验主标识
    flgCheckMain: {
      type: Boolean,
      default: false
    },
    // 是否查询数据标识
    selectDataFlag: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const vm = window.vm
    return {
      vm: vm,
      colCount: 4,
      modalWidth: 600,
      // 选择的显示的数据
      selectedValue: '',
      documentKeyDownContent: Object,
      tabIndex: 0,
      model: null,
      options: [],
      tableData: [],
      showModal: false,
      batchRowsPage: [],
      batchKeysPage: [],
      batchRowsPageSocial: [],
      batchKeysPageSocial: [],
      // 数据源的service
      service: {},
      // 详细的查询方法
      methodsNameDetail: '',
      //列设置
      columns: [],
      selectCol: 'selectFlag',// 选择列的列名
      // 选择的key
      selectKey: '',
      // 选择的label
      selectLabel: '',
      // 查询条件
      searchCond: {},
      searchContent: [],
      searchTable: {},
      // 最大的条数
      maxTagCount: 1,
      placeholderData: '',
      clearFlag: false, // 是否点击清空按钮
      autoRateCalc: true, // 是否自动计算比率
      tabsOptions: [
        {label: '选择列表', name: 'name1', index: 0},
        {label: '已选列表', name: 'name2', index: 1, clear: true},
      ],
    }
  },
  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();
    },
    orderId(n, o) {
      if(n){
        // 如果Id改变，需要重新查询数据库
        this.getDataTable();
      }
    },
    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;
    },
    /**
     * @desc   : 删除已选
     * @author : 周兴
     * @date   : 2022/5/31 15:04
     */
    clearSelected(val) {
      this.clearAll(val);
    },
    /**
     * @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   : 2023/11/13 16:01
     */
    handleInputKeydown(e) {
      if (e.key === 'Enter') {
        this.magnifierClick();
      }
    },
    /**
     *   @desc   : 监控checkbox值
     *   @date   : 2022/5/27 11:36
     *   @author : 寇珊珊
     */
    selectChange({batchRows, row, checked}) {
      //组织机构选择仓库，如果存在禁用行，则必须选择
      if (this.type === this.$config.MagnifierType.warehouseForOrg && row.disabled) {
        if (!this.$refs['table-select'].batchKeys.some(s => s === row[this.selectKey])) {
          this.$refs['table-select'].batchKeys.push(row[this.selectKey])
          this.$nextTick(() => {
            this.$refs['table-select'].$refs.table.setCheckboxRow(this.tableData[0], true)
          })
        }
      }
      //获取当前选中的checkbox
      let batchKeys = this.$refs['table-select'].batchKeys;
      this.batchKeysPage = [...batchKeys]
      if (this.rateField && this.autoRateCalc) {
        //定义每行数据中的百分比
        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   : 2023-11-15 14:39
     */
    selectAll(checked) {
      //组织机构选择仓库，如果存在禁用行，则默认选中
      if (checked && this.type === this.$config.MagnifierType.warehouseForOrg &&
        this.tableData.some(s => s.disabled && s[this.mainField])) {
        this.$refs['table-select'].selectChange({
          checked: false,
          row: this.tableData.filter(f => f.disabled)[0],
          cellClick: false
        })
      }
    },
    /**
     * @desc   : 设置主业务信息
     * @author : 周兴
     * @date   : 2022/6/13 9:24
     */
    setMain(row, checked) {
      if (!this.mainField) return;
      // 组织机构选择默认仓库，如果是整行禁用不自动修改主标识
      if (this.$config.MagnifierType.warehouseForOrg === this.type && row.disabled) {
        return
      }
      //选中状态
      if (checked) {
        // 其他都去掉选中状态
        // let filterRows = this.tableData.filter()
        let filterRows = this.tableData.filter(it => it[this.mainField])
        if (!filterRows || filterRows.length === 0) {
          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[this.selectKey] != this.tableData[i][this.selectKey] && 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) {
      //组织机构选择仓库，如果是禁用行已经是默认，则不自动修改主标识
      if (this.type === this.$config.MagnifierType.warehouseForOrg &&
        this.tableData.some(s => s.disabled && s[this.mainField])) {
        this.$nextTick(() => {
          for (let it of this.tableData.filter(f => !f.disabled && f[this.mainField])) {
            it[this.mainField] = false
          }
        })
        return
      }

      let batchKeys = this.$refs['table-select'].batchKeys;
      if (e.checked) {
        // 如果选中，需要增加前面的checkbox的勾选，并且去掉其他的主业务的勾选
        for (let i in this.tableData) {
          if (e[this.selectKey] !== this.tableData[i][this.selectKey]) {
            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[this.selectKey] != this.tableData[i][this.selectKey] && 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 = {}
      // this.getDataTable() // 重新查询
    },
    /**
     * @desc   : 获取表格数据
     * @author : 沈博
     * @date   : 2022/3/7 16:59
     */
    getDataTable() {
      let param = {...this.$refs['table-select'].pageInfo}
      if (this.cpId) {
        param.cpId = this.$store.state.user.cpId
      }
      param.userId = this.$store.state.user.id
      param.orgId = this.$store.state.user.orgId
      // 如果是最末级节点需要传递到后台
      param.leafFlag = this.leafFlag
      // 不分页
      param.pageSize = null
      // 如果是结算方式或仓库、资金账户，需要赋值给
      if (this.type === this.$config.MagnifierType.settlementType || this.type === this.$config.MagnifierType.warehouse
            ||this.type === this.$config.MagnifierType.moneyAccount) {
        param['orgId'] = this.orderId;
        if (this.organizationFlag) {
          param.organizationFlag = true;
        }
      } else {
        param['orderId'] = this.orderId?this.orderId:null
      }

      // 拼接外部传入的其他参数otherCondition
      if (this.otherCondition) {
        param = Object.assign(param, this.otherCondition)
      }
      //退换补 不用查询
      if (!this.selectDataFlag) {
        return
      }
      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 = res.data.list || res.data;
          this.tableData = arr;
          // 根据传入的数据进行数据处理
          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])
              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];
                it[this.selectLabel] = filterRows[0][this.selectLabel];
                //设置勾选
                this.setCheckRow(it, filterRows[0]);
              }
            })
            // 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.tableData.forEach(row => {
                  // 设置勾选
                  if (row[this.selectCol]) {
                    this.setCheckRow(row, row);
                  }
                })
                //设置显示的名称
                this.setDisplayText();
              }
            }
          }
        } else {
          this.$Message.error(res.message)
        }
      })
    },
    /**
     * @desc   : 设置勾选
     * @author : 周兴
     * @date   : 2022/6/21 16:16
     */
    setCheckRow(it, row) {
      if (!this.batchKeysPage.includes(it[this.selectKey])) {
        this.batchKeysPage.push(it[this.selectKey]);
        this.batchRowsPage.push(it)
        this.$refs['table-select'].batchKeys = this.batchKeysPage;
        this.$refs['table-select'].batchRows = [...this.batchRowsPage];
      }
      this.$refs['table-select'].setCheckboxRow(row);
    },
    /**
     * @desc   : 放大镜点击事件
     * @author : 沈博
     * @date   : 2022/3/7 14:21
     */
    magnifierClick(type) {
      if (this.readonly) {
        return;
      }
      // 如果focus,并且数据为空才会弹出选择框
      if (type && this.selectedValue) {
        return;
      }
      this.showModal = true
    },
    /**
     * @desc   : 清空数据
     * @author : 周兴
     * @date   : 2022/3/17 17:29
     */
    clearAll(val) {
      // 改成如果有主仓标识，不能清空
      if (val) {
        let data = this.tableData.filter(it => it.warehouseFlgDefault)
        if (data && data.length > 0) {
          return;
        }
      }
      this.clearFlag = true;
      this.showClear = false
      this.selectedValue = ''
      this.model = null;
      this.$refs['table-select']?.clearBatchKeys() //清空选择
      this.batchKeysPage = null
      this.batchRowsPage = null;
      if (this.tableData) {
        this.tableData.forEach(it => {
          this.$set(it, this.mainField, false);
          this.$set(it, this.rateField, 100)
        })
      }
      this.$emit('ok', []);
      this.$emit('input', [])
    },
    /**
     * @desc   : modal变化事件
     * @author : 沈博
     * @date   : 2022/3/7 14:28
     */
    onVisibleChange(val) {
      if (val) {
        // console.log('f',this.showModal)
        this.$nextTick(()=>{
          //打开从第一页开始
          this.$refs['table-select'].pageInfo.currentPage = 1
          if (this.model) {
            this.$refs['table-select'].batchKeys = [this.model]
            this.batchKeysPage = [this.model]
          }
          this.$refs['table-select'].selectAll({checked: false})
          // console.log('t1')
          // 查询数据
          this.getDataTable()
        })
      } else {
        this.autoRateCalc = true;
        this.searchTable = {} // 关闭选择画面需要清空条件
      }
    },
    /**
     * @desc   : 校验是否选择
     * @author : 沈博
     * @date   : 2022/3/7 15:44
     */
    checkBatch() {
      if (this.batchKeysPage.length <= 0) {
        this.$Message.error('请先选择数据')
        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.error(this.$t('W_052'))
        //   return
        // }

        //必须选择主数据
        if (this.type === this.$config.MagnifierType.organization
          || this.type === this.$config.MagnifierType.user
          || this.type === this.$config.MagnifierType.homeDesigner
          || this.type === this.$config.MagnifierType.warehouse
          || this.flgCheckMain) {
          if (!(this.batchRowsPage.some(s => s[this.mainField]))) {
            this.$Message.error(this.$t('W_130'))
            return
          }
          // 手动输入比例时，计算合计是否等于100
          if (!this.autoRateCalc) {
            let sumRate = 0;
            this.batchRowsPage.forEach(it => {
              sumRate += parseFloat(it.allocationRatio);
            })
            if (sumRate != 100) {
              this.$Message.error(this.$t('W_131'))
              return
            }
          }
        }
        this.showModal = false
        let isShowOkEventFlag = true;
        //光标切回select组件
        this.$refs['input'].$refs.input.focus = true
        this.clearFlag = false;
        this.$emit('ok', this.batchRowsPage)
        //设置显示的名称
        this.$nextTick(() => {
          this.setDisplayText(isShowOkEventFlag);
        })
      }
    },
    /**
     * @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) {
          if (this.zhuFlag) {
            //家装设计师显示 =  家装公司 + 家装设计师
            if (this.type === this.$config.MagnifierType.homeDesigner) {
              display = '【' + list[0].dcName + '】' + list[0][this.selectLabel] + '【主】'
            } else {
              display = list[0][this.selectLabel] + '【主】'
            }
          } else {
            display = list[0][this.selectLabel]
          }
        }
        // 从业务数据
        list = this.batchRowsPage.filter(it => !it[this.mainField])
        if (list && list.length > 0) {
          display += ',';
          list.forEach(it => {
            display += it[this.selectLabel] + ','
          })
          display = display.substring(0, display.length - 1)
        }
        this.selectedValue = display;
      } else {
        this.selectedValue = null;
      }
      if (!isShowOkEventFlag) {
        this.$emit('ok', this.batchRowsPage)
      }
    },
    /**
     * @desc   : 关闭点击事件
     * @author : 沈博
     * @date   : 2022/3/7 15:43
     */
    cancel() {
      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
        }
        let btList = []
        for (let itKey in buttonList) {
          if (!buttonList[itKey].includes('(')) {
            continue
          }
          btList.push({
            name: itKey,
            hotKey: buttonList[itKey].substring(buttonList[itKey].length - 2, buttonList[itKey].length - 1)
          })
        }
        //只有modal弹出才能可见
        if (self.$refs.modal_search && self.$refs.modal_search.showModal) {
          // 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
        }
      }
    },
    /**
     * @desc   : 设置显示值
     * @author : 周兴
     * @date   : 2022/6/15 15:48
     */
    setDefaultValue() {
      if (this.defaultValue) {
        if (this.zhuFlag) {
          this.selectedValue = this.defaultValue + '【主】'
        } else {
          this.selectedValue = this.defaultValue
        }
      }
    },
    /**
     * @desc   : 是否自动计算比率
     * @author : 付斌
     * @date   : 2023-10-19 10:55
     */
    onNumberChange(val) {
      //console.log("改数", val)
      // 不自动计算比率
      this.autoRateCalc = false;
    },
    /**
     * @desc   : 定位数据
     * @author : 付斌
     * @date   : 2023-11-10 17:01
     */
    positionDataTable() {
      let param = {}
      param = Object.assign(param, this.searchTable)
      const tableColumns = this.$refs['table-select'].getTableColumn();
      let fields = tableColumns.visibleColumn;

      // 获取当前行
      let currentIndex = this.$refs['table-select'].getCurrentRowIndex()
      if (!currentIndex && currentIndex != 0) {
        currentIndex = -1;
      }

      let table = this.tableData;
      let flag = false;
      for (let i = currentIndex + 1; i < table.length; i++) {
        flag = this._changeFindItem(table[i], fields, param.positionInfo)
        if (flag) {
          return
        }
      }
      // 从第一行开始，再查一遍
      if (!flag) {
        currentIndex = -1;
        for (let i = currentIndex + 1; i < table.length; i++) {
          flag = this._changeFindItem(table[i], fields, param.positionInfo)
          if (flag) {
            return
          }
        }
      }
    },
    /**
     * @desc   : 匹配定位数据
     * @author : 付斌
     * @date   : 2023-11-13 9:14
     */
    _changeFindItem(item, fields, searchText) {
      // 模糊查询
      for (let it of fields) {
        // 模糊
        if ((item[it.field] + '').indexOf(searchText) >= 0) {
          // 定位当前行
          this.$refs['table-select'].setCurrentRow(item);
          this.$nextTick(() => {
            this.$refs['table-select'].scrollToRow(item);
          });
          return true;
        }
      }
      return false;
    },
    /**
     * @desc   : 根据类型给属性赋值
     * @author : 周兴
     * @date   : 2022/3/16 18:12
     */
    setMagnifierProperty() {
      let self = this
      // 部门
      if (self.type === self.$config.MagnifierType.org) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'getMultiOrg'
        self.searchContent = [
          {itemCode: 'orgName'},                       //查询条件
          {itemCode: 'orgCode'},
        ]
        self.selectKey = 'orgId'
        self.selectLabel = 'orgName'
        self.columns = [
          {field: this.rateField, width: '150', flgCanInput: true},
          {field: 'orgName', width: '200'},
          {field: 'orgCode', width: '200'},
          {field: 'ownerFlag', width: '40', type: 'switch', disabled: false},
        ]
      }
      // 员工
      else if (self.type === self.$config.MagnifierType.staff) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'getMultiStaff'
        self.searchContent = [
          {itemCode: 'staffName'},                       //查询条件
          {itemCode: 'staffCode'},
        ]
        self.selectKey = 'staffId'
        self.selectLabel = 'staffName'
        self.columns = [
          {field: this.rateField, width: '150', flgCanInput: true},
          {field: 'staffCode', width: '200'},
          {field: 'staffName', width: '200'},
          {field: 'orgName', width: '200'},
          {field: 'ownerFlag', width: '40', type: 'switch', disabled: false},
        ]
      }
      // 仓库
      else if (self.type === self.$config.MagnifierType.warehouse) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'getMultiWarehouse' //详细函数名称,目前对应后台的查询接口名称
        self.searchContent = [
          {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: 'contactPhone', width: '100'},
          {field: 'supervisor', width: '100'},
          {field: 'remarks', width: '100'},
          {field: 'ownerFlag', width: '40', type: 'switch', disabled: false},
        ]
      }
      //资金账号
      else if (self.type === self.$config.MagnifierType.moneyAccount) {
        self.service = this.$service.commonService
        self.methodsNameDetail = 'getMultiMoneyAccount'
        self.searchContent = [
          {itemCode: 'macCode'},
          {itemCode: 'macName'},
        ]
        self.selectKey = 'macId'
        self.selectLabel = 'macName'
        self.modalWidth = 700
        self.colCount = 2
        self.columns = [
          {field: 'macCode', width: '100'},
          {field: 'macName', width: '100'},
          {field: 'macType', width: '100'},
          {field: 'remarks', width: '100'},
          {field: 'ownerFlag', width: '40', type: 'switch', disabled: false},
        ]
      }
    }
  },
  created() {
    this.setMagnifierProperty() // 根据类型给属性赋值
    if (!this.placeholderData) {
      this.placeholderData = vm.$t('inputWords', {'search-name': vm.$t(this.prop)})
    }
    //赋默认值
    this.setDefaultValue();
  },
  mounted() {
    // 如果orderId有值，查询数据
    if(this.orderId){
      this.getDataTable()
    }
  }
}
</script>
<style scoped>
/deep/ .ivu-modal-body {
  padding: 0 10px 10px 10px;
}

/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;
}

/**
 * @desc   : 关闭的样式
 * @author : 周兴
 * @date   : 2022/6/14 8:29
 */
.close-class {
  cursor: pointer;
  width: 24px;
  position: absolute;
  top: 5px;
  right: 20px;
  align-items: center;
  justify-content: center;
  height: 24px;
  color: #a0a5ac;
  z-index: 99;
}

/deep/ .input-class .vxe-input {
  height: 28px !important;
  line-height: 26px !important;
  display: flex;
  align-items: center;
  padding-top: 4px;
}


</style>

