<template>
  <div>
    <a-modal v-model="visible" width="70%" :title="title" :footer="null" @cancel="afterDialogClose">
      <VxeRender
        ref="crud"
        :data="crudOption.data"
        :loadingState.sync="loading"
        :option.sync="crudOption.option"
        :page.sync="crudOption.page"
        :selection="multiple"
        :checkKey="checkKey"
        :selectionData="selectionData"
        :searchFormShow="searchFormShow"
        :showPager="crudOption.page.total !== 0"
        showType="page"
        @selection-change="selectionChange"
        @row-click="handleRowClick"
        @handle-search="searchChange"
        @handle-reset="handleReset"
        @page-change="currentChange"
      >
        <template slot="leftMenu">
          <a-button @click="handleSave">{{ labels.save }} </a-button>
        </template>
        <template slot="rightTools">
          <a-button type="circle" icon="search" @click="handleSearchShow" />
        </template>
      </VxeRender>
    </a-modal>
  </div>
</template>
<script>
import { cloneDeep } from 'lodash';
import VxeRender from '../widget/pop-vxe.vue';
import commonApi from '../../../lib/api';
import { ft } from '../../../lib/utils.js';
import { i18nConfig } from '../../../mixins/i18n';

const LABELS = {
  atLeastOneData: ft('i18n_common_at_least_one_data', '至少一条数据'),
  data: ft('i18n_common_data', '数据'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  save: ft('i18n_common_save', '保存')
};

export default {
  name: 'selectVxeDialog',
  components: { VxeRender },
  mixins: [i18nConfig],
  props: {
    title: { type: String, default: '' },
    api: { type: Function },
    checkKey: { type: String, default: '' },
    dialogVisible: { type: Boolean, default: false },
    multiple: { type: Boolean, default: false },
    selected: {
      type: Array,
      default: () => {
        return [];
      }
    },
    expandParams: {
      type: Object,
      default: () => {
        return {};
      }
    },
    columns: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // enAbleI18n: 是否支持多语言
    enAbleI18n: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      labels: LABELS,
      visible: this.dialogVisible,
      selectionData: [],
      crudSelection: [],
      searchFormShow: false,
      crudOption: {
        data: [],
        page: {
          currentPage: 1,
          pageSize: 500,
          pageSizes: [100, 500, 1000],
          total: 0
        },
        option: {
          column: []
        }
      },
      searchCondition: {},
      loading: false
    };
  },
  watch: {
    visible(newValue) {
      this.$emit('update:dialogVisible', newValue);
    },
    dialogVisible(newValue) {
      this.visible = newValue;
      if (newValue) {
        this.selectionData = cloneDeep(this.selected) || [];
        this.findPageList();
      }
    }
  },
  async created() {
    await this.getColumnDic();
    for (const item of this.columns) {
      if (this.enAbleI18n) {
        this.setI18n(item);
      } else {
        this.setDisplayName(item);
      }
    }
    this.crudOption.option.column = this.columns;
  },
  methods: {
    afterDialogClose() {
      this.crudSelection = [];
    },
    getColumnDic() {
      for (const column of this.columns) {
        if (column.bizDic || column.datatype === 'select' || column.datatype === 'bizDic') {
          commonApi.getDic(column.bizDic || column.prop).then((res) => {
            if (res.data && res.data.code === '200') {
              column.dicData = res.data.data;
            }
          });
        }
      }
    },
    selectionChange(list) {
      this.crudSelection = list;
    },
    handleSave() {
      if (this.crudSelection.length === 0) {
        this.$message.error(`${LABELS.pleaseSelect}${LABELS.atLeastOneData}`);
        return;
      }
      this.$emit('selectItem', this.crudSelection);
      this.visible = false;
    },
    async findPageList() {
      const params = Object.assign(
        {},
        this.crudOption.page,
        this.searchCondition,
        this.expandParams
      );

      this.loading = true;

      this.api(params)
        .then((res) => {
          if (res.data && res.data.code === '200') {
            this.crudOption.data = res.data.data.rows;
            this.crudOption.page.total = res.data.data.total;
          } else {
            console.log('Failed to list data.', res.data || res);
            this.$message.error(
              res.data.message || LABELS.failedToQueryData.replace('?', LABELS.data)
            );
          }
        })
        .catch((err) => {
          console.log('Error to list data', err);
          this.$message.error(LABELS.failedToQueryData.replace('?', LABELS.data));
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSearchShow() {
      this.searchFormShow = !this.searchFormShow;
    },
    searchChange(params) {
      this.searchCondition = params;
      this.crudOption.page.currentPage = 1;
      this.findPageList();
      this.crudSelection = [];
    },
    handleReset() {
      this.searchCondition = {};
      this.crudOption.page.currentPage = 1;
      this.findPageList();
      this.crudSelection = [];
      this.searchFormShow = false;
    },
    currentChange(page) {
      this.crudOption.page = page;
      this.findPageList();
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
  padding: 0 20px !important;
}
</style>
