<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-dialog
      append-to-body
      :id="dialogElementId"
      :title="title"
      :visible.sync="visible"
      @open="handleList"
    >
      <el-button type="primary" size="small" plain v-text="btnText" @click.stop="handleOk()">
      </el-button>
      <avue-crud
        ref="crud"
        v-model="crudObj"
        :data.sync="crudData"
        :option.sync="crudOption"
        :page.sync="crudPage"
        @row-dblclick="handleOk"
        @selection-change="selectionChange"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @current-row-change="currentRowChange"
      >
      </avue-crud>
    </el-dialog>
  </div>
</template>
<script>
import { DEFAULT_PAGER_COUNT, DIALOG_TABLE_MAX_HEIGHT, STATION } from '../../../lib/const';
import { bringMessageBeforeDialog, ft, getBusinessAccount } from '../../../lib/utils.js';
import { ElsAccountService } from '../../../lib/api/materials';
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', '暂无数据'),
  personName: ft('i18n_common_person_name', '姓名'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  purchasingGroup: ft('i18n_common_purchasing_group', '采购组'),
  responsiblePerson: ft('i18n_common_responsible_person', '负责人'),
  save: ft('i18n_common_save', '保存'),
  select: ft('i18n_common_select', '选择'),
  subAccount: ft('i18n_common_sub_account', '子账号')
};

export default {
  name: 'SelectPurchaseLeader',
  props: {
    elsAccount: { type: String, default: '' }, // elsAccount
    elsSubAccount: { type: String, default: '' }, // elsSubAccount
    btnText: { type: String, default: LABELS.save }, // 保存按钮文字
    title: { type: String, default: '' }, // dialog标题
    selected: { type: String, default: '' },
    actionPath: { type: String, default: null }, // 数据接口地址

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

    // 表格的列配置
    column: {
      type: Array,
      default: () => {
        return [
          {
            label: LABELS.subAccount,
            prop: 'elsSubAccount',
            overHidden: true,
            search: true,
            searchSpan: 12
          },
          {
            label: LABELS.personName,
            prop: 'name',
            overHidden: true,
            search: true,
            searchSpan: 12
          }
        ];
      }
    },
    // 表格的分页配置
    page: {
      type: Object,
      default: () => {
        return { total: 0, currentPage: 1, pageSize: 10, pagerCount: DEFAULT_PAGER_COUNT };
      }
    }
  },
  data() {
    return {
      dialogElementId: 'employeeDialog',
      visible: this.dialogVisible,
      selectColumns: [],
      currentRow: null,

      crudObj: {},
      crudData: [],
      crudOption: {
        indexLabel: '#',
        indexFixed: false,
        header: true,
        searchShow: false,
        searchBtn: true,
        columnBtn: false,
        align: 'center',
        menu: false,
        refreshBtn: 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,
        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;

          this.selected = row.elsSubAccount + '_' + row.name + ' ';
        }
      }
    },

    handleList() {
      this.clearSelected();

      const userInfo = getUserInfo();
      const params = {};

      Object.assign(params, this.searchCondition);

      params.currentPage = this.crudPage.currentPage;
      params.pageSize = this.crudPage.pageSize;

      let queryAction;

      if (userInfo.station === STATION.SALE) {
        params.toElsAccount = getBusinessAccount(userInfo);

        queryAction = 'listPurchaseEmployeeBySale';
      } else {
        params.elsAccount = userInfo.elsAccount;

        queryAction = 'listEmployee';
      }

      ElsAccountService[queryAction](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 {
            const resData = res.data || res;
            console.log('Failed to list purchase employees.', resData);
            this.$message.error(
              resData.message ||
                LABELS.failedToQueryData.replace('?', LABELS.responsiblePerson.toLowerCase())
            );
          }
        })
        .catch((err) => {
          console.log('Error to list purchase employees.', err);
          this.$message.error(
            LABELS.failedToQueryData.replace('?', LABELS.responsiblePerson.toLowerCase())
          );
        });
    },

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

    ok() {
      const selectItems = this.crudMultiple ? this.selectColumns : [this.currentRow];

      this.clearSelected();

      this.$emit('selectDone', selectItems);

      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.handleList();

      done();
    },

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

        let str = '';

        list.map((item) => {
          str += item.elsSubAccount + '_' + item.name + ' ';
        });

        this.selected = str;
      }
    },

    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>
