<template>
  <div @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
      size="small"
      v-if="batchAddition || multiple"
      @click.stop="handleOpenBatchAddition"
      >{{ batchAdditionBtnText }}</el-button
    >
    <el-button v-else size="small" @click.stop="openFieldDialog">{{ addBtnText }}</el-button>

    <el-dialog
      append-to-body
      :id="dialogElementId"
      :title="title"
      :visible.sync="visible"
      @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"
        @row-dblclick="handleOk"
        @search-change="searchChange"
        @search-reset="searchReset"
        @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 { ReconNumberService } from '../../../lib/api/materials';
import { getUserInfo } from '../../../lib/auth';
import reconNumberDialogOption from './const/reconNumberList';

const LABELS = {
  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', '请选择'),
  reconciliations: ft('i18n_common_reconciliations', '对账单'),
  save: ft('i18n_common_save', '保存'),
  select: ft('i18n_common_select', '选择'),
  serialNumber: ft('i18n_common_serial_number', '序号')
};

export default {
  name: 'SelectRecon',
  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.reconciliations}` },

    batchAddition: { type: Boolean, default: false }, // 批量添加
    batchAdditionBtnText: {
      type: String,
      default: `${LABELS.batchSelection} ${LABELS.reconciliations}`
    },

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

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

    openBatchAdditionFn: {
      type: Function
    }
  },
  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: {
    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.crudPage = this.page;
    this.crudMultiple = this.multiple;
    this.crudOption.selection = this.multiple;
    this.crudOption.highlightCurrentRow = !this.multiple;
  },
  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;
        }
      }
    },

    handleList() {
      this.clearSelected();

      const params = this.listParams;

      Object.assign(params, this.searchCondition);

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

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

            this.crudData = pageData.rows;
            this.crudPage.total = pageData.total;

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

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

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

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

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

      this.crudPage.currentPage = 1;
      this.handleList();

      done();
    },

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

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

    sizeChange(pageSize) {
      this.crudPageParam.currentPage = 1;
      this.crudPageParam.pageSize = pageSize;
      this.handleList();
    }
  }
};
</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>
