<template>
  <picker :range="displayOptions" @change="onChange">
    <view class="form-select">
      <text :class="['select-text', hasValue ? '' : 'placeholder']">
        {{ hasValue ? selectedLabel : placeholder }}
      </text>
      <image src="https://mrrplus.oss-cn-beijing.aliyuncs.com/wxstaic/images/arrow_right.png" class="arrow-right"
        mode="aspectFit" />
    </view>
  </picker>
</template>

<script>
export default {
  name: 'FormItemSelect',
  props: {
    value: { type: [String, Number], default: '' },
    options: { type: Array, default: function () { return []; } },
    placeholder: { type: String, default: '请选择' }
  },
  computed: {
    displayOptions: function () {
      var self = this;
      return this.options.map(function (item) {
        return self.getOptionLabel(item);
      });
    },
    hasValue: function () {
      return this.value !== undefined && this.value !== null && this.value !== '';
    },
    selectedLabel: function () {
      var self = this;
      var selected = this.options.find(function (item) {
        return self.getOptionValue(item) == self.value;
      });
      return selected !== undefined ? this.getOptionLabel(selected) : this.value;
    }
  },
  methods: {
    getOptionValue: function (item) {
      if (item && typeof item === 'object') {
        if (item.value !== undefined) return item.value;
        if (item.id !== undefined) return item.id;
        if (item.key !== undefined) return item.key;
        if (item.code !== undefined) return item.code;
        return item.label;
      }
      return item;
    },
    getOptionLabel: function (item) {
      if (item && typeof item === 'object') {
        var label = item.label || item.title || item.name || item.text;
        if (label !== undefined && label !== null) return label;
        return String(this.getOptionValue(item));
      }
      return item;
    },
    onChange: function (e) {
      var index = e.detail.value;
      var selected = this.options[index];
      if (selected !== undefined) {
        this.$emit('input', this.getOptionValue(selected));
      }
    }
  }
};
</script>

<style scoped>
.form-select {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.select-text {
  font-size: 28rpx;
  color: #333333;
  margin-right: 16rpx;
}

.placeholder {
  font-weight: 400;
  font-size: 28rpx;
  color: #999999;
}

.arrow-right {
  width: 32rpx;
  height: 32rpx;
}
</style>
