<template>
  <div class="xd-remote-input" :class="{mode:mode}" v-if="isInit">
    <div class="xd-remote-input__tag" v-if="mode && remoteSelected.length >0">
      <div v-show="0">已选中:</div>
      <div class="tags">
        <el-tag
          @close="remove(tag)"
          :closable="!disabled"
          v-for="tag in remoteSelected"
          :key="tag.value"
        >{{tag.label}}</el-tag>
      </div>
    </div>
    <div class="xd-remote-input__select">
      <el-select
        class="input100"
        v-model="remoteValue"
        filterable
        remote
        clearable
        :disabled="disabled"
        reserve-keyword
        :placeholder="placeholder"
        :remote-method="remoteMethod"
        :loading="loading"
        :multiple="multiple"
        :collapse-tags="mode"
        @change="handleChange"
      >
        <el-option
          :class="{initSelect: item.selected}"
          v-for="item in remoteListLoad"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
        <div class="no-data" v-if="isEmpty">请输入查询关键字</div>
        <div class="no-data" v-if="remoteOrgList.length === 0 && remoteSelectedEmpty && query">暂无数据</div>
      </el-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 XdFontIcon from "@/components/XdFontIcon";
  import emitter from 'element-ui/src/mixins/emitter';

  export default {
    name: "XdRemoteInput",
    components:{
      XdFontIcon
    },
    mixins: [
      emitter
    ],
    props:{
      defaultValue: {
        type: Array|null,
        default(){
          return null;
        }
      },

      width: {
        type: String,
        default: '400px'
      },

      multiple: {
        type: Boolean,
        default: false,
      },

      remoteSearch: {
        type: Function,
        required: true
      },

      placeholder:{
        type:String,
        default: '请输入搜索关键字'
      },

      disabled:{
        type: Boolean,
        default: false,
      },

      collapseTags: {
        type: Boolean,
        default: false,
      },

      mode: {
        type: Boolean,
        default: false, //false => 老模式  true=>新模式
      }
    },
    data(){
      return {
        lists: [],
        loading: false,

        remoteValue: '', //
        isEmpty: false,
        remoteOrgList: [],
        remoteSelectedEmpty: false,
        query: '',
        isInit : false,
        timeInput: null,
        remoteList: [],

        remoteSelected: [],
      }
    },


    computed:{
      remoteListLoad(){
        if(this.mode) {
          if (this.query === '') return []
          return this.remoteList.filter(item => {
            let key = this.query.toLocaleUpperCase();
            let label = item.label.toLocaleUpperCase();
            return label.indexOf(key) !== -1;
          });
        }
        return this.remoteList;

      },
    },

    created(){
      if(this.defaultValue !== null && !this.$xdHelper.isEmpty(this.defaultValue)) {
        let remoteValue = this.defaultValue.map(item=>{
          return item.value
        });

        if (this.multiple) this.remoteValue = remoteValue;
        else this.remoteValue = remoteValue[0];

        //设置选择状态
        this.remoteList = this.remoteList.concat(this.$xdHelper.cloneDeep(this.defaultValue));
        this.remoteSelected = this.remoteSelected.concat(this.$xdHelper.cloneDeep(this.defaultValue));

      }
      else{
        if (this.multiple) this.remoteValue = [];
        else this.remoteValue = '';
      }

      this.isInit = true;
      this.updateInput();
    },

    methods:{
      remove(item){
        let remoteValue = this.remoteValue || [];
        let newRemoteValue =  remoteValue.filter(it=>{
          return item.value !== it;
        });
        this.remoteValue = newRemoteValue;
        this.handleAdd()
      },


      handleChange(){
        this.handleAdd();
      },

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

      remoteMethod(query){
        query = this.$xdHelper.tirm(query);
        this.query = query;
        if (!query) {
          this.remoteList = [].concat(this.remoteSelected);
          return;
        }
        if (this.timeInput) clearTimeout(this.timeInput);
        this.timeInput = setTimeout(() => {
          this.loading = true;
          if(typeof this.remoteSearch === 'function') {
            this.remoteSearch(query, (res)=>{
              this.remoteOrgList = this.$xdHelper.cloneDeep(res);
              //搜索结果返回空数组
              if(res.length === 0) {
                this.remoteList = this.$xdHelper.cloneDeep(this.remoteSelected);
                this.loading = false;
                return;
              }

              //判断当前选择对象是否在返回列表中
              let temp = [];
              let newSelect = [];
              res.map(item=>{
                let it = this.$xdHelper.isKeyInLists(this.remoteSelected, item.value, 'value');
                if(it === null) temp.push(item);
                else newSelect.push(item)
              });
              if(newSelect.length > 0) {
                this.remoteSelected = this.remoteSelected.map(item=>{
                  let temp = JSON.parse(JSON.stringify(item));
                  let t = newSelect.filter(it=>{
                    return it.value === item.value
                  });
                  if(t.length === 1){
                    //t[0].label = t[0].label + '.test';
                    temp = JSON.parse(JSON.stringify(t[0]));
                  }
                  return temp
                });
              }
              this.remoteList = this.$xdHelper.cloneDeep(temp).concat(this.remoteSelected);
              this.loading = false;
            })
          }
          else {
            throw new Error('请实现remoteSearch方法');
          }
        });
      },

      handleAdd(){
        if(this.disabled) {
          return;
        }
        let value = [this.remoteValue];
        if (this.multiple) value = this.remoteValue;
        this.remoteSelected  = this.$xdHelper.getValuesForList(this.remoteList, value, 'value');
        this.updateInput();
      },
    }
  }
</script>

<style scoped lang="scss">
  .xd-remote-input {

    &.mode {
      padding: 5px;
      border-radius: 4px;
      border: 1px solid #eee;
    }


    & > * {
      flex-shrink: 0;
      width: 100%;
    }

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

    &__tag {
      padding-bottom: 10px;
      & > *:first-child {
        line-height: 20px;
      }
      & > .tags{
        & >  * {
          margin-right: 10px;
        }
      }
    }

  }

  .no-data {
    font-size: 14px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    color: #999;
  }

  .mode ::v-deep {
    .el-select__tags > span {
      & > *:first-child {
        display: none
      }

    }
  }



  @media screen and (max-width: 768px) {
    .xd-remote-input {
      width: 100%!important;

      &__select {
        width: 100% !important;
      }
    }
  }
</style>
