<template>
  <div class="selectBox" @click.stop="preventBubblingUp">
    <el-input readonly size="small" v-if="!multiple" 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-button v-else @click.stop="openFieldDialog">{{ addBtnText }}</el-button>

    <el-dialog
      append-to-body
      :id="dialogElementId"
      :visible.sync="visible"
      :title="title"
      @close="handleClose"
      @open="handleOpenDialog"
    >
      <avue-crud
        ref="crud"
        v-model="crudObj"
        :data.sync="crudData"
        :option.sync="crudOption"
        :page.sync="crudPage"
        @current-change="currentChange"
        @current-row-change="currentRowChange"
        @refresh-change="refreshChange"
        @search-change="searchChange"
        @selection-change="selectionChange"
        @size-change="sizeChange"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" plain @click.stop="handleOk()">{{
            btnText
          }}</el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </div>
</template>
<script>
import { DEFAULT_PAGER_COUNT, DIALOG_TABLE_MAX_HEIGHT } from '../../../lib/const';
import { bringMessageBeforeDialog, ft } from '../../../lib/utils.js';
import { SupplierMasterDataService } from '../../../lib/api/materials';
import { getUserInfo } from '../../../lib/auth';

import supplierDialogOption from './const/supplierList';

const LABELS = {
  atLeastOneData: ft('i18n_common_at_least_one_data', '至少一条数据'),
  data: ft('i18n_common_data', '数据'),
  batchSelection: ft('i18n_common_batch_selection', '批量选择'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  noData: ft('i18n_common_no_data', '暂无数据'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  ok: ft('i18n_common_ok', '确定'),
  save: ft('i18n_common_save', '保存'),
  select: ft('i18n_common_select', '选择'),
  selectAll: ft('i18n_common_select_all', '全选'),
  serialNumber: ft('i18n_common_serial_number', '序号'),
  supplier: ft('i18n_common_supplier', '供应商')
};

export default {
  name: 'SelectSupplier',
  props: {
    btnText: { type: String, default: LABELS.save }, // 保存按钮文字
    title: { type: String, default: '' }, // dialog标题
    selected: { type: String, default: '' },
    addBtnText: { type: String, default: `${LABELS.select}${LABELS.supplier}` },

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

    // 表格的列配置
    column: {
      type: Array,
      default: null
    },
    // 表格的分页配置
    page: {
      type: Object,
      default: () => {
        return { total: 0, currentPage: 1, pageSize: 10, pagerCount: DEFAULT_PAGER_COUNT };
      }
    },

    // 输入查询接口方法
    api: {
      type: Function,
      default: null
    },

    // 输入查询条件
    listParams: {
      type: Object,
      default: function () {
        return {};
      }
    },

    option: {
      type: Object,
      default: () => {
        return {
          column: null
        };
      }
    }
  },
  data() {
    return {
      dialogElementId: 'supplierDialog',
      visible: this.dialogVisible,
      selectColumns: [],
      currentRow: null,

      crudObj: {},
      crudData: [],
      crudOption: {
        indexLabel: LABELS.serialNumber,
        indexFixed: false,
        header: true,
        searchShow: false,
        searchBtn: true,
        columnBtn: false,
        refreshBtn: false,
        align: 'left',
        menu: false,
        border: true,
        highlightCurrentRow: true,
        selection: true,
        stripe: true,
        page: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        sortable: false,
        tip: false,
        indeterminate: true,
        labelPosition: 'top',
        searchSpan: 12,
        searchMenuSpan: 12,
        maxHeight: DIALOG_TABLE_MAX_HEIGHT,
        emptyText: LABELS.noData,
        column: []
      },
      crudPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      crudPageParam: {
        currentPage: 1,
        pageSize: 10
      },
      crudMultiple: true,
      searchCondition: {}
    };
  },

  watch: {
    column: function (newValue) {
      this.crudOption.column = newValue;
    },

    'option.column': function (newValue) {
      this.crudOption.column = newValue;
    },

    visible: function (newValue) {
      this.$emit('update:dialogVisible', newValue);
    },

    dialogVisible: function (newValue) {
      this.visible = newValue;
    },

    page: function (newValue) {
      this.crudPage = newValue;
    }
  },
  created() {
    this.crudPage = this.page;
    this.crudMultiple = this.multiple;
    this.crudOption.selection = this.multiple;
    this.crudOption.highlightCurrentRow = !this.multiple;
    this.isOk = false;

    this.updateColumn();
  },
  methods: {
    checkSelectedItem() {
      const selectedItem = this.crudMultiple ? this.selectColumns.length : this.currentRow;

      if (selectedItem) {
        this.ok();
      } else {
        bringMessageBeforeDialog(this.dialogElementId);

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

    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);
          }
        }
      }
    },

    currentChange(page) {
      this.crudPageParam.currentPage = page;
      this.handleList();
    },

    currentRowChange(row) {
      if (!this.crudMultiple) {
        if (row) {
          this.currentRow = row;
        }
      }
    },

    handleClose() {
      if (this.isOk === false) {
        this.$emit('cancel');
      }
    },

    handleList() {
      this.clearSelected();

      const params = {};

      // 外部传递参数
      const listKeys = Object.keys(this.listParams);

      if (listKeys.length > 0) {
        Object.assign(params, this.listParams);
      }

      Object.assign(params, this.searchCondition);

      params.elsAccount = getUserInfo().elsAccount;
      params.currentPage = this.crudPage.currentPage;
      params.pageSize = this.crudPage.pageSize;

      const apiFn = this.api || SupplierMasterDataService.list;

      apiFn(params)
        .then((res) => {
          if (res.data && res.data.code === '200' && res.data.data) {
            const pageData = res.data.data;

            this.crudData = pageData.rows;
            pageData.rows.forEach((item) => {
              this.crudData.forEach((i) => {
                if (i.toElsAccount === item.toElsAccount) {
                  i.toElsAccountName = item.toElsAccountName;
                }
              });
            });

            this.crudPage.total = pageData.total;

            this.crudPage.currentPage = this.crudPageParam.currentPage;
            this.crudPage.pageSize = this.crudPageParam.pageSize;
          } else {
            console.log('Failed to list suppliers.', res.data || res);
            this.$message.error(
              res.data.message ||
                LABELS.failedToQueryData.replace('?', LABELS.supplier.toLowerCase())
            );
          }
        })
        .catch((err) => {
          console.log('Error to list suppliers.', err);
          this.$message.error(LABELS.failedToQueryData.replace('?', LABELS.supplier.toLowerCase()));
        });
    },

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

    handleOpenDialog() {
      this.handleList();
    },

    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
    },

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

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

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

      this.handleList();

      done();
    },

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

    // 处理外部传入弹窗展示字段
    updateColumn() {
      const columns = this.column || this.option.column || supplierDialogOption.option.column;
      if (columns && columns.length) {
        this.crudOption.column = columns;
      }
    }
  }
};
</script>
<style lang="scss">
#supplierDialog .el-dialog {
  min-width: 720px;
}
</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>
