<!-- @desc:定位信息框  @auth:周兴  @time:2022/11/30 13:17 -->
<template>
  <DkModal :left="location.left?location.left-170 + 'px':null" :top="location.top?location.top + 'px':null"
           :position="location.left?'absolute':'relative'" :footerFlag="false" ref="modal_message" v-model="visible"
           width="450" :title="title" :mask="true">
    <card ref="tableCard">
      <!--  选择tab区域  -->
      <div v-if="exchangeFlag&&!colPosition">
        <DkTabs size="small" v-model="tabValue" :options="tabsOptions" @on-click="changeTabs"></DkTabs>
      </div>
      <div class="content-div">
        <div style="width: 80px">{{ vm.$t('findContent') }}</div>
        <InputPop ref="searchInput" v-model="searchText" :upperFlag="false" :placeholder="vm.$t('searchText')"
                  @on-keydown.enter="searchAll"/>
      </div>
      <div class="exchange-div" v-if="tabValue=='exchange'">
        <div style="width: 80px">{{ vm.$t('exchangeAs') }}</div>
        <InputPop ref="exchangeInput" v-model="exchangeText" :upperFlag="false" :placeholder="vm.$t('searchText')"/>
      </div>
      <!--单元格匹配（是否模糊查询）-->
      <div class="tool-div">
        <Checkbox v-model="equalFlag">{{ vm.$t('equalCell') }}</Checkbox>
      </div>
    </card>
    <!--查找替换-->
    <div class="btn-class" v-if="!colPosition">
      <Button v-if="tabValue=='exchange'" @click="exchangeAll" style="margin-left: 5px;" size="small" ref="exchangeAll">{{
          vm.$t('exchangeAll')
        }}
      </Button>
      <Button v-if="tabValue=='exchange'" @click="exchange" style="margin-left: 5px;" size="small" ref="exchange">{{
          vm.$t('exchange')
        }}
      </Button>
      <Button @click="searchAll" style="margin-left: 5px;" type="primary" size="small" ref="searchAll">{{
          vm.$t('searchAll')
        }}
      </Button>
      <Button @click="previous" style="margin-left: 5px;" size="small" ref="previous">{{ vm.$t('previousNo') }}</Button>
      <Button @click="next" style="margin-left: 5px;" size="small" ref="next">{{ vm.$t('nextNo') }}</Button>
      <Button @click="close" style="margin-left: 5px;" size="small" ref="close">{{ vm.$t('close') }}</Button>
    </div>
    <!--列定位-->
    <div class="btn-class" v-else>
      <Button @click="ok" style="margin-left: 5px;" size="small" ref="confirm">{{ vm.$t('confirm') }}</Button>
      <Button @click="close" style="margin-left: 5px;" size="small" ref="close">{{ vm.$t('close') }}</Button>
    </div>
    <div style="padding-top: 5px;padding-left: 10px" v-if="tableData && tableData.length > 0">
      <DkTable ref="table-select" :data="tableData"
               :pageFlag="false"
               :choose-flag="false"
               :show-setting-flag="false"
               :select-flag="false"
               :height="tableHeight"
               @current-change="currentChange"
      >
        <DkTableColumn field="label" :title="vm.$t('col')" width="120"></DkTableColumn>
        <DkTableColumn field="rowIndex" :title="vm.$t('rowNo')" width="80"></DkTableColumn>
        <DkTableColumn field="value" width="auto"></DkTableColumn>
      </DkTable>
    </div>
  </DkModal>
</template>

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

