import { selectTypeMapping } from '@/config';
import { mapGetters, mapActions } from 'vuex';

const getterList = selectTypeMapping.map(types => `optionList${types.value}`);
const actionsList = selectTypeMapping.map(
  types => `fetchOptionList${types.value}`
);

export default {
  data() {
    return {
      baseDataOptionsLabel: [], // 页面需要声明需要使用的基础数据 例如: ['赠送类型']
    };
  },
  created() {
    this.baseDataOptionsLabel.map(this.getOptionsValue).map(value => {
      if (!this[`optionList${value}`].length) {
        this[`fetchOptionList${value}`]();
      }
    });
  },
  computed: {
    ...mapGetters(getterList),
  },
  methods: {
    ...mapActions(actionsList),
    changeHandle(val) {
      this.$emit('input', val);
    },
    getOptionsList(label) {
      let optionValue = this.getOptionsValue(label);
      if (optionValue) {
        let options = this.$store.getters['optionList' + optionValue];
        if (options && options.length) {
          return Promise.resolve(options);
        } else {
          return this.$store.dispatch('fetchOptionList' + optionValue);
        }
      } else {
        return Promise.resolve([]);
      }
    },
    getOptionsValue(label) {
      let item = selectTypeMapping.find(item => item.label === label);
      return item ? item.value : null;
    },
    getOptionsName(label, val) {
      let optionValue = this.getOptionsValue(label);
      if (optionValue) {
        let item = this[`optionList${optionValue}`].find(
          ({ value }) => val === value
        );
        return item ? item.name : '';
      }
      return '';
    },
    formatterMoneyToDouble(val) {
      return val ? Number(val).toFixed(2) : Number(0).toFixed(2);
    },
  },
};