<!-- @desc:查询界面  @auth:周兴  @time:2023/2/19 14:48 -->
<template>
  <DkModal
      width="1100"
      ref="modal_search"
      v-model="visible"
      @modalOk="ok"
      @modalCancel="cancel"
      :title="title">
    <BaseIndexButtonGroup>
      <template #left>
        <BaseIndexButton ref="search" name="search" @click="searchData"></BaseIndexButton>
        <BaseIndexButton :finalFlag="true" ref="clear" name="clear" @click="clear"></BaseIndexButton>
      </template>
    </BaseIndexButtonGroup>

    <SearchCond id="search-cond-div" width="1000px" v-if="searchContent && searchContent.length > 0" ref="searchCond"
                v-model="searchCond" :setFlag="false" :searchContent="searchContent" :col-count="4"></SearchCond>
    <div style="width: 100%;height: 10px"></div>

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

      <!--多选-->
      <DkTable v-show="tabIndex === 0" :primaryKey="primaryKey"
               :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"
               @pageChange="pageSizeChange"
               @chooseData="chooseData"
      >
        <DkTableColumn v-for="(item,index) in columns" :key="index" :field="item.field"
                       :title="vm.$t(item.field)" :width="item.width"
                       :resize-flag="index === columns.length - 1"></DkTableColumn>
      </DkTable>

      <DkTable v-show="tabIndex === 1" :pageFlag="false" :pageTotalFlag="false" :primaryKey="primaryKey"
               :id="'table-'+$options.name"
               :choose-flag="multiple"
               name="table" :data="batchRowsPage" :operateFlag="true" :height="tableHeight"
               size="mini" :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"
                       :title="vm.$t(item.field)" :width="item.width"
                       :resize-flag="index === columns.length - 1"></DkTableColumn>
      </DkTable>
    </div>

    <!--单选-->
    <DkTable v-else :primaryKey="primaryKey" :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"
             :seq-tip-content="vm.$t('doubleSeq')"
             :choose-data-flag="true"
             :linkClickChecked="true" @pageChange="pageSizeChange"
             @chooseData="chooseData"
    >
      <DkTableColumn v-for="(item,index) in columns" :key="index" :field="item.field"
                     :title="item.title" :width="item.width"
                     :type="item.type" :switch-disabled="item.switchDisabled"
                     :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>
</template>

<script>
import {button as buttonList} from "@/locale/lang/zh-CN";

