<template>
  <div class="xd-remote-cascader">
    <div class="xd-remote-cascader__tip">{{notice}}</div>
    <div class="xd-remote-cascader__tags">
      <el-tag
        v-for="(content,index) in remoteSelected"
        :key="content.name"
        :closable="!disabled"
        :disabled="disabled"
        @close="handleClose(index)"
        type="primary">{{content.label}}
      </el-tag>
    </div>
    <div class="xd-remote-cascader__select">
      <xd-cascade-select
        v-model="xdCascadeSelect"
        @loadChildren="handleChildren"
        :disabled="disabled"
      >
        <div class="xd-remote-cascader__select-add" v-if="!disabled" @click="handleAdd">
          <i class="el-icon-circle-plus"></i>
        </div>
      </xd-cascade-select>
    </div>
  </div>
</template>

<script>

  /**
   * @description 远程搜索进行添加数据操作
   * 文档：https://www.npmjs.com/package/gxd-helper
   *
   * @property {Array} defaultValue 设置默认选择值 （选填） 默认：null
   * @property {Boolean} multiple 搜索完成是否多选或者单选 （选填） 默认：false => 单选 true=> 多选
   * @property {Function} remoteSearch 搜索方法 （必填）
   * @property {String} placeholder 占位 （选填） 默认：请输入搜索关键字
   * @property {String} notice 操作提示文案 （选填） 默认：输入或选中操作后，请点击右侧"+"按钮进行添加操作
   * @property {Boolean} disabled 是否禁用 （选填） 默认：false
   */

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

  export default {
    name: "XdRemoteCascader",
    mixins: [emitter],
    components: {
      XdCascadeSelect
    },
    props: {
      defaultValue: {
        type: Array | null,
        default() {
          return null;
        }
      },
      remoteSearch: {
        type: Function,
        required: true
      },
      placeholder: {
        type: String,
        default: '请输入搜索关键字'
      },
      notice: {
        type: String,
        default: '输入或选中操作后，请点击右侧"+"按钮进行添加操作'
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      multiple: {
        type: Boolean,
        default: false,
      },
      required: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        isInit: false,
        xdCascadeSelect: {}, //用户选择对象
        remoteSelected: [], //选择的城市
        remoteSelectedSource: [], //当前选中数据
      }
    },

    created() {
      if (this.defaultValue !== null) {
        this.remoteSelected = this.defaultValue;
      }
      this.updateInput()
    },

    methods: {
      checkParams(){
        return this.remoteSelected
      },

      /**
       * @description 数据改变事件
       */
      change() {
        this.$emit('onChange', this.checkParams())
      },

      updateInput() {
        this.$emit('input', this.checkParams());
        if (this.$parent.$options['componentName'] === 'ElFormItem') {
          this.dispatch('ElFormItem', 'el.form.change', [this.checkParams()]);
          this.dispatch('ElFormItem', 'el.form.blur', [this.checkParams()])
        }
      },

      handleClose(index) {
        this.remoteSelected.splice(index, 1);
        this.updateInput()
      },

      checkRepeat(value) {
        console.log(value, this.remoteSelected);
        let temp = false;
        let name = '';
        let lenCont = this.remoteSelected.length;
        let val = JSON.stringify(value.selectValue);
        for (let i = 0; i < lenCont; i++) {
          let v = JSON.stringify(this.remoteSelected[i].value);
          if(v === val) {
            temp = true;
            name = value.name.join('/');
            break;
          }
        }

        if (temp) {
          this.$message({message: `添加的值【${name}】重复！`, type: 'error', duration: 2000});
        }

        return temp;
      },

      handleAdd() {
        if (this.disabled) {
          return;
        }

        if(!this.xdCascadeSelect || this.xdCascadeSelect.select.length === 0) {
          this.$message({message: `添加值不能为空！`, type: 'error', duration: 2000});
          return;
        }

        if(this.checkRepeat(this.xdCascadeSelect)) return;

        if(this.multiple) {
          this.remoteSelected.push({
            value: this.xdCascadeSelect.selectValue,
            label: this.xdCascadeSelect.name.join('/'),
            source: this.xdCascadeSelect
          });
          this.remoteSelectedSource.push(this.remoteSelected);
        }
        else {
          this.remoteSelected = [{
            value: this.xdCascadeSelect.selectValue,
            label: this.xdCascadeSelect.name.join('/'),
            source: this.xdCascadeSelect
          }];
          this.remoteSelectedSource = [this.remoteSelected]
        }
        this.updateInput();
      },

      handleChildren({level, select, item}, resolve){
        if (typeof this.remoteSearch === 'function') {
          this.remoteSearch({level, select, item}, (res) => {
            resolve(res);
            setTimeout(()=>{
              this.isInit = true;
            }, 400)

          })
        } else {
          throw new Error('请实现remoteSearch方法');
        }
      },

    }
  }
</script>

<style scoped lang="scss">
  .xd-remote-cascader {
    width: 100%;
    &__tip {
      color: #f56c6c;
      font-size: 14px;
      line-height: 16px;
      padding-bottom: 10px;
    }

    &__tags {
      & > * {
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }

    &__select {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      &-add {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 30px;
        height: 35px;
        flex-shrink: 0;
        overflow: hidden;


        & i {
          font-size: 25px;
          cursor: pointer;
          color: $blue;
        }
      }

    }
  }
</style>
