<template>
  <Select
    ref="select"
    v-bind="$attrs"
    :value="strValue"
    :parentVal="parentVal"
    :code="code"
    v-on="$listeners"
    @input="handleInput"
  >
    <Option
      v-for="(item,index) in dataList"
      :key="item.value+item.label+index"
      :value="item.value"
    >
      {{ item.label }}
    </Option>
  </Select>
</template>
<script>
/**
 * 反显值集信息下拉框组件
 * 该组件需要返回数据严格为：[{label: 'xxx', value: 'xxx'}]格式
 * 其它props和event请参考iview select组件
 */
// import Server from "./server.js";
import { QueryValueSetByCodeAndParentKey, QueryValueSetByCode } from '../server.js';
// const server = new Server();
export default {
  name: 'DataSelectV',
  components: {},
  directives: {},
  props: {
    value: {
      type: [String, Array, Number],
      default() {
        return '';
      }
    },
    datas: {
      type: Array,
      default() {
        return [];
      }
    },
    // 值集code
    code: {
      type: String,
      default() {
        return '';
      }
    },
    // 父值集value
    parentVal: {
      type: [String, Number],
      default() {
        return '';
      }
    },
    filterValue: {
      type: Array,
      default() {
        return [];
      }
    },
    // 只显示配置的值
    someValue: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      // server: server,
      dataList: [],
      dataMap: {}
    };
  },
  computed: {
    strValue() {
      if (this.value instanceof Array) {
        return this.value;
      } else {
        return '' + this.value;
      }
    }
  },
  watch: {
    datas: function(newVal, oldVal) {
      this.dataList = newVal;
    },
    dataList: function(newVal, oldVal) {
      this.dataMap = {};
      if (this.dataList && this.dataList.length) {
        for (const item of this.dataList) {
          this.dataMap[item.value] = item.label;
        }
      }

      this.loadFinish();
    },
    someValue: function(newVal, oldVal) {
      if (newVal.length == oldVal.length) {
        return;
      }
      this.loadData();
    },
    parentVal: function(newVal, oldVal) {
      this.$refs.select.clearSingleSelect();
      this.loadData();
    },
    value: function(newVal, oldVal) {
      this.$emit('input', newVal);
    }
  },
  created: function() {
    if (!sessionStorage.getItem('valueSet')) {
      sessionStorage.setItem('valueSet', JSON.stringify({}));
    }
  },
  beforeMount: function() {},
  mounted: function() {
    this.loadData();
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    handleInput(value) {
      this.$emit('input', value);
      this.$emit('dataSelectChange', value, this.dataMap[value]);
    },
    loadData() {
      const valueSet = JSON.parse(sessionStorage.getItem('valueSet'));
      if (this.datas.length) {
        this.dataList = this.datas;
      } else {
        if (!this.code) {
          return console.warn('通过接口查询值集时code为必须');
        }

        if (this.filterValue.length && this.someValue.length) {
          return console.error('filterValue和someValue只能设置其中一个，不能同时设置');
        }

        const vkey = this.parentVal + '$' + this.code;
        const fkey = this.parentVal + '$' + this.code + this.filterValue.join('-');
        const skey = this.parentVal + '$' + this.code + this.someValue.join('-');

        if (!this.filterValue.length && !this.someValue.length && valueSet[vkey]) {
          this.dataList = valueSet[vkey];
          return;
        }

        if (this.filterValue.length && valueSet[fkey]) {
          this.dataList = valueSet[fkey];
          this.filterOptions();
          return;
        }

        if (this.someValue.length && valueSet[skey]) {
          this.dataList = valueSet[skey];
          this.setSomeValue();
          return;
        }

        if (this.parentVal) {
          QueryValueSetByCodeAndParentKey({
            parentKey: this.parentVal,
            code: this.code
          }).then(response => {
            if (response.statusCode != '-1') {
              this.dataList = response;
              this.filterOptions();
              this.setSomeValue();
            } else {
              this.$Message.error('查询值集失败');
            }
          });
        } else {
          QueryValueSetByCode({
            code: this.code
          }).then(response => {
            if (response.statusCode != '-1') {
              this.dataList = response;
              this.filterOptions();
              this.setSomeValue();
            } else {
              this.$Message.error('查询值集失败');
            }
          });
        }
      }
    },
    loadFinish() {
      const valueSet = JSON.parse(sessionStorage.getItem('valueSet'));
      this.$emit('loadFinish', {
        valueList: this.dataList,
        valueMap: this.dataMap
      });
      if (this.dataList && this.dataList.length > 0) {
        valueSet[
          this.parentVal + '$' + this.code + this.filterValue.join('-') + this.someValue.join('-')
        ] = this.dataList;
        sessionStorage.setItem('valueSet', JSON.stringify(valueSet));
      }
    },
    filterOptions() {
      if (this.filterValue.length != 0) {
        // console.log(this.dataList);
        for (let i = 0; i < this.filterValue.length; i++) {
          for (let j = 0; j < this.dataList.length; j++) {
            if (this.filterValue[i] == this.dataList[j].value) {
              this.dataList.splice(j, 1);
              break;
            }
          }
        }
      }
    },
    setSomeValue() {
      const sv = [];
      if (this.someValue.length != 0) {
        for (let i = 0; i < this.someValue.length; i++) {
          for (let j = 0; j < this.dataList.length; j++) {
            if (this.someValue[i] == this.dataList[j].value) {
              sv.push(this.dataList[j]);
              break;
            }
          }
        }
        this.dataList = sv;
      }
    }
  }
};
</script>
