<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"
          @keyup="keyupEvent" :placeholder="placeholder" @click="clickEvent" @suffix-click="suffixClick"
          @search-click="popupEvent"></vxe-input>


      </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" @cell-dblclick="dblClickEvent" @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">
      <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'; // 接口地址

/*

  grid 中 选择数据的组件，支持分页
  默认将选择的数据以 [id,name] 的方式返回，
  params.dataType = 'object' 将会以 完整数据返回
  params.dataUrl 可以自定义数据请求URL
  
*/
export default {
  name: 'MkGridDataSelector',
  props: {
    params: Object
  },
  data() {
    return {
      actions: {
        getList: `${BASE_URL}/api/web/listdata`
      },
      modalVisible: false,
      listdataFieldName: 'list',
      keyFieldName: "id",
      lastKey: '',
      modelName: '',
      orderBy: '',
      textboxValue: '',
      placeholder: '',
      row: null,
      column: null,
      loading: false,
      tableData: [],
      enalbedPopup: false,
      popupPage: null,
      popupPageOptions: {},
      popupPageMode: '',
      actionParams: null,
      tableColumn: [
        { field: 'name', title: '名称' },
        { field: 'code', title: '编码' }
      ],
      modalWidth: 800,
      modalHeight: 600,
      searchFieldNames: ['name'],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 100
      }
    }
  },
  created() {
    this.load()
    this.heightInit();
  },
  methods: {
    heightInit() {
      this.$nextTick(() => {

        this.modalHeight = this.$mk.getWindowSize().height * 0.9;
        this.modalWidth = this.$mk.getWindowSize().width * 0.9;
      });
    },
    load() {
      const { row, column } = this.params

      this.row = row
      this.column = column

      if (column && column.params) {


        this.modelName = column.params.modelName;
        this.orderBy = column.params.orderBy;
        this.placeholder = column.params.placeholder;
        if (column.params.searchFieldNames) {
          this.searchFieldNames = column.params.searchFieldNames;
        }
        if (column.params.columns) {
          this.tableColumn = column.params.columns;
        }
        if (column.params.popup) {
          this.enalbedPopup = true;
          this.popupPage = column.params.popup.page;
        }
        if (column.params.dataUrl) {
          this.actions.getList = column.params.dataUrl;
        }


        if (column.params.listdataFieldName) {
          this.listdataFieldName = column.params.listdataFieldName;
        }

        if (column.params.actionParams) {
          this.actionParams = column.params.actionParams;
        }
      }

      if (column && column.params && column.params.dataType == "object") {
        if (this.row[column.field]) {
          this.textboxValue = this.row[column.field][column.params.textField];
        }

      }
      else if (column && column.params && column.params.dataType == "string") {
        if (this.row[column.field]) {
          this.textboxValue = this.row[column.field];
        }

      }

      else if (column.params && column.params.dataType == 'mapper') {
        this.textboxValue = this.row[column.params.showField || column.field];
      }
      else if (this.row[column.field] && this.row[column.field][1]) {
        this.textboxValue = this.row[column.field][1];

      }

      this.getData().then(data => {

        this.tablePage.total = data.total;
        this.tableData = data[this.listdataFieldName];

        if(column.params.extendData){
          this.tableData = [...column.params.extendData,...this.tableData];
        }
      });
    },
    getData(key) {


      this.lastKey = key;


      var params = Object.assign({}, this.actionParams || {}) // 定义请求参数
      params.page = this.tablePage.currentPage; // 当前页码
      params.limit = this.tablePage.pageSize; // 每页条数
      params.order_bys = []; // 排序信息
      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,
        data: params
      });
    },
    clickEvent() {
      this.$refs.xDown.showPanel()
    },
    keyupEvent(e) {
      const { row, column } = this
      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;
      this.loading = true

      if (!cellValue) {
        row[column.field] = null;
      }

      this.getData(cellValue).then(data => {

        this.loading = false
        this.tablePage.total = data.total;
        this.tableData = data[this.listdataFieldName] || [];
      }).catch(() => {
        this.loading = false;
      });
    },
    suffixClick() {
      this.$refs.xDown.togglePanel()
    },
    pageChangeEvent({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.loading = true

      this.getData(this.lastKey).then(data => {

        this.loading = false
        this.tablePage.total = data.total;
        this.tableData = data[this.listdataFieldName];
      }).catch(() => {
        this.loading = false;
      });
    },
    getIdValue({ row }) {
      let id = row[this.keyFieldName];
      if (!id) id = '';
      if (id.toString) id = id.toString();
      return id;
    },
    selectEvent(params) {
      const { row, column } = this

      let id = this.getIdValue({ row: params.row });


      let textField = column.params.textField;
      this.textboxValue = params.row[textField];
      if (column.params && column.params.dataType == 'object') {
        row[column.field] = Object.assign({}, params.row)
      }
      else if (column.params && column.params.dataType == 'string') {
        row[column.field] = params.row[textField]
      }
      else if (column.params && column.params.dataType == 'mapper') {
        console.log(params.row) 

      }
      else {
        row[column.field] = [id, params.row[textField]];
      }

      
      if (column.params.mapper) {
        column.params.mapper.forEach(item => {

          row[item.field] = params.row[item.fromField];
        })
      }


      this.params.$table.$emit("pulldownSelected", { row, selectedData: params.row, column, name: column.params.name, params: this.params });
      this.$refs.xDown.hidePanel()
    },
    dblClickEvent(params) {
      const { row, column } = this

      let id = this.getIdValue({ row: params.row });

      let textField = column.params.textField;
      this.textboxValue = params.row[textField];

      if (column.params && column.params.dataType == 'object') {
        row[column.field] = Object.assign({}, params.row)


      }
      else if (column.params && column.params.dataType == 'string') {
        row[column.field] = params.row[textField]
      }

      else if (column.params && column.params.dataType == 'mapper') {
        console.log(column);
      }
      else {
        row[column.field] = [id, params.row[textField]];
      }
      if (column.params.mapper) {
        column.params.mapper.forEach(item => {

          row[item.field] = params.row[item.fromField];
        })
      }

      console.log(id)
      this.modalVisible = false;
      let rows = this.$refs.popup.getConfirmData();
      this.params.$table.$emit("popupSelected", { rows, name: column.params.name, params: this.params });
    },
    popupEvent() {
      this.modalVisible = true;
    },
    confirmEvent() {
      const { row, column } = this
      let selectedRow = this.$refs.popup.getSelectdRow();
      let id = this.getIdValue({ row: selectedRow });
      let textField = column.params.textField;
      this.textboxValue = selectedRow[textField];


      if (column.params && column.params.dataType == 'object') {
        row[column.field] = Object.assign({}, selectedRow)
      }
      else if (column.params && column.params.dataType == 'string') {
        row[column.field] = selectedRow[textField]
      }

      else if (column.params && column.params.dataType == 'mapper') {
        console.log(column)

      }
      else {
        row[column.field] = [id, selectedRow[textField]];
      }
      if (column.params.mapper) {
        column.params.mapper.forEach(item => {

          row[item.field] = selectedRow[item.fromField];
        })
      }


      this.modalVisible = false;

      let rows = this.$refs.popup.getConfirmData();
      this.params.$table.$emit("popupSelected", { rows, column: column, name: column.params.name, params: this.params });
    }
  }
}
</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>