<template>
  <div class="xd-cascade-select" :class="{multiple: multiple}">
    <template v-for="(item,index) in cascadeList">
      <xd-select-list
        :key="item['refresh']"
        v-if="item['list'].length > 0"
        :default-value="item['selectValue']"
        :list="item['list']"
        :placeholder="item['placeholder']"
        :clearable="true"
        collapse-tags
        :disabled="disabled"
        v-model="item['selectValue']"
        :multiple="item['multiple']"
        class="xd-cascade-select__select"
        @change="(select)=>{handleChange(select,item,index)}"
        @clear="()=>{handleClear(index)}"
      ></xd-select-list>
    </template>
    <slot></slot>
  </div>
</template>

<script>

  import XdSelectList from "@/components/XdSelectList";
  import emitter from 'element-ui/src/mixins/emitter';

  export default {
    name: "XdCascadeSelect",
    mixins: [emitter],
    components: {
      XdSelectList
    },
    props:{
      defaultValue:{
        type:Array,
        default(){
          return []
        }
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      multiple:{
        type: Boolean,
        default: false,
      },
      inForm:{
        type: Boolean,
        default: false,
      },
      required: {
        type: Boolean,
        default: false,
      },
    },
    data(){
      return {
        isFirst: true,
        level: 0, //级别
        cascadeList:[], //所有级联插件数组列表
        cascadeValue:[], //存储选择列表值（不准确）
        hasChildren: true,

        /**
         * @description 级联基础数据
         */
        isEmptyCascade: {
          isChildren: null,
          level: 0,
          placeholder: '',
          selectValue: '',
          list: [],
        },
      }
    },

    watch:{
      cascadeList: {
        handler(value) {
          //初始化
          if(value.length === 1) {
            return;
          }

          let parentNode = [];
          let selectValue = [];
          let select = [];
          let name = [];
          value.map((item) => {
            if (item['selectValue']) {
              parentNode.push(item);
              selectValue.push(item['selectValue']);

              //是否为多选并且是否最后一层
              let multiple = false;
              if (this.multiple && !item.isChildren) multiple = true;
              if (multiple) {
                if(this.$xdHelper.checkVarType(item.selectValue) === 'string' && item.selectValue) select.push(item.selectValue);
                else {
                  select.push(item.selectValue.map(value => {
                    return item.list.filter(ls => {
                      return value === ls.value
                    })[0]
                  }))
                }
              } else {
                select.push(this.$xdHelper.isKeyInLists(item.list, item.selectValue, 'value'))
              }
            }
          });

          //设置名称
          name = select.map(item => {
            if(item) {
              if (this.$xdHelper.checkVarType(item) === 'object') return item.label;
              if (this.$xdHelper.checkVarType(item) === 'string') return item;
              return item.map(it => {
                return it.label
              })
            }

          })

          //未选中操作
          if (this.required || this.inForm) {
            selectValue = selectValue.filter(item=>{
              if (this.$xdHelper.checkVarType(item) ==='string' && item) return true;
              if (this.$xdHelper.checkVarType(item) === 'array' && item.length !== 0) return true;
              return false
            })

            if(selectValue.length !== value.length) {
              this.update(null);
              this.change(null);
              return;
            }
          }

          //返回数据
          this.update({parentNode, selectValue, select, name})
          this.change({parentNode, selectValue, select, name});
        },
        deep: true
      },
    },

    created(){
      this.cascadeValue = this.$xdHelper.cloneDeep(this.defaultValue);
      this.handleChange(null, null, 0)
    },

    methods:{
      update(data,index){
        this.$emit('input', data,index);
        if (this.$parent.$options['componentName'] === 'ElFormItem') {
          this.dispatch('ElFormItem', 'el.form.change', [data]);
          this.dispatch('ElFormItem', 'el.form.blur', [data])
        }
      },
      change(data,index){
        this.$emit('change', data,index);
      },
      handleClear(index){
        this.cascadeList = this.cascadeList.slice(0, index + 1);
        this.cascadeValue = this.cascadeValue.slice(0, index + 1);
      },

      handleChange(select, item, index){
        //清空操作(必选时候需要处理)
        if(this.required && select !== null && !select.value && select.select === null) {
          this.update(null,index);
          this.change(null,index);
          console.log('clear', select, item, index);
        }

        //设置默认值
        if (select !== null && select['value']) {
          this.cascadeValue[index] = select['value'];
        }

        //无子集列表不处理
        this.hasChildren = item && item['isChildren'] ? true: false;
        if(item !== null && (item['isChildren'] === false || item['selectValue'] === '')){
          return;
        }

        //清除当前操作选择对象之后的对象
        this.clearCascade(index);

        //设置级别
        let level = this.level;

        /**
         * @description 加载子集数据列表
         * @param level 级别
         * @param select 选中数据
         * @param item 级别对象数据
         */
        this.$emit('loadChildren',{level , select, item},
          /**
           * @description 返回数据
           * @param res 子集数据列表 [{"label": "万利达集团", "value": 1},{"label": "中国移动集团", "value": 2}]
           * @param isChildren 是否有子集列表
           */
          ({list, isChildren, placeholder, ...other})=>{
            if(list.length > 0) {
              this.cascadeList.push(this.getEmptyCascade(level, list, placeholder, isChildren, other));
              this.level++;
            }
          }
        )
      },

      clearCascade(index){
        if(this.cascadeList.length === 0) return;
        this.cascadeList = this.cascadeList.slice(0, index + 1);
        this.level = index + 1;

      },

      getEmptyCascade(level , list, placeholder, isChildren, other ){
        let multiple = false;
        if(this.multiple && !isChildren) multiple = true;
        let item = {...other, ...this.$xdHelper.cloneDeep(this.isEmptyCascade)};
        item['level'] = level;
        item['list'] = list;
        item['placeholder'] = placeholder;
        item['isChildren'] = isChildren;
        item['multiple'] = multiple;
        item['refresh'] = this.$xdHelper.randomChar(20);

        if(this.cascadeValue[level]) item['selectValue'] = this.cascadeValue[level];
        if(multiple && !item['selectValue']) item['selectValue'] = [];
        return item;
      }
    }
  }
</script>

<style scoped lang="scss">
  .xd-cascade-select {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    flex-wrap: wrap;
    width: 100%;

    &.multiple {
      .xd-cascade-select__select:last-child {
        min-width: 200px;
        max-width: 260px;
      }
    }

    &__select {
      margin-right: 10px;
      min-width: 120px;
      max-width: 200px;
      margin-bottom: 10px;
    }
  }

  @media screen and (max-width: 768px) {
    .xd-cascade-select {
      &__select {
        margin-right: 0;
        width: 100%;
        max-width: 100%;
        min-width: 100%;
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
</style>
