<template>
  <!-- 物料明细弹窗 -->
  <div class="materialBox" @click.stop="preventBubblingUp">
    <span v-if="readonly" v-text="selected"></span>
    <el-input readonly size="small" v-else-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="openFieldDialog">
      {{ addBtnText }}
    </el-button>

    <SelectDialogTable
      ref="materialsDialog"
      :beforeCloseFn="listHandlers.beforeCloseFn"
      :column.sync="finalColumns"
      :customSlots="customSlots"
      :data="materialsDialogOption.data"
      :dialog-element-id="dialogElementId"
      :dialog-visible.sync="materialDlgVisible"
      :loading="loading"
      :multiple="materialsDialogOption.option.multiple"
      :page="materialsDialogOption.page"
      :page-param="materialsDialogPageParam"
      :query-param="materialsDialogQueryParam"
      :searchResetFn="listHandlers.searchResetFn"
      :title="labels.materials"
      @handleList="handleList"
      @ok="selectedMaterials"
    >
      <!-- 自定义 slots -->
      <template
        v-for="customSlotItem in customSlotItems"
        :slot="customSlotItem.prop"
        slot-scope="{ row }"
      >
        <slot
          v-if="customSlotItem && customSlotItem.prop"
          :slot-scope="row"
          :name="customSlotItem.slotName"
        />
      </template>
    </SelectDialogTable>
  </div>
</template>
<script>
import SelectDialogTable from '../selectDialog/selectDialogTablePage';
import materialsDialogOption from './const/materialsDialog';
import { getUserInfo } from '../../../lib/auth';
import { MaterialService } from '../../../lib/api/materials';
import { ft } from '../../../lib/utils.js';
import cloneDeep from 'lodash/cloneDeep';

const LABELS = {
  add: ft('i18n_common_add', '添加'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  materials: ft('i18n_common_materials', '物料')
};

export default {
  name: 'SelectMaterial',
  components: {
    SelectDialogTable
  },
  props: {
    api: {
      type: Function,
      default: MaterialService.list
    },

    listParams: {
      type: Object,
      default: () => {
        return {};
      }
    },

    columns: {
      type: Object,
      default: () => {
        return null;
      }
    },

    // customSlots: 自定义 slots, 只输出 slot name, 具体内容由使用都定义(不在组件内部定义), 最多支持 10 个自定义 slot
    customSlots: {
      type: Array,
      default: function () {
        return [];
      }
    },

    selected: { type: String, default: '' },
    addBtnText: { type: String, default: `${LABELS.add}${LABELS.materials}` },

    isDisabled: { type: Boolean, default: false }, // 是否禁用
    multiple: { type: Boolean, default: false },

    /*
     * 增加 readonly 用于二级 slot 显示内容,
     * 解決 slot 未启用时, vxe-table 行编辑, 没有对应的内容显示，导致单元格空白
     */
    readonly: { type: Boolean, default: false },

    beforeCloseFn: {
      type: Function,
      default: null
    },

    listHandlers: {
      type: Object,
      default: function () {
        return {
          beforeCloseFn: null,
          searchResetFn: null
        };
      }
    },

    searchResetFn: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      labels: LABELS,
      materialDlgVisible: false,
      dialogElementId: 'selectMaterialDialog',
      dialogTitle: '',
      dialogWidth: '60%',

      loading: true,

      materialsDialogOption: materialsDialogOption,
      materialsDialogQueryParam: {},
      materialsDialogPageParam: { pageNo: 1, pageSize: 10 },
      fieldDialogForm: {
        materials: []
      },

      customSlotItems: []
    };
  },

  computed: {
    finalColumns() {
      const columns =
        this.columns && Array.isArray(this.columns) && this.columns.length > 0
          ? this.columns
          : cloneDeep(this.materialsDialogOption.option.column);

      return columns;
    }
  },

  watch: {
    customSlots: {
      handler: function (newVal, oldVar) {
        if (newVal) {
          this.handleCustomSlotsChanged(newVal);
        }
      },
      immediate: true,
      deep: true
    }
  },

  methods: {
    closeFieldDialog() {
      this.materialDlgVisible = false;
    },

    handleCustomSlotsChanged(customSlots = []) {
      for (const customSlot of customSlots) {
        if (customSlot && customSlot.prop && customSlot.slotName) {
          this.customSlotItems.push(customSlot || {});
        }
      }
    },

    handleList(queryCondition = {}, pagination) {
      const params = {
        auditStatus: 0,
        elsAccount: getUserInfo().elsAccount,
        elsSubAccount: 1001,
        pageSize: pagination.pageSize,
        currentPage: pagination.currentPage,
        isFreeze: 'N',
        deleteIndicator: 'N'
      };

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

      // 外部传递参数
      for (const key in this.listParams) {
        if (this.listParams[key]) {
          params[key] = this.listParams[key];
        }
      }

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

            const pageData = res.data.data;

            if (pageData && Array.isArray(pageData)) {
              this.materialsDialogOption.data = pageData;
            } else {
              this.materialsDialogOption.data = pageData.rows || [];
            }

            this.materialsDialogOption.page.total = pageData.total || 0;
          } else {
            console.log('Failed to list materials.', res.data || res);
            this.$message.error(
              res.data.message ||
                LABELS.failedToQueryData.replace('?', LABELS.materials.toLowerCase())
            );
          }
        })
        .catch((err) => {
          this.loading = false;

          console.log('Error to list materials.', err);
          this.$message.error(
            LABELS.failedToQueryData.replace('?', LABELS.materials.toLowerCase())
          );
        });
    },

    openFieldDialog(title = LABELS.add, row = {}) {
      this.fieldDialogForm = title
        ? {
            elsAccount: getUserInfo().elsAccount,
            whetherDefault: 'Y',
            fromDesc: '',
            fromBusiness: '',
            materials: []
          }
        : {
            ...row,
            materials: []
          };

      this.dialogTitle = `${title}${LABELS.materials}`;
      this.materialDlgVisible = true;
    },

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

    selectedMaterials(materialList) {
      this.$emit('selectDone', materialList);
    }
  }
};
</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>
