<!-- 下拉列表表单组件 zhao -->
<template>
  <div>
    <van-field
      :readonly="true"
      :clickable="!readonly"
      :name="name"
      :value="visibleValue"
      :label="label"
      :placeholder="placeholder"
      @click="openPopup"
      input-align="right"
      right-icon="arrow-down"
      :rules="rules"
      :required="required"
      :label-width="labelWidth || 'auto'"
      :size="size || ''"
    >
    </van-field>
    <van-popup v-model="popupVisible" position="bottom">
      <van-picker
        ref="picker"
        :title="label"
        show-toolbar
        :columns="columns ? columns : remoteColumns"
        :readonly="readonly"
        :value-key="valueKey"
        :loading="loading"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChanged"
      />
    </van-popup>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "fieldSelect",
  props: [
    'name', 'readonly', 'value', 'label', 'placeholder', 'required', 'rules', 'labelWidth',
    'columns', // 列表数据 Array
    'valueKey', // 名称键名 String
    'dataKey', // 值键名 String
    'remoteUrl', // 远程列表加载地址 String
    'onRemoteResponse', // 远程获取到结果的处理回调 String|Function 如果是函数需返回数组, 如果是字符串支持.分割
    'clearable', // 点击取消时清空绑定值
    'size',
  ],
  watch: {
    value: function (newVal, oldVal) {
      this.internalValue = newVal;
      this.visibleValue = newVal;
      this.syncIndex();
    },
    columns: function (newVal, oldVal) {
      this.syncIndex();
    },
    remoteUrl: function (newVal, oldVal) {
      this.requestRemote();
    },
    onRemoteResponse: function (newVal, oldVal) {
      this.parseRemote();
    }
  },
  created() {
    if(this.remoteUrl)
      this.requestRemote();
  },
  data() {
    return {
      popupVisible: false,
      internalValue: this.value,
      visibleValue: '',
      defaultIndex: 0,
      remoteColumns: null,
      loading: false,
      remoteResponse: null,
    };
  },
  methods: {
    openPopup() {
      if(!this.readonly)
      {
        this.popupVisible = true;
        this.$nextTick(() => {
          this.$refs.picker.setIndexes([this.defaultIndex]);
        })
      }
    },
    closePopup() {
      this.popupVisible = false;
    },
    onChanged(data) {
      this.$emit('change', data);
    },
    onConfirm(data) {
      this.syncValue(data);
      this.$emit('input', this.internalValue);
      this.$emit('confirm', this.internalValue);
      this.closePopup();
    },
    onCancel() {
      this.closePopup();
      this.$emit('cancel');
      if(this.clearable)
      {
        this.visibleValue = '';
        this.internalValue = null;
        this.$emit('input', this.internalValue);
      }
    },
    getValue(data) {
      return typeof(data) === 'object' && this.dataKey ? data[this.dataKey] : data;
    },
    getLabel(data) {
      return typeof(data) === 'object' && this.valueKey ? data[this.valueKey] : data;
    },
    syncValue(data) {
      this.internalValue = this.getValue(data);
      this.visibleValue = this.getLabel(data);
    },
    syncIndex() {
      let columns = this.getColumns();
      if(!columns)
        return -1;
      for(let i in columns)
      {
        if(this.getValue(columns[i]) == this.internalValue) {
          this.defaultIndex = i;
          this.visibleValue = this.getLabel(columns[i]);
          this.onChanged(columns[i]);
          return i;
        }
      }
      if(1) // 不存在
      {
        this.defaultIndex = -1;
        this.visibleValue = this.internalValue;
        this.onChanged(null);
      }
      return -1;
    },
    getColumns() {
      return this.columns ? this.columns : this.remoteColumns;
    },
    requestRemote() {
      if(!this.remoteUrl)
        return;
      this.loading = true;
      this.remoteColumns = [];
      let promise = typeof(this.remoteUrl) === 'function' ? this.remoteUrl() : (this.remoteUrl instanceof Promise ? this.remoteUrl : request(this.remoteUrl));
      promise.then((resp) => {
        this.remoteResponse = resp;
        this.parseRemote();
        this.syncIndex();
      }).catch((e) => {
        console.error(e);
      }).finally(() => {
        this.loading = false;
      })
    },
    parseRemote() {
      if(!this.remoteResponse)
        return;
      let type = typeof(this.onRemoteResponse);
      if(type === 'function')
        this.remoteColumns = this.onRemoteResponse(this.remoteResponse);
      else if(type === 'string')
      {
        let arr = this.onRemoteResponse.split('.');
        let ptr = this.remoteResponse;
        for(let i in arr)
        {
          ptr = this.remoteResponse[arr[i]];
        }
        this.remoteColumns = ptr;
      }
      else
        this.remoteColumns = this.remoteResponse;
    },
  },
}
</script>

<style scoped>

</style>
