<template>
  <view class="cv-picker">
    <picker
      class="cv-picker-item"
      mode="multiSelector"
      :range="range_data"
      range-key="text"
      :value="items_index"
      @change="bindPickerChange"
      @columnchange="bindPickerColumnchange"
      @cancel="onCancel"
      @click="changeIconTop"
    >
      <view
        class="cv-picker-item-text"
        v-if="last_range_data[0] && lastRetDataIndex[0] && last_range_data[1] && lastRetDataIndex[1]"
      >
        {{ last_range_data[0][lastRetDataIndex[0]].text }}{{ joint || ' ' }}{{ last_range_data[1][lastRetDataIndex[1]].text }}
      </view>
      <view class="cv-picker-item-placeholder" v-else>{{ placeholder }}</view>
    </picker>
  </view>
</template>
<script>
import mpMixin from '../../libs/mixin/mpMixin.js';
import mixin from '../../libs/mixin/mixin.js';
export default {
  mixins: [mpMixin, mixin],
  name: 'cvPicker2',
  emits: ['input', 'update:modelValue'],
  props: {
    value: {
      type: [Array],
      default: () => []
    },
    modelValue: {
      type: [Array],
      default: () => []
    },
    dataType: {
      type: String,
      default: 'value'
    },
    //选项数组
    dataLists: {
      type: [Array, String],
      default: []
    },
    //数据类型value的名称
    dataValue: {
      type: String,
      default: 'value'
    },
    //数据类型text的名称
    dataText: {
      type: String,
      default: 'text'
    },
    dataTree: {
      type: String,
      default: 'tree'
    },
    joint: {
      type: String,
      default: ''
    },
    // 占位符
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  watch: {
    dataLists: {
      handler(newValue) {
        this.itemsSortOut();
      },
      deep: true
    },
    value(newVal) {
      this.localVal = newVal;
      this.itemsSortOut();
    },
    modelValue(newVal) {
      this.localVal = newVal;
      this.itemsSortOut();
    }
  },
  data() {
    return {
      iconTop: false,
      localVal: [],
      items: [], //全部数据
      range_data: [], //弹窗临时数组
      last_range_data: [], //最终显示页面数组
      items_sub: [],
      items_index: [0, 0], //当前下标
      lastRetDataIndex: [0, 0], // 最终确定选中的下标
      localDataType: 'value',
      localDataValue: 'value',
      localDataText: 'label'
    };
  },
  created() {
    this.localVal = this.doValueGet();
    this.localDataType = this.dataType != 'text' ? 'value' : 'text';
    this.itemsSortOut();
  },
  methods: {
    doValueGet() {
      if (this.value === '' || (Array.prototype.isPrototypeOf(this.value) && this.value.length === 0)) {
        return this.modelValue.length != 2 ? [0, 0] : this.modelValue;
      }
      if (this.modelValue === '' || (Array.prototype.isPrototypeOf(this.modelValue) && this.modelValue.length === 0)) {
        return this.value.length != 2 ? [0, 0] : this.value;
      }
      return this.value.length != 2 ? [0, 0] : this.value;
    },
    itemsSortOut() {
      let original = [];
      original = this.dataLists || [];

      if (typeof original == 'string') {
        original = JSON.parse(original);
      }
      if (!original || original.length <= 0) {
        console.warn('original 暂无数据', original);
        return;
      }
      //整理数据
      let items = [];
      let dataValue = this.dataValue ? this.dataValue : 'value';
      let dataText = this.dataText ? this.dataText : 'text';

      let tree = this.dataTree;
      let items_index = this.items_index;
      let dataType = this.localDataType;
      for (let i in original) {
        let data = original[i];
        //查找一级绑定参数
        if (this.localVal && this.localVal.length >= 1) {
          if (dataType == 'text' && this.localVal[0] == data[dataText]) {
            items_index[0] = i;
          } else if (dataType == 'value' && this.localVal[0] == data[dataValue]) {
            items_index[0] = i;
          }
        }

        items.push({
          value: data[dataValue].toString(),
          text: data[dataText]
        });
        if (original[i][tree]) {
          let tree_data = original[i][tree];
          let temp = [];
          for (const ii in tree_data) {
            let data = tree_data[ii];

            //查找二级绑定参数
            if (this.localVal && this.localVal.length >= 2) {
              if (dataType == 'text' && this.localVal[1] == data[dataText]) {
                items_index[1] = ii;
              } else if (dataType == 'value' && this.localVal[1] == data[dataValue]) {
                items_index[1] = ii;
              }
            }
            temp.push({
              value: data[dataValue].toString(),
              text: data[dataText]
            });
          }
          items[i].tree = temp;
        }
      }
      if (!items) {
        return;
      }
      //默认Value
      this.items = items;
      this.items_sub = items[items_index[0] ?? 0].tree;
      this.range_data = [items, this.items_sub];
      this.last_range_data = [...this.range_data];
      this.items_index = items_index;
      if (this.localVal && this.localVal.length == 2) {
        this.lastRetDataIndex = [...this.items_index];
      }
    },
    bindPickerChange: function (e) {
      let items_index = e.detail.value;
      this.items_index = items_index;
      this.updateLocalVal();
      this.iconTop = false;
    },
    changeIconTop() {
      this.iconTop = true;
    },
    /* 取消选择 */
    onCancel(e) {
      this.iconTop = false;
      this.range_data = [...this.last_range_data];
      this.items_index = [...this.lastRetDataIndex];
    },
    bindPickerColumnchange: function (e) {
      let items_index = this.items_index;
      if (e.detail.column == 1) {
        items_index[1] = e.detail.value;
      } else if (e.detail.column == 0) {
        items_index[0] = e.detail.value;
        items_index[1] = 0;
        let range_data = this.range_data;
        range_data[1] = range_data[0][items_index[0]].tree;
        this.range_data = range_data;
      }
      this.items_index = items_index;
      this.$forceUpdate();
    },
    updateLocalVal() {
      let items_index = this.items_index;
      this.last_range_data = [...this.range_data];
      this.lastRetDataIndex = [...items_index];
      let value = [];
      let items = this.items;
      if (this.dataType == 'text') {
        value[0] = items[items_index[0]].text;
        value[1] = items[items_index[0]].tree[items_index[1]].text;
      } else {
        value[0] = items[items_index[0]].value;
        value[1] = items[items_index[0]].tree[items_index[1]].value;
      }
      this.localVal = value;
      this.$emit('input', value);
      this.$emit('update:modelValue', value);
    }
  }
};
</script>

<style>
.cv-picker {
  min-height: 35px;
  display: flex;
  flex: 1;
}
.cv-picker-item {
  height: 35px;
  line-height: 35px;
  float: left;
  margin-right: 10px;
  width: 100%;
  font-size: 15px;
}
.cv-picker-item-placeholder {
  color: grey;
}
</style>
