<template>
  <div>
    <el-dialog
      class="selectMaterialBoxDialog"
      width="70%"
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @open="handleOpenDialog"
    >
      <div v-if="subtitle" style="margin-bottom: 10px; margin-top: -15px" v-text="subtitle"></div>
      <slot name="searchSlot"> </slot>
      <VxeRender
        checkKey="materialNumber"
        ref="crud"
        showType="page"
        v-model="crudObj"
        :data="crudList"
        :loadingState.sync="loading"
        :mergeKey="mergeKey"
        :option.sync="finalOption"
        :page.sync="materialSelectDialog.page"
        :selection="multiple"
        :selectionData="selectionData"
        @page-change="pageChange"
        @selection-change="selectionChange"
        @search-change="searchChange"
      >
        <template slot="leftMenu">
          <el-button type="primary" size="small" plain @click.stop="crudSave()">
            {{ btnText }}
          </el-button>
        </template>
      </VxeRender>
    </el-dialog>
  </div>
</template>
<script>
import materialSelectDialog from './const/materialSelectBoxDialog';
import { MaterialService } from '../../../lib/api/materials';
import { ft } from '../../../lib/utils.js';
import { cloneDeep } from 'lodash';
import VxeRender from './../widget/pop-vxe';

const LABELS = {
  atLeastOneData: ft('i18n_common_at_least_one_data', '至少一条数据'),
  data: ft('i18n_common_data', '数据'),
  batchSelection: ft('i18n_common_batch_selection', '批量选择'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  materials: ft('i18n_common_materials', '物料'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  ok: ft('i18n_common_ok', '确定'),
  save: ft('i18n_common_save', '保存'),
  select: ft('i18n_common_select', '选择'),
  serialNumber: ft('i18n_common_serial_number', '序号')
};

export default {
  name: 'SelectMaterialBoxDialog',
  components: { VxeRender },
  props: {
    api: {
      type: Function,
      default: MaterialService.list
    },
    expendParams: {
      type: Object,
      default: () => {
        return {};
      }
    },
    btnText: { type: String, default: LABELS.ok }, // 保存按钮文字
    title: { type: String, default: '' }, // dialog 标题
    subtitle: { type: String, default: '' }, // dialog 副标题
    dialogVisible: { type: Boolean, default: false }, // dialog显隐

    params: {
      type: Object,
      default: () => {
        return {};
      }
    },
    selectedMaterial: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },

    option: {
      type: Object,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      visible: this.dialogVisible,
      selectionData: [],
      crudData: [],
      materialSelectDialog: materialSelectDialog,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      queryParam: {},
      crudMultiple: false,
      currentRow: null,
      allSelectItem: [], // 所有选择的
      mergeKey: [
        'checkbox',
        'materialNumber',
        'materialName',
        'materialDesc',
        'materialSpecifications'
      ],
      loading: false
    };
  },
  created() {
    this.crudMultiple = this.multiple;
  },
  computed: {
    crudList() {
      return this.materialSelectDialog.data.map((item) => {
        item.itemStatus = this.selectionData
          ? this.selectionData.map((i) => i.materialNumber).includes(item.materialNumber)
          : false;
        return item;
      });
    },

    finalOption() {
      const finalOption = cloneDeep(this.materialSelectDialog.option);
      const option = this.option || {};
      const columns = option.column || finalOption.column;

      finalOption.column = columns;

      return finalOption;
    }
  },
  watch: {
    visible: function (newValue) {
      this.$emit('update:dialogVisible', newValue);
    },
    dialogVisible: function (newValue) {
      this.visible = newValue;
    }
  },
  methods: {
    crudSave() {
      const selectItems = this.selectionData;
      this.selectColumns = [];
      this.$emit('handleSure', this.allSelectItem);
      this.$emit('ok', selectItems);
      this.$emit('selectDone', selectItems);
      this.visible = false;
    },

    doAction() {
      const selectItems = cloneDeep(this.selectionData);

      if (selectItems.length < 1) {
        this.$message.warning(`${LABELS.pleaseSelect}${LABELS.atLeastOneData}`);
        return;
      }

      this.selectionData = [];
      this.$emit('ok', selectItems);
      this.visible = false;
    },

    // 物料列表
    getMaterialData(queryCondition = {}, pagination = this.page) {
      const params = {
        ...this.expendParams,
        ...this.params,
        pageSize: pagination.pageSize,
        currentPage: pagination.currentPage
      };

      for (const key in queryCondition) {
        if (queryCondition[key]) {
          params[key] = queryCondition[key];
        }
      }

      this.loading = true;

      const api = this.api;
      api(params)
        .then((res) => {
          if (res.data && res.data.code === '200' && res.data.data) {
            const data = res.data.data;

            this.materialSelectDialog.data = data.rows;

            this.materialSelectDialog.page.total = data.total;
            this.materialSelectDialog.page.pageSize = pagination.pageSize;
            this.materialSelectDialog.page.currentPage = pagination.currentPage;
          } else {
            console.log('Failed to list materials.', res.data || res);
            this.$message.error(
              'res.data.message' ||
                LABELS.failedToQueryData.replace('?', LABELS.materials.toLowerCase())
            );
          }
        })
        .catch((err) => {
          console.log('Error to list materials.', err);
          this.$message.error(
            LABELS.failedToQueryData.replace('?', LABELS.materials.toLowerCase())
          );
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleCheckChange(value, row) {
      const materialNumber = row.materialNumber;
      if (
        this.selectionData &&
        this.selectionData.map((item) => item.materialNumber).includes(materialNumber)
      ) {
        const index = this.selectionData.findIndex(
          (item) => item.materialNumber === materialNumber
        );
        this.selectionData.splice(index, 1);
      } else {
        this.selectionData.push(row);
      }
    },

    handleOpenDialog() {
      this.page = {
        ...this.page,
        currentPage: 1,
        pageSize: 100
      };

      if (this.visible) {
        this.getMaterialData(this.queryParam, this.page);
        this.selectionData = cloneDeep(this.selectedMaterial) || [];
      }
    },

    pageChange(page) {
      this.page = page;
      this.getMaterialData(this.queryParam, this.page);
    },

    refreshChange() {
      this.getMaterialData(this.queryParam, this.page);
    },

    selectionChange(array) {
      this.allSelectItem = array;
    },

    searchChange(params) {
      this.queryParam = params;
      this.page.currentPage = 1;
      this.getMaterialData(this.queryParam, this.page);
    },

    toggleSelection(rows) {
      if (!this.$refs.materialCrud) {
        return;
      }
      if (rows) {
        rows.forEach((row) => {
          this.$refs.materialCrud.toggleRowSelection(row);
        });
      } else {
        this.$refs.materialCrud.clearSelection();
      }
    }
  }
};
</script>

<style>
.selectMaterialBoxDialog .el-dialog__body {
  padding-top: 5px;
  padding-bottom: 20px;
}
</style>