export default {
  name: "MyMessage",
  data() {
    const vm = window.vm;
    let self = this;
    return {
      documentKeyDownContent: Object,
      vm: vm,
      title: '系统提示',//标题
      content: '确定要这么做吗？',//主体内容
      visible: false,//显示控制
      cancelFunc: () => {
      },//取消回调
      okFunc: () => {
      },//确定回调
      okText: vm.$t('confirm'),
      cancelText: vm.$t('close'),
      pageInfo: {
        total: 0,
        pageSize: self.$config.pageSize,
        currentPage: 1
      },
      tabIndex: 0,
      tabsOptions: [
        {label: '选择列表', name: 'name1', index: 0},
        {label: '已选列表', name: 'name2', index: 1, clear: true},
      ],
      chooseLabel: (h) => {
        return h('div', [
          h('span', '已选'),
          h('Badge', {
            props: {
              count: self.batchRowsPage ? self.batchRowsPage.length : null
            }
          })
        ])
      },
      searchContent: [], // 查询条件
      searchCond: {},
      //列设置
      columns: [],
      tableData: [],
      batchRowsPage: [],
      batchKeysPage: [],
      // 数据源的service
      service: {},
      // 查询方法名字
      methodsName: '',

      otherCondition: null, // 其他查询条件
      multiple: false, // 是否多选
      primaryKey: '',// 主键Id
      type: null,// 查询的类型
      tableHeight: 400,// 列表高度
    }
  },
  methods: {
    /**
     * @desc   : 选择数据
     * @author : 周兴
     * @date   : 2023/2/19 18:46
     */
    chooseData(row) {
      this.okFunc({batchKeys: [row[this.primaryKey]], batchRows:[row] , searchCond: this.searchCond._value})
      this.visible = false;
    },
    /**
     * @desc   : 选择数据
     * @author : 周兴
     * @date   : 2023/2/19 16:00
     */
    ok() {
      if (this.checkBatch()) {
        // 重新去keys，考虑到可能会有无效的数据
        this.batchKeysPage = [...this.$refs['table-select'].batchKeys]
        this.batchRowsPage = [...this.$refs['table-select'].batchRows]
        this.okFunc({batchKeys: this.batchKeysPage, batchRows: this.batchRowsPage, searchCond: this.searchCond._value})
        this.visible = false;
      }
    },
    /**
     * @desc   : desc
     * @author : 周兴
     * @date   : 2023/2/19 15:59
     */
    cancel() {
      this.visible = false
    },
    /**
     * @desc   : 校验是否选择
     * @author : 沈博
     * @date   : 2022/3/7 15:44
     */
    checkBatch() {
      if (this.$refs['table-select'].batchKeys.length <= 0) {
        this.$Message.warning('请先选择数据')
        return false
      }
      return true
    },
    /**
     * @desc   : 设置查询条件
     * @author : 周兴
     * @date   : 2022/3/4 17:03
     */
    setCondition(val) {
      if (val._value) {
        this.searchList = val._value
        let keys = Object.keys(this.searchList);
        for (let i in keys) {
          // 处理数据 把空字符串处理为undifined
          if (this.searchList[keys[i]] == '') {
            this.searchList[keys[i]] = undefined;
          }
        }
      } else {
        this.searchList = this.pageInfo
      }
    },
    /**
     * @desc   : 查询，从第一页开始
     * @author : 周兴
     * @date   : 2023/2/24 10:45
     */
    searchData(){
      this.pageInfo.currentPage = 1;
      this.getDataTable();
    },
    /**
     * @desc   : 查询数据
     * @author : 周兴
     * @date   : 2023/2/19 15:20
     */
    getDataTable() {
      let param = {...this.$refs['table-select'].pageInfo}
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      param.userId = vm.$store.state.user.id
      param.ftyId = vm.$store.state.user.ftyId
      // 拼接外部传入的其他参数otherCondition
      if (this.otherCondition) {
        param = Object.assign(param, this.otherCondition)
      }
      if (this.searchCond) {
        param = Object.assign(param, this.searchCond._value)
      }
      this.excute(this.service, this.methodsName, param).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          let arr = [...res.data]
          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.primaryKey]).length > 0) {
                  this.$refs['table-select'].setCheckboxRow(it);
                }
              })
            }
          } else {
            if (this.batchKeysPage && this.batchKeysPage.length > 0) {
              let keyName = this.telephone ? 'customerPhone' : this.primaryKey;
              this.batchRowsPage = []
              arr.forEach(it => {
                if (it[this.primaryKey] && this.batchKeysPage && this.batchKeysPage.includes(it[keyName])) {
                  this.batchRowsPage.push(it);
                }
              })
            }
          }
          this.tableData = arr
          // 单选需要设置当前行状态
          if (!this.multiple && this.batchRowsPage && this.batchRowsPage.length > 0) {
            this.$nextTick(() => {
              this.$refs['table-select'].setCurrentRow(this.batchRowsPage[0]);
            })
          }
          this.$refs['table-select'].pageInfo.total = res.data.total
        } else {
          this.$Message.warning(res.message)
        }
      })
    },
    /**
     * @desc   : 翻页
     * @author : 周兴
     * @date   : 2022/3/17 14:57
     */
    pageSizeChange(pageInfo) {
      this.pageInfo = pageInfo
      this.getDataTable() // 查询数据
    },
    /**
     * @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   : 2023/2/19 15:28
     */
    clearSelected() {
      this.selectedKeys = []
      this.selectedTable = []
      this.batchKeysPage = []
      this.batchRowsPage = []
      this.$refs['table-select'].clearBatchKeys();
    },
    /**
     * @desc   : 切换事件
     * @author : 周兴
     * @date   : 2023/2/19 15:22
     */
    tabsClick(e, option) {
      this.tabIndex = option.index;
    },
    /**
     * @desc   : 删除一行
     * @author : 周兴
     * @date   : 2023/2/19 15:24
     */
    delItem(rowIndex) {
      let row = this.batchRowsPage[rowIndex]
      // 如果存在就删除
      if (row) {
        let key = row[this.primaryKey];
        this.batchRowsPage = this.batchRowsPage.filter(it => it[this.primaryKey] !== row[this.primaryKey])
        this.batchKeysPage = this.batchKeysPage.filter(it => it !== row[this.primaryKey])
        let tRow = this.tableData.filter(it => it[this.primaryKey] === 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.primaryKey] == 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/3/16 18:12
     */
    setMagnifierProperty() {
      let self = this
      // 成型线
      if (self.type === self.$config.MagnifierType.moldline) {
        self.service = this.$service.moldingService
        self.methodsName = this.$service.moldingService.searchMoldline
        self.searchContent = [
          {
            itemCode: 'moldingDate',
            valueFormat: {code: 'lastMoldingDate', default: new Date().toDateStr()},
            valueKind: 'DATE',
            clearable:false
          },
          {
            itemCode: 'moldlineCode',
            valueFormat: {code: 'uniqueCode'},
          },
          {
            itemCode: 'moldlineName',
          },
          {
            itemCode: 'moldingUserName',
          },
        ]
        self.primaryKey = 'groupId'
        self.columns = [
          // {field: 'uniqueCode', title: vm.$t('moldlineCode')},
          // {field: 'moldlineName'},
          {field: 'moldlineCodeName'},
          {field: 'groupNo', type: "number"},
          {field: 'flgCanBatches', type: "switch", switchDisabled: true},
          {field: 'moldlineItemQty', type: "number"},
          {field: 'userBindKind'},
          {field: 'lastMoldingDate', type: "date"},
          {field: 'lastMoldingBatch',title: vm.$t('moldingBatch')},
          {field: 'remarks', width: 'auto'}
        ]
      }
    },
    /**
     * @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
        }

        // 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[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)
      }
    },
    /**
     * @author : 沈博
     * @date   : 2022/2/28 16:57
     * @desc   : 点击取消
     */
    onCancel() {
      this.visible = false
      this.cancelFunc()
      this.displayFlag = false;
    },
    /**
     * @author : 沈博
     * @date   : 2022/2/28 16:57
     * @desc   : 点击确定
     */
    onOk() {
      this.visible = false
      this.okFunc()
    }
  },
  watch: {
    visible(n, o) {
      if (!n) {
        //回复快捷键
        document.onkeydown = this.documentKeyDownContent;
      }
    }
  },
  mounted() {
    // this.getDataTable();  // 查询数据
  },
  created() {
    this.vm = window.vm;
    this.setMagnifierProperty() // 根据类型给属性赋值
    this.$nextTick(() => {
      this.addKeyBoardEvent()   // 增加快捷键
    })
  }
}
</script>
<style scoped>


.close-div {
  color: #fff;
}

.close-icon {
  font-size: 20px;
  margin-top: -1px;
}

.content-div {
  height: 180px;
  align-items: center;
  justify-content: center;
  display: flex;
}

.content-icon {
  font-size: 28px;
  margin-right: 10px;
}
</style>
