<template>
  <div class="selectBox" @click.stop="preventBubblingUp">
    <el-input readonly size="small" v-if="!multiple" v-model="selectedData" :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
      ref="selectBoxOInnerDialog"
      :id="dialogElementId"
      :title="title"
      :visible.sync="visible"
      :width="width"
      @open="handleOpenDialog"
    >
      <VxeRender
        ref="crud"
        v-model="crudObj"
        :checkKey="rowKey"
        :data.sync="crudData"
        :hasSearchBar="hasSearchBar"
        :loadingState.sync="loading"
        :option.sync="crudOption"
        :page.sync="crudPage"
        :selection="multiple"
        :showPager="showPager"
        :showType="showType"
        @close-dialog="closeDialog"
        @page-change="pageChange"
        @refresh-change="refreshChange"
        @search-change="searchChange"
        @selection-change="selectionChange"
      >
        <template slot="leftMenu">
          <el-button type="primary" size="small" plain @click.stop="crudSave()">
            {{ btnText }}
          </el-button>
        </template>
      </VxeRender>
    </el-dialog>
  </div>
</template>
<script>
import { getUserInfo } from '../../../lib/auth';
import { ft } from '../../../lib/utils.js';
import VxeRender from './../widget/pop-vxe';
export default {
  name: 'baseSelect',
  inheritAttrs: false,
  components: { VxeRender },
  props: {
    elsAccount: { type: String, default: '' }, // elsAccount
    elsSubAccount: { type: String, default: '' }, // elsSubAccount

    actionPath: { type: String, default: '' }, // 数据接口地址
    addBtnText: { type: String, default: '' },
    btnText: { type: String, default: '' }, // 保存按钮文字
    dialogElementId: { type: String, default: 'selectBoxOInnerDialogId' },
    selected: { type: String, default: '' },
    title: { type: String, default: '' }, // dialog标题
    type: { type: String, default: '' },
    width: { type: String, default: '60%' },

    tableColumn: {
      type: Array,
      default: () => {
        return [];
      }
    },

    data: {
      type: Array,
      default: () => {
        return [];
      }
    },

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

    loadingState: {
      type: Boolean,
      default: false
    },

    api: {
      type: Function
    },

    params: {
      type: Object,
      default: () => {
        return {
          elsAccount: getUserInfo().elsAccount
        };
      }
    },

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

    showType: {
      type: String,
      default: 'page'
    }
  },
  data() {
    return {
      crudData: [],
      crudMultiple: true,
      crudObj: {},
      crudOption: {
        column: []
      },
      crudPage: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      showPager: true, // 是否展示分页

      loading: this.loadingState || false,

      selectColumns: [],
      selectedData: '',

      visible: this.dialogVisible
    };
  },

  watch: {
    column: function (newValue) {
      this.crudOption.column = newValue;
    },
    data: function (newValue) {
      this.crudData = newValue;
    },
    dialogVisible: function (newValue) {
      this.visible = newValue;
    },

    loadingState(newVal) {
      this.loading = newVal;
    },

    page: function (newValue) {
      this.crudPage = newValue;
    },
    selected: function (newValue) {
      this.selectedData = newValue;
    },
    visible: function (newValue) {
      this.$emit('update:dialogVisible', newValue);
    }
  },
  created() {
    this.crudOption.column = this.tableColumn;
    this.crudPage = this.page;
    this.crudMultiple = this.multiple;
    this.crudOption.selection = this.multiple;
    this.crudOption.highlightCurrentRow = !this.multiple;
    this.selectedData = this.selected;
  },

  methods: {
    handleList() {
      const LABELS = {
        failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败')
      };

      const reqData = {
        ...this.params,
        currentPage: this.crudPage.currentPage,
        pageSize: this.crudPage.pageSize
      };

      this.loading = true;

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

            // 兼容处理没有分页直接返回 list 的场景
            if (rows && Array.isArray(rows)) {
              this.crudData = rows;
              this.crudPage.total = pageData.total;
            } else {
              this.showPager = false;
              this.crudData = pageData;
              this.crudPage.total = this.crudData.length;
            }
          } else {
            console.log('Failed to list data.', res.data || res);
            this.$message.error(
              res.data.message || LABELS.failedToQueryData.replace('?', this.type)
            );
          }
        })
        .catch((err) => {
          console.log('Error to list data.', err);
          this.$message.error(LABELS.failedToQueryData.replace('?', this.type));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleOpenDialog() {
      if (this.api) {
        this.handleList();
      } else {
        this.$emit('on-load');
      }
    },

    crudSave() {
      const selectItems = this.selectColumns;
      this.selectColumns = [];
      this.$emit('selectDone', selectItems);
      this.visible = false;
    },

    currentRowChange(row) {
      if (!this.crudMultiple) {
        const list = [];
        list.push(row);
        this.selectColumns = list;
      }
    },

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

    pageChange(page) {
      this.crudPage = page;
      this.handleList();
    },

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

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

    searchChange(params) {
      this.crudPage.currentPage = 1;
      // Object.assign(this.crudQueryParam, params);
      this.handleList();
    },

    selectionChange(list) {
      this.selectColumns = list;
    }
  }
};
</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>