export default {
  name: "MyPosition",
  data() {
    const vm = window.vm;
    return {
      documentKeyDownContent: Object,
      vm: vm,
      location: {left: null, top: null},
      title: '系统提示',//标题
      visible: false,//显示控制
      okFunc: () => {
      },//确定回调
      changeFunc: () => {
      },// 行切换回调
      exchangeAllFunc: () => {
      },// 替换全部回调
      exchangeFunc: () => {
      },// 替换回调
      okText: vm.$t('confirm'),
      searchText: '', // 查询内容
      exchangeText:'',// 替换内容
      options: [],   // 源数据
      tableData: [],
      tableHeight: 200,
      component: null,
      fields: [],
      colPosition: false, // 是否是列定位
      exchangeFlag: true,// 是否显示替换
      tabValue: 'search',
      equalFlag:false,// 是否单元格匹配
      //tabs
      tabsOptions: [
        {label: vm.$t('rowPosition'), name: 'search'},
        {label: vm.$t('exchange'), name: 'exchange'},
      ],
    }
  },
  methods: {
    /**
     * @desc   : 切换tabs
     * @author : 周兴
     * @date   : 2023/2/15 13:54
     */
    changeTabs(e) {
      // console.log('eee', e)
    },
    /**
     * @desc   : 行改变事件
     * @author : 周兴
     * @date   : 2023/2/15 9:07
     */
    currentChange({row}) {
      this.changeFunc({field: row.field, rowIndex: row.rowIndex - 1, column: row.column})
    },
    /**
     * @desc   : 全部替换
     * @author : 周兴
     * @date   : 2023/2/15 14:20
     */
    exchangeAll(){
      this.exchangeAllFunc(this.searchText ? this.searchText.trim() : null,this.exchangeText.trim(),this.fields,this.equalFlag)
    },
    /**
     * @desc   : 替换
     * @author : 周兴
     * @date   : 2023/2/15 15:34
     */
    exchange(){
      this.exchangeFunc(this.searchText ? this.searchText.trim() : null,this.exchangeText.trim(),this.fields,this.equalFlag)
    },
    /**
     * @desc   : 查询全部
     * @author : 周兴
     * @date   : 2023/2/14 17:27
     */
    searchAll() {
      if (this.fields && this.fields.length > 0 && this.component.tableData
        && this.component.tableData.length && this.searchText) {
        let tableData = []
        let table = this.component.tableData
        let searchText = this.searchText;
        for (let i = 0; i < table.length; i++) {
          // 模糊查询
          this.fields.forEach(it => {
            // 模糊
            if(!this.equalFlag){
              if ((table[i][it.field] + '').indexOf(searchText) >= 0) {
                let item = {
                  label:it.title,
                  field: it.field,
                  rowIndex: i + 1,
                  value: table[i][it.field],
                  column: it
                }
                tableData.push(item);
              }
            }else{
              // 值等
              if ((table[i][it.field] + '') == searchText) {
                let item = {
                  label:it.title,
                  field: it.field,
                  rowIndex: i + 1,
                  value: table[i][it.field],
                  column: it
                }
                tableData.push(item);
              }
            }
          })
        }
        // 提示没有数据
        if (tableData.length === 0) {
          this.$Message.warning("未查询到数据");
        }
        this.tableData = tableData
      }
      // this.visible = false
      // this.okFunc(this.searchText ? this.searchText.trim() : null)
    },
    /**
     * @desc   : 切换到上一个
     * @author : 周兴
     * @date   : 2023/2/14 17:27
     */
    previous() {
      if (!this.tableData || this.tableData.length == 0) {
        // 下方列表没有数据
        this.changeFunc({noSelectAll:true,type:'previous',fields:this.fields,equalFlag:this.equalFlag,searchText:this.searchText})
      }else{
        // 获取当前行
        let currentIndex = this.$refs['table-select'].getCurrentRowIndex();
        if (!currentIndex && currentIndex != 0) {
          currentIndex = -1;
        }
        if (currentIndex > 0) {
          this.$refs['table-select'].clearCurrentRow()
          this.$nextTick(() => {
            this.$refs['table-select'].setCurrentRow(this.tableData[currentIndex - 1])
            this.$refs['table-select'].scrollToRow(this.tableData[currentIndex - 1]);
          });
        }
      }
    },
    /**
     * @desc   : 切换到下一个
     * @author : 周兴
     * @date   : 2023/2/14 17:27
     */
    next() {
      if (!this.tableData || this.tableData.length == 0) {
        // 下方列表没有数据
        this.changeFunc({noSelectAll:true,type:'next',fields:this.fields,equalFlag:this.equalFlag,searchText:this.searchText})
      }else{
        // 获取当前行
        let currentIndex = this.$refs['table-select'].getCurrentRowIndex();
        if (!currentIndex && currentIndex != 0) {
          currentIndex = -1;
        }
        if (currentIndex < this.tableData.length - 1) {
          this.$refs['table-select'].clearCurrentRow()
          this.$nextTick(() => {
            this.$refs['table-select'].setCurrentRow(this.tableData[currentIndex + 1])
            this.$refs['table-select'].scrollToRow(this.tableData[currentIndex + 1]);
          });
        }
      }
    },
    /**
     * @desc   : 列定位数据
     * @author : 周兴
     * @date   : 2023/2/15 14:12
     */
    ok() {
      this.okFunc(this.searchText ? this.searchText.trim() : null)
    },
    /**
     * @desc   : 关闭查询页面
     * @author : 周兴
     * @date   : 2023/2/14 17:29
     */
    close() {
      this.visible = false;
    },
    /**
     * @desc   : 获取组件的列
     * @author : 周兴
     * @date   : 2023/2/15 13:18
     */
    getComponentColumns() {
      let fields = []
      // 获取显示的列
      let tableColumns = this.component.getTableColumn()
      if (tableColumns && tableColumns.visibleColumn && tableColumns.visibleColumn.length > 0) {
        tableColumns.visibleColumn.forEach(it => {
          // 按时不支持数值
          if(!it.type || (it.type && it.type !=='select' && it.type !== 'tableSelect'  && it.type !== 'checkbox'
            && it.type !== 'radio' && it.type !== 'number')){
            fields.pushNoRepeat(it);
          }
        })
      }
      this.fields = fields;
    },
    /**
     * @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)
      }
    },
  },
  watch: {
    visible(n, o) {
      if (!n) {
        //回复快捷键
        document.onkeydown = this.documentKeyDownContent;
      }
    }
  },
  mounted() {
    setTimeout(() => {
      //光标搜索框上
      this.$refs.searchInput.focus()
    }, 100)
  },
  created() {
    this.$nextTick(() => {
      this.addKeyBoardEvent()   // 增加快捷键
    })
    this.getComponentColumns(); // 获取组件的所有显示列
  }
}
</script>
<style scoped>

/deep/ .ivu-modal-body {
  padding: 0;
}

.close-div {
  color: #fff;
}

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

.content-div {
  padding: 10px 20px 5px 20px;
  align-items: center;
  justify-content: center;
  display: flex;
}

.exchange-div {
  padding-left:  20px;
  padding-right:  20px;
  align-items: center;
  justify-content: center;
  display: flex;
}

.tool-div{
  padding-top:10px;
  padding-left:  20px;
  align-items: center;
  display: flex;
}

.content-icon {
  font-size: 28px;
  margin-right: 10px;
}

.btn-class {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
}

/deep/ .ivu-card-body {
  padding: 5px !important;
  margin: 2px !important;
}
</style>
