<template>
  <div class="edit-down-table">
    <vxe-pulldown class="edit-down-pulldown" ref="xDown" transfer>
      <template>
        <vxe-input class="edit-down-input" ref="inputx" :type="enalbedPopup ? 'search' : 'input'" v-model="textboxValue"
          :readonly="readonly" @keyup="keyupEvent" @keydown="keydownEvent" :placeholder="placeholder" @click="clickEvent"
          @suffix-click="suffixClick" @focus="onFocus" @search-click="popupEvent"></vxe-input>

        <div style="margin-top: 10px;" v-if="buttons && buttons.length">
          <a-icon v-for="(btn, index) in buttons" :key="index" @click="buttonClick(btn)" :type="btn.type"
            :style="{ fontSize: '26px', color: '#08c' }"></a-icon>
        </div>

      </template>
      <template #dropdown>

        <vxe-grid :keyboard-config="{ isArrow: true }" auto-resize height="400" ref="xgrid"
          :row-config="{ isCurrent: true, isHover: true }" :loading="loading" :pager-config="tablePage" :data="tableData"
          :columns="tableColumn" :treeConfig="treeConfig" @cell-click="selectEvent" @page-change="pageChangeEvent">
        </vxe-grid>

      </template>
    </vxe-pulldown>

    <vxe-modal show-footer class-name="vxe-table--ignore-clear edit-popup-box" title="选择数据" :width="modalWidth"
      :height="modalHeight" v-model="modalVisible" @confirm="confirmEvent">
      <!-- vxe-modal 有以下属性
  show-footer 显示底部按钮
  width 宽度
  height 高度
  v-model 显示隐藏
  @confirm 确认按钮事件
  -->

      <template #default>
        <component :is="popupPage" ref="popup" :pageOptions="popupPageOptions" :pageMode="popupPageMode"></component>
      </template>
    </vxe-modal>
  </div>
</template>

<script>



