<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
      :id="dialogElementId"
      :title="title"
      :visible.sync="visible"
      append-to-body
      @open="handleOpenDialog"
    >
      <avue-crud
        ref="crud"
        v-if="crudOption.column.length"
        v-model="crudObj"
        :data.sync="crudData"
        :option.sync="crudOption"
        :page.sync="crudPage"
        @row-dblclick="handleOk"
        @selection-change="selectionChange"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @current-row-change="currentRowChange"
      >
        <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 { ElsOrgInfoService } from '../../../lib/api/materials';
import { bringMessageBeforeDialog, ft } from '../../../lib/utils.js';
import DialogOption from './const/purchaseOrgList';
import { getUserInfo } from '../../../lib/auth';

const LABELS = {
  data: ft('i18n_common_data', '数据'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  noData: ft('i18n_common_no_data', '暂无数据'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  purchasingOrganization: ft('i18n_common_purchasing_organization', '采购组织'),
  save: ft('i18n_common_save', '保存'),
  select: ft('i18n_common_select', '选择'),
  serialNumber: ft('i18n_common_serial_number', '序号')
};

export default {
  name: 'SelectPurchaseOrganization',
  props: {
    elsAccount: { type: String, default: '' }, // elsAccount
    elsSubAccount: { type: String, default: '' }, // elsSubAccount

    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.purchasingOrganization}`
    },

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

    api: {
      type: Function,
      default: () => {
        return ElsOrgInfoService.listPurchaseOrganization;
      }
    },
    // 表格的分页配置
    page: {
      type: Object,
      default: () => {
        return { total: 0, currentPage: 1, pageSize: 10, pagerCount: DEFAULT_PAGER_COUNT };
      }
    }
  },
  data() {
    return {
      dialogElementId: 'purchaseOrganizationDialog',
      visible: this.dialogVisible,
      selectColumns: [],
      crudObj: {},
      crudData: [],
      crudOption: {
        indexLabel: LABELS.serialNumber,
        indexFixed: false,
        searchShow: false,
        searchBtn: true,
        columnBtn: false,
        refreshBtn: false,
        align: 'center',
        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,
        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 = DialogOption.option.column;
    this.crudPage = this.page;
    this.crudMultiple = this.multiple;
    this.crudOption.selection = this.multiple;
    this.crudOption.highlightCurrentRow = !this.multiple;
  },
  methods: {
    handleOpenDialog() {
      this.handleList();
    },
    handleClose() {
      this.crudData = [];
    },
    // $ft(code, str) {
    //   return ft(code, str);
    // },
    handleList() {
      this.clearSelected();

      const listParams = {
        ...this.searchCondition
      };

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

      ElsOrgInfoService.listPurchaseOrganization(this.actionPath, listParams)
        .then((res) => {
          if (res.data && res.data.code === '200') {
            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 purchasing organizations.', res.data || res);
            this.$message.error(
              res.data.message ||
                LABELS.failedToQueryData.replace('?', LABELS.purchasingOrganization.toLowerCase())
            );
          }
        })
        .catch((err) => {
          console.log('Error to list purchasing organizations.', err);
          this.$message.error(
            LABELS.failedToQueryData.replace('?', LABELS.purchasingOrganization.toLowerCase())
          );
        });
    },

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

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

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

    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.crudPageParam.currentPage = page;
      this.handleList();
    },

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

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

    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>
.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>
