<template>
  <div class="data-select">
    <Select
      v-show="!readonly"
      ref="select"
      v-bind="$attrs"
      :value="strValue"
      :parent-val="parentVal"
      :code="code"
      :size="size"
      :placeholder="placeholder"
      :disabled="disabled"
      transfer
      :clearable="clearable"
      v-on="$listeners"
      @input="handleInput"
    >
      <Option
        v-for="item in dataList"
        :key="item.value + item.label"
        :value="item.value"
      >
        {{ item.label }}
      </Option>
    </Select>
    <span v-if="readonly">{{ selItemName }}</span>
  </div>
</template>
<script>
/**
 * 反显值集信息下拉框组件
 * 该组件需要返回数据严格为：[{label: 'xxx', value: 'xxx'}]格式
 * 其它props和event请参考iview select组件
 */
import { QueryValueSetByCodeAndParentKey, QueryValueSetByCode } from '../server.js';
export default {
  name: 'DataSelect',
  directives: {},
  props: {
    value: {
      type: [String, Number, Array],
      default() {
        return '';
      }
    },
    datas: {
      type: Array,
      default() {
        return [];
      }
    },
    // 值集code
    code: {
      type: String,
      default() {
        return '';
      }
    },
    // 父值集value
    parentVal: {
      type: String,
      default() {
        return '';
      }
    },
    size: {
      type: String,
      default: 'default'
    },
    placeholder: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    vindex: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dataList: [],
      dataMap: {}
    };
  },
  computed: {
    strValue() {
      if (this.value instanceof Array) {
        return this.value;
      } else {
        return '' + this.value;
      }
    },
    selItemName() {
      if (this.value != null && this.value != undefined && this.dataList && this.dataList.length) {
        const a = this.dataList.filter(item => item.value == this.value);
        return a[0] ? a[0].label : '';
      }
    }
  },
  watch: {
    datas: function(newVal, oldVal) {
      this.dataList = newVal;
    },
    dataList: function(newVal, oldVal) {
      this.dataMap = {};
      for (const item of this.dataList) {
        this.dataMap[item.value] = item.label;
      }
      this.loadFinish();
    },
    parentVal: function(newVal, oldVal) {
      this.$refs.select.clearSingleSelect();
      this.loadData();
    },
    value: function(newVal, oldVal) {
      this.$emit('input', newVal);
    }
  },
  created() {
    if (!sessionStorage.getItem('valueSet')) {
      sessionStorage.setItem('valueSet', JSON.stringify({}));
    }
  },
  mounted() {
    this.loadData();
  },
  methods: {
    handleInput(value) {
      this.$emit('input', value);
      this.$emit('dataSelectChange', value, this.dataMap[value]);
    },
    loadData() {
      const valueSet = JSON.parse(sessionStorage.getItem('valueSet'));
      const vkey = this.parentVal + '$' + this.code;
      if (!this.code) {
        this.dataList = this.datas;
      } else if (this.parentVal !== '' && this.parentVal !== null && this.parentVal !== undefined && this.code) {
        if (valueSet[vkey]) {
          this.dataList = valueSet[vkey];
          return;
        }
        // 解决多行并发请求
        if (this.vindex === 0) {
          QueryValueSetByCodeAndParentKey({
            parentKey: this.parentVal,
            code: this.code
          }).then(response => {
            if (response.statusCode !== '-1') {
              this.dataList = response;

              window.dispatchEvent(
                new CustomEvent(vkey, {
                  detail: {
                    data: this.dataList
                  }
                })
              );
            } else {
              this.$Message.error(this.$t('查询值集失败'));
            }
          });
        } else {
          const foo = e => {
            this.dataList = e.detail.data;
            window.removeEventListener(vkey, foo);
          };
          window.addEventListener(vkey, foo);
        }
      } else if (!this.parentVal && this.code) {
        if (valueSet[vkey]) {
          this.dataList = valueSet[vkey];
          return;
        }
        if (this.vindex === 0) {
          QueryValueSetByCode({
            code: this.code
          })
            .then(response => {
              if (response.statusCode !== '-1') {
                this.dataList = response;

                window.dispatchEvent(
                  new CustomEvent(vkey, {
                    detail: {
                      data: this.dataList
                    }
                  })
                );
              } else {
                this.dataList = [];
                this.$Message.error(this.$t('查询值集失败'));
              }
            })
            .catch(error => {
              this.dataList = [];
              this.$Message.error(error || this.$t('查询值集失败'));
            });
        } else {
          const foo = e => {
            this.dataList = e.detail.data;
            window.removeEventListener(vkey, foo);
          };
          window.addEventListener(vkey, foo);
        }
      }
    },
    loadFinish() {
      const valueSet = JSON.parse(sessionStorage.getItem('valueSet'));
      if (this.code && !(this.value instanceof Array) && !this.dataMap[this.strValue || '']) {
        this.$emit('input', '');
      }
      this.$emit('loadFinish', {
        valueList: this.dataList,
        valueMap: this.dataMap
      });
      if (this.dataList && this.dataList.length > 0) {
        valueSet[this.parentVal + '$' + this.code] = this.dataList;
        sessionStorage.setItem('valueSet', JSON.stringify(valueSet));
      }
    }
  }
};
</script>
