<template>
  <div class="selectBox" @click.stop="preventBubblingUp">
    <el-button v-if="batchAddition" size="small" @click.stop="handleOpenBatchAddition">{{
      batchAdditionBtnText
    }}</el-button>
    <span v-else-if="multiple">{{ selected }}</span>
    <el-input readonly size="small" v-else v-model="selected" :title="selected">
      <div class="search-button" slot="append">
        <div class="inner-container" @click.stop="openFieldDialog">
          <div class="inner-content">
            <i class="el-icon-search"></i>
          </div>
        </div>
      </div>
    </el-input>

    <a-modal
      width="80%"
      :cancel-text="cancelText"
      :ok-text="btnText"
      :title="title"
      :visible.sync="visible"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <slot name="searchSlot"> </slot>
      <VxeRender
        checkKey="uuid"
        ref="crud"
        showType="page"
        v-model="crudObj"
        :data="crudOption.data"
        :loadingState.sync="loading"
        :option.sync="crudOption.option"
        :page.sync="crudOption.page"
        :selection="multiple"
        :selectionData="selectionData"
        :searchFormShow="searchFormShow"
        @current-change="handlerCurrentChange"
        @handle-reset="handleSearchReset"
        @handle-search="handleSearch"
        @page-change="handlePgeChange"
        @row-dblclick="handleOk"
        @selection-change="selectionChange"
      >
        <!-- <template slot="leftMenu">
          <el-button type="primary" size="small" plain @click="handleOk()">
            {{ btnText }}
          </el-button>
        </template> -->
        <template slot="rightTools">
          <i v-if="searchShow" class="vxe-icon--search" @click="handleSearchShow"></i>
        </template>
      </VxeRender>
    </a-modal>
  </div>
</template>
<script>
import { DEFAULT_PAGER_COUNT } from '../../../lib/const';
import { PurchaseDeliveryNoteService } from '../../../lib/api/materials';
import { getUserInfo } from '../../../lib/auth';
import { bringMessageBeforeDialog, ft } from '../../../lib/utils';
import VxeRender from './../widget/pop-vxe';
import dialogOption from './const/order';