import BASE_URL from '@/services/base/api.js'; // 加载api地址
export default {
  name: 'MkFormDataSelector', // 组件名称
  props: { // 组件属性
    readonly: Boolean,
    params: Object,
    value: [Array, String, Object]
  },
  data() {
    return {
      actions: { // api地址
        getList: `${BASE_URL}/api/web/listdata` // 获取列表数据
      },
      actionParams: null,
      buttons: [],
      modalVisible: false, // 弹出框显示
      lastKey: '', // 上次输入的值
      modelName: '',  // 模块名称
      orderBy: '',  // 排序
      textboxValue: '', // 输入框值
      placeholder: '', // 提示
      row: null, // 行
      column: null, // 列
      loading: false, // 加载中
      tableData: [], // 表格数据
      enalbedPopup: false, // 是否启用弹出框
      popupPage: null, // 弹出框页面
      popupPageOptions: {}, // 弹出框页面参数
      popupPageMode: '', // 弹出框页面模式

      tableColumn: [ // 表格列
        { field: 'name', title: '名称' },   // 字段名称，字段标题
        { field: 'code', title: '编码' }   // 字段名称，字段标题
      ],
      treeConfig: null,
      modalWidth: 800, // 弹出框宽度
      modalHeight: 600, // 弹出框高度
      searchFieldNames: ['name'], // 搜索字段
      tablePage: { // 表格分页
        total: 0, // 总数
        currentPage: 1, // 当前页
        pageSize: 100 // 每页显示条数
      }
    }
  },
  created() { // 创建
    this.load() // 加载
    this.heightInit(); // 高度初始化

    const { params } = this
    if (params.autoFocus) {
      this.$nextTick(() => {

        setTimeout(() => {
          this.$refs.inputx.focus();
        }, 100)

      });
    }
  },
  beforeDestroy() {
  },
  watch: {
    value() {
      const { params } = this
      if (params.dataType == "string") {
        this.textboxValue = this.value || "";
      }
      else if (params.dataType == "object") {
        if (this.value) {
          this.textboxValue = this.getShowValue({ obj: this.value, path: params.textField });
        }
      }
      else if (this.value && this.value[1]) {
        this.textboxValue = this.value[1];
      } else {
        this.textboxValue = "";
      }
    }
  },
  methods: {


    getShowValue({ obj, path }) {
      const parts = path.split('.');
      let value = obj;
      for (let i = 0; i < parts.length; i++) {
        const part = parts[i];
        if (!value[part]) return null;
        value = value[part];
      }
      return value;
    },

    heightInit() { // 高度初始化
      this.$nextTick(() => { // 下一次

        this.modalHeight = this.$mk.getWindowSize().height * 0.9; // 弹出框高度
        this.modalWidth = this.$mk.getWindowSize().width * 0.9; // 弹出框宽度
      });
    },


    load() { // 加载
      const { params } = this // 参数
      if (params) { // 如果参数存在
        this.modelName = params.modelName;  // 模块名称
        this.orderBy = params.orderBy; // 排序
        this.placeholder = params.placeholder; // 提示
        if (params.searchFieldNames) { // 如果搜索字段存在
          this.searchFieldNames = params.searchFieldNames; // 搜索字段
        }
        if (params.columns) { // 如果列存在
          this.tableColumn = params.columns;  // 表格列
        }
        if (params.treeConfig) {
          this.treeConfig = params.treeConfig;
        }

        if (params.popup) { // 如果弹出框存在
          this.enalbedPopup = true; // 是否启用弹出框
          this.popupPage = params.popup.page; // 弹出框页面

        }
        if (params.dataUrl) {
          this.actions.getList = params.dataUrl;
        }
        if (params.actionParams) {
          this.actionParams = params.actionParams;
        }
      }

      if (params.dataType == "string") {
        this.textboxValue = this.value || "";
      }
      else if (params.dataType == "object") {
        if (this.value) {
          this.textboxValue = this.getShowValue({ obj: this.value, path: params.textField });
        }
      }
      else if (params && params.dataType == 'mapper') {
        this.textboxValue = this.row[params.showField];
      }
      else if (this.value && this.value[1]) {
        this.textboxValue = this.value[1];
      } else {
        this.textboxValue = "";
      }



      let f = params.listdataFieldName || "Records";
      this.getData().then(data => {
        if ('Total' in data) {
          this.tablePage.total = data.Total;
        } else {
          this.tablePage.total = data.total;
        }

        this.tableData = data[f];
      });
    },

    getData(key) { // 获取数据 
      var params = Object.assign({}, this.params.actionParams || {}) // 定义请求参数


      params.page = this.tablePage.currentPage; // 当前页码
      params.limit = this.tablePage.pageSize; // 每页条数
      params.order_bys = params.order_bys || []; // 排序信息
      params.search_rules = params.search_rules || []; // 搜索信息 
      if (key) {
        key = this.$mk.trim(key);
      }
      if (key) {
        for (let i = 0; i < this.searchFieldNames.length; i++) {
          let field = this.searchFieldNames[i];
          params.search_rules.push({ // 添加搜索参数
            column: field, // 字段名
            mode: "like", // 搜索模式
            value: "%" + key + "%" // 值
          });
        }
      }

      return this.$mk.getPagedData({
        url: this.actions.getList,
        useBigInt: true,
        data: params
      });
    },
    clickEvent() { // 点击事件
      if (this.readonly) { // 如果只读
        return; // 返回
      }
      this.$refs.xDown.showPanel() // 显示面板
    },

    handleScanInput(event) {
      const { params } = this
      const input = event.target;
      const inputValue = input.value;
      this.scanEntry = input.value;

      if (event.key === 'Enter') {

        setTimeout(() => {

          input.value = '';

          this.scanEntry = '';

        }, 10);
        if (params.scan) {
          console.log(inputValue)
          params.scan({ value: inputValue, input: input })
        }


      }

    },
    keydownEvent(e) {

      const { params } = this
      if (params.scan) {
        this.handleScanInput(e.$event);
      }
    },
    keyupEvent(e) {
      const { params } = this
      if (this.readonly) {
        return;
      }
      let keyCode = e.$event.keyCode;
      if (keyCode == 38 || keyCode == 113 || keyCode == 115) {
        return;
      }
      if (keyCode == 40) {
        this.$refs.xDown.showPanel()
        const grid = this.$refs.xgrid;
        console.log(grid)
        if (!grid) return;
        grid.focus();

        let row = grid.getCurrentRecord();
        var ds = grid.getTableData();

        if (!row) {

          grid.setCurrentRow(ds.tableData[0]);
        }
        return false;
      }
      if (keyCode == 13) {
        const grid = this.$refs.xgrid;
        if (!grid) return;
        let row = grid.getCurrentRecord();
        this.selectEvent({
          row: row
        })
        return false;
      }
      const cellValue = this.textboxValue;
      if (!cellValue) {
        if (params.dataType == "string") {
          this.$emit('input', "");
          if (params.onDataChanged) {
            params.onDataChanged({ value: "" })
          }
        }
        else if (params.dataType == "object") {
          this.$emit('input', null);
          if (params.onDataChanged) {
            params.onDataChanged({ value: null })
          }
        }
        else {
          this.$emit('input', ["", ""]);
          if (params.onDataChanged) {
            params.onDataChanged({ value: ["", ""] })
          }
        }


      }
      this.loading = true // 加载
      let f = params.listdataFieldName || "Records";
      this.getData(cellValue).then(data => {
        this.loading = false
        if ('Total' in data) {
          this.tablePage.total = data.Total;
        } else {
          this.tablePage.total = data.total;
        }
        this.tableData = data[f];
      })
    },
    onFocus(){
      const { params } = this
      console.log(params)
      if (params.focusToLoad) {
        const cellValue = this.textboxValue;
        let f = params.listdataFieldName || "Records";
        this.loading = true
        this.getData(cellValue).then(data => {

          this.loading = false
          if ('Total' in data) {
            this.tablePage.total = data.Total;
          } else {
            this.tablePage.total = data.total;
          }
          this.tableData = data[f];
        })
      }

    },
    suffixClick() { // 后缀点击事件

      this.$refs.xDown.togglePanel();
    

    },
    pageChangeEvent({ currentPage, pageSize }) { // 分页改变事件
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.loading = true
      const { params } = this
      let f = params.listdataFieldName || "Records";
      this.getData(this.lastKey).then(data => {

        this.loading = false
        if ('Total' in data) {
          this.tablePage.total = data.Total;
        } else {
          this.tablePage.total = data.total;
        }
        this.tableData = data[f];
      })
    },
    selectEvent(e) { // 选择事件 
      const { params } = this
      let textField = params.textField;
      this.textboxValue = e.row[textField];
      if (params.dataType == "string") {
        this.$emit('input', e.row[textField]);
      }
      else if (params.dataType == "object") {
        this.$emit('input', e.row);
      }

      else if (params.dataType == 'mapper') {
        if (params.showField) {
          this.$emit('input', e.row[params.showField]);
        }
      }
      else {
        this.$emit('input', [e.row.ID, e.row[textField]]);
      }


      if (params.onDataChanged) {
        params.onDataChanged({ value: [e.row.ID, e.row[textField]], data: e.row })
      }
      this.$refs.xDown.hidePanel()
    },

    popupEvent() {
      console.log("popupEvent");
      this.modalVisible = true;
    },
    confirmEvent() {
      const { params } = this
      let selectedRow = this.$refs.popup.getSelectdRow();
      let textField = params.textField;
      this.textboxValue = selectedRow[textField];
      this.modalVisible = false;
      if (params.dataType == "string") {
        this.$emit('input', selectedRow[textField]);
      }
      else if (params.dataType == "object") {
        this.$emit('input', selectedRow);
      }
      else if (params.dataType == 'mapper') {
        if (params.showField) {
          this.$emit('input', selectedRow[params.showField]);
        }
      }
      else {
        this.$emit('input', [selectedRow.ID, selectedRow[textField]]);
      }


      if (params.onDataChanged) {
        params.onDataChanged({ value: [selectedRow.ID, selectedRow[textField]], data: selectedRow })
      }
    }
  }
}
</script>

<style>
.edit-down-pulldown {
  width: 100%;
}



.edit-down-wrapper {
  width: 600px;
  height: 300px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>