<template>
  <view class="dict-selection">
    <view class="select-input" :class="{ disabled: disabled }" @click="handleClick">
      <text class="value-text">{{ displayValue || placeholder }}</text>
      <text class="arrow" v-if="!disabled">›</text>
    </view>
    <u-picker
      :show="showPicker"
      :columns="[dictList]"
      keyName="label"
      @confirm="onConfirm"
      @cancel="showPicker = false"
    ></u-picker>
  </view>
</template>

<script>
import dictEnum from '@/enum/dict';
import { mapActions, mapGetters } from 'vuex';

export default {
  model: {
    prop: 'value',
    event: 'updateVal'
  },
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    dictName: {
      type: String,
      required: true
    },
    labelName: {
      type: String,
      default: 'dictValue'
    },
    valueName: {
      type: String,
      default: 'dictCode'
    },
    listFormatte: Function,
    placeholder: {
      type: String,
      default: '请选择'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showPicker: false
    };
  },
  computed: {
    ...mapGetters(['dict', 'getDict']),
    dictList() {
      const list =
        (this.listFormatte &&
          this.listFormatte(this.dict[dictEnum[this.dictName]] || [])) ||
        this.dict[dictEnum[this.dictName]] ||
        [];
      return list.map(item => ({
        label: item[this.labelName],
        value: item[this.valueName],
        ...item
      }));
    },
    displayValue() {
      if (!this.value && this.value !== 0) return '';
      const item = this.dictList.find(d => d.value == this.value);

      return item ? item.label : '';
    }
  },
  created() {
    if (this.dictName) {
      this.requestDict(this.dictName);
    }
  },
  methods: {
    ...mapActions('dict', ['requestDict']),
    handleClick() {
      if (!this.disabled) {
        this.showPicker = true;
      }
    },
    onConfirm(e) {
      const value = e.value[0].value;
      this.$emit('updateVal', value);
      this.$emit('itemChange', this.getDict(this.dictName, value));
      this.showPicker = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.dict-selection {
  width: 100%;
}

.select-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  min-height: 70rpx;
  border-bottom: 1rpx solid #e5e5e5;

  &.disabled {
    opacity: 0.6;
  }

  .value-text {
    flex: 1;
    font-size: 28rpx;
    color: #333;

    &.empty {
      color: #999;
    }
  }

  .arrow {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
    margin-left: 20rpx;
  }
}
</style>