<template>
  <div @click.stop="preventBubblingUp">
    <span v-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>

    <el-dialog
      append-to-body
      width="80%"
      :id="dialogElementId"
      :title="title"
      :visible.sync="visible"
      @close="handleClose"
      @open="handleList"
    >
      <slot name="searchSlot"> </slot>
      <VxeRender
        checkKey="uuid"
        ref="crud"
        showType="page"
        v-model="crudObj"
        :data="crudData"
        :loadingState.sync="loading"
        :option.sync="crudOption"
        :page.sync="crudPage"
        :selection="multiple"
        :selectionData="selectionData"
        @page-change="currentChange"
        @row-dblclick="handleOk"
        @selection-change="selectionChange"
      >
        <template slot="leftMenu">
          <el-button type="primary" size="small" plain @click="handleOk()">
            {{ btnText }}
          </el-button>
        </template>
      </VxeRender>
    </el-dialog>
  </div>
</template>
<script>
import { DEFAULT_PAGER_COUNT } from '../../../lib/const';
import { bringMessageBeforeDialog, ft } from '../../../lib/utils.js';
import { SaleDeliveryNoteService } from '../../../lib/api/materials';
import { getUserInfo } from '../../../lib/auth';
import deliveryDialogOption from './const/deliveryList';
import VxeRender from './../widget/pop-vxe';

const LABELS = {
  costCenter: ft('i18n_common_cost_center', '成本中心'),
  data: ft('i18n_common_data', '数据'),
  deliveryNotice: ft('i18n_common_delivery_notice', '送货通知单'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  save: ft('i18n_common_save', '保存'),
  select: ft('i18n_common_select', '选择'),
  serialNumber: ft('i18n_common_serial_number', '序号')
};

export default {
  name: 'SelectDelivery',
  components: { VxeRender },
  props: {
    btnText: { type: String, default: LABELS.save }, // 保存按钮文字
    title: { type: String, default: '' }, // dialog标题
    actionPath: { type: String, default: 'findPageList' }, // 数据接口地址
    selected: { type: String, default: '' },
    addBtnText: { type: String, default: `${LABELS.select}${LABELS.deliveryNotice}` },

    dialogVisible: { type: Boolean, default: false }, // dialog显隐
    isDisabled: { type: Boolean, default: false }, // 是否禁用
    multiple: { type: Boolean, default: false }, // 是否多选

    // 表格的列配置
    column: {
      type: Array,
      default: () => {
        return deliveryDialogOption.option.column;
      }
    },

    listParams: {
      type: Object,
      default: () => {
        return {};
      }
    },

    // 表格的分页配置
    page: {
      type: Object,
      default: () => {
        return { total: 0, currentPage: 1, pageSize: 10, pagerCount: DEFAULT_PAGER_COUNT };
      }
    }
  },
  data() {
    return {
      dialogElementId: 'deliveryManageDialog',
      visible: this.dialogVisible,
      selectColumns: [],
      currentRow: null,
      selectionData: [],

      crudObj: {},
      crudData: [],
      crudOption: {
        indexLabel: LABELS.serialNumber,
        indexFixed: false,
        header: true,
        searchShow: false,
        searchBtn: true,
        refreshBtn: false,
        columnBtn: false,
        align: 'left',
        menu: false,
        border: true,
        highlightCurrentRow: true,
        selection: true,
        stripe: true,
        page: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        sortable: true,
        tip: false,
        indeterminate: true,
        labelPosition: 'top',
        searchSpan: 12,
        searchMenuSpan: 12,
        column: []
      },
      crudPageParam: {
        currentPage: 1,
        pageSize: 10
      },
      crudMultiple: true,
      searchCondition: {},
      loading: false
    };
  },

  watch: {
    page: function (newValue) {
      this.crudPage = newValue;
    },
    column: function (newValue) {
      this.crudOption.column = newValue;
    },
    visible: function (newValue) {
      this.$emit('update:dialogVisible', newValue);
    },
    dialogVisible: function (newValue) {
      this.visible = newValue;
    }
  },
  created() {
    this.crudOption.column = this.column;
    this.crudMultiple = this.multiple;
    this.crudOption.selection = this.multiple;
    this.crudOption.highlightCurrentRow = !this.multiple;
    this.handleList();
  },
  methods: {
    handleClose() {
      this.crudData = [];
    },

    handleList() {
      this.clearSelected();

      const listParams = this.listParams;

      Object.assign(listParams, this.searchCondition);

      listParams.elsAccount = listParams.elsAccount || getUserInfo().elsAccount;
      listParams.currentPage = this.page.currentPage;
      listParams.pageSize = this.page.pageSize;

      this.loading = true;

      SaleDeliveryNoteService.list(listParams)
        .then((res) => {
          if (res.data && res.data.code === '200' && res.data.data) {
            const pageData = res.data.data;

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

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

    selectionChange(list) {
      this.selectColumns = list;
    },
    searchReset() {
      this.crudPageParam.currentPage = 1;
      for (const key in this.searchCondition) {
        this.searchCondition[key] = '';
      }
      this.handleList();
    },

    searchChange(params, done) {
      this.crudPageParam.currentPage = 1;
      this.searchCondition = Object.assign(params);

      this.handleList();

      done();
    },

    refreshChange() {
      this.crudPageParam.currentPage = 1;
      this.handleList();
    },

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

    checkSelectedItem() {
      const selectedItem = this.selectColumns.length;

      if (selectedItem) {
        this.ok();
      } else {
        bringMessageBeforeDialog(this.dialogElementId);
        this.$message.warning('请选择数据!');
      }
    },

    clearSelected() {
      this.currentRow = null;
      this.selectColumns = [];

      const crud = this.$refs.crud;

      if (crud) {
        if (typeof crud.selectClear === 'function') {
          try {
            crud.selectClear();
          } catch (err) {
            console.log('selectClear error', err);
          }
        }

        if (typeof crud.setCurrentRow === 'function') {
          try {
            crud.setCurrentRow();
          } catch (err) {
            console.log('setCurrentRow error', err);
          }
        }
      }
    },

    ok() {
      const selectItems = this.crudMultiple ? this.selectColumns : [this.currentRow];

      this.$emit('selectDone', selectItems);

      this.clearSelected();

      this.visible = false;
    },

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

    preventBubblingUp() {
      // Prevent events from bubbling up
    }
  }
};
</script>
<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>