const LABELS = {
  batchAdding: ft('i18n_common_batch_adding', '批量添加'),
  close: ft('i18n_common_close', '关闭'),
  data: ft('i18n_common_data', '数据'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  order: ft('i18n_common_order', '订单'),
  save: ft('i18n_common_save', '保存'),
  select: ft('i18n_common_select', '选择')
};

export default {
  name: 'SelectOrder',
  components: { VxeRender },
  props: {
    searchShow: { type: Boolean, default: true }, // 是否需要搜索
    btnText: { type: String, default: LABELS.save }, // 保存按钮文字
    cancelText: { type: String, default: LABELS.close }, // 关闭对话框按钮文字
    title: { type: String, default: '' }, // dialog标题
    actionPath: { type: String, default: 'findPageList' }, // 数据接口地址
    selected: { type: String, default: '' },
    addBtnText: { type: String, default: `${LABELS.select}${LABELS.order}` },
    dialogVisible: { type: Boolean, default: false }, // dialog显隐
    isDisabled: { type: Boolean, default: false }, // 是否禁用
    multiple: { type: Boolean, default: false }, // 是否多选

    batchAddition: { type: Boolean, default: false }, // 批量添加
    batchAdditionBtnText: {
      type: String,
      default: LABELS.batchAdding
    },

    api: {
      type: Function,
      default: PurchaseDeliveryNoteService.list
    },
    option: {
      type: Object,
      default: () => {
        return {};
      }
    },
    listParams: {
      type: Object,
      default: () => {
        return {};
      }
    },

    // 表格的分页配置
    page: {
      type: Object,
      default: () => {
        return { total: 0, currentPage: 1, pageSize: 10, pagerCount: DEFAULT_PAGER_COUNT };
      }
    }
  },
  data() {
    return {
      labels: LABELS,
      searchFormShow: false,
      visible: this.dialogVisible,
      selectColumns: [],
      searchCondition: {},
      crudObj: {},
      currentData: null,
      selectionData: [],
      crudOption: dialogOption,
      showSearch: false,
      loading: false
    };
  },
  watch: {
    page: function (newValue) {
      this.crudOption.page = newValue;
    },
    column: function (newValue) {
      this.crudOption.column = newValue;
    },
    visible: function (newValue) {
      if (newValue === true) {
        this.beforeOpen(this);
        this.handleList();
      }
      this.$emit('update:dialogVisible', newValue);
    },
    dialogVisible: function (newValue) {
      this.visible = newValue;
    }
  },
  created() {
    this.crudOption.page = this.page;
    this.crudOption.selection = this.multiple;
    this.crudOption.highlightCurrentRow = !this.multiple;

    // 如果外部传入弹窗展示字段
    if (this.option.column) {
      this.updateColumn(this.option.column);
    }

    if (typeof this.option?.beforeOk === 'function') {
      this.beforeOk = this.option?.beforeOk || this._beforeOk;
    }

    if (typeof this.option?.beforeOpen === 'function') {
      this.beforeOpen = this.option?.beforeOpen || this._beforeOpen;
    }

    this.showSearch = true;
  },
  methods: {
    _beforeOk() {
      return null;
    },

    _beforeOpen() {
      return null;
    },

    beforeOk() {},

    beforeOpen() {},

    checkSelectedItem() {
      const selectedItems = this.selectColumns;

      if (selectedItems.length > 0) {
        try {
          const items = [...selectedItems];
          this.beforeOk(items);
          this.ok(items);
        } catch (err) {
          console.log(err);
        }
      } else {
        bringMessageBeforeDialog(this.dialogElementId);

        this.$message.warning(`${LABELS.pleaseSelect}${LABELS.data}`);
      }
    },

    clearSelection() {
      this.selectionData = [];
      const curd = this.$refs.crud;
      curd && curd.clearSelection && curd.clearSelection();
    },

    handleCancel() {
      this.crudOption.data = [];
      this.visible = false;
      this.$emit('cancelBatchSelected');
    },

    handlerCurrentChange(data) {
      this.currentData = data;
    },

    handleList() {
      const userInfo = getUserInfo();

      const reqData = {
        ...this.listParams,
        ...this.searchCondition,
        elsAccount: this.listParams.elsAccount || userInfo.elsAccount,
        toElsAccount: this.listParams.toElsAccount || userInfo.elsAccount,
        currentPage: this.crudOption.page.currentPage,
        pageSize: this.crudOption.page.pageSize
      };

      this.loading = true;

      this.api(reqData)
        .then((res) => {
          if (res.data && res.data.code === '200' && res.data.data) {
            const pageData = res.data.data;

            this.crudOption.data = pageData.rows;
            this.crudOption.page.total = pageData.total;
          } else {
            console.log('Failed to list orders, ', res.data || res);
            this.$message.error(
              res.data.message || LABELS.failedToQueryData.replace('?', LABELS.order.toLowerCase())
            );
          }
        })
        .catch((err) => {
          console.log('Error to list orders, ', err);
          this.$message.error(LABELS.failedToQueryData.replace('?', LABELS.order.toLowerCase()));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleOk() {
      this.checkSelectedItem();
    },

    handleOpenBatchAddition() {
      this.$emit('onOpenBatchAddition');
    },

    handlePgeChange(page) {
      this.$emit('update:page', page);
      this.handleList();
    },

    handleSearch(searchFormObj) {
      this.searchCondition = searchFormObj;
      this.crudOption.page.currentPage = 1;
      this.handleList();
    },

    handleSearchReset() {
      this.searchCondition = {};
      this.crudOption.page.currentPage = 1;
      this.handleList();
    },

    handleSearchShow() {
      this.searchFormShow = !this.searchFormShow;
    },

    ok(selectedItems) {
      this.$emit('selectDone', selectedItems);
      this.visible = false;
      this.selectColumns = [];
    },

    openFieldDialog() {
      this.visible = true;
    },

    preventBubblingUp() {
      // Prevent events from bubbling up
    },

    selectionChange(list) {
      this.selectColumns = list;
    },

    updateColumn(column) {
      if (column && column.length) {
        this.crudOption.option.column = column;
      }
    }
  }
};
</script>
<style>
.selectBox .el-table--striped .el-table__body tr.el-table__row--striped.current-row td {
  background-color: lightslategray !important;
  color: #fff;
}
</style>
<style lang="scss" scoped>
.inner-container {
  position: relative;
  width: 100%;
  padding-top: 100%;
}

.inner-content {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
