<template>
  <el-form-item
    :label="label"
    :rules="requireRule(required, label)"
    :prop="prop"
    :label-width="labelWidth"
    v-loadMore="handleScroll"
  >
    <el-tooltip v-if="showTip && !isBlank(formRef.model[prop])" placement="top">
      <div slot="content" >{{ initName }}</div>
      <span>
         <el-select
           ref="select2"
           v-model="formRef.model[prop]"
           :multiple="multiple"
           :multiple-limit="multipleLimit"
           collapse-tags
           :clearable="clearable"
           filterable
           :style="{width}"
           :disabled="disabled"
           @focus="focus"
           @change="handleChange()"
           :placeholder="placeholder"
           :popper-append-to-body="popperAppendToBody"
         >
      <el-option
        v-for="item in data"
        :key="item[`${valueProp}`]"
        :value="String(item[`${valueProp}`])"
        :label="item[`${labelProp}`]"
      />
      </el-select>
      </span>
    </el-tooltip>
    <el-select
      v-if="!showTip || isBlank(formRef.model[prop])"
      v-model="formRef.model[prop]"
      :multiple="multiple"
      :multiple-limit="multipleLimit"
      collapse-tags
      :clearable="clearable"
      filterable
      :disabled="disabled"
      :style="{width}"
      @focus="focus"
      @change="handleChange"
      :popper-append-to-body="popperAppendToBody"
      :filter-method="filterMethod"
      @visible-change="visibleChange"
      remote
      reserve-keyword
      ref="select1"
      :placeholder="placeholder"
    >
      <el-option
        v-for="(item,index) in data"
        :value="String(item[`${valueProp}`])"
        :label="formatLabel(item[`${labelProp}`],item)"
        :key="index"
      />
    </el-select>
  </el-form-item>
</template>
<script>
import mixin from "./mixin";
import {isBlank} from "../../../../utils";

export default {
  name: "PageSelect",
  mixins: [mixin],
  props: {
    multiple: {
      type: Boolean,
      default: false,
    },
    multipleLimit: {
      type: Number,
      default: 10,
    },
    labelWidth: {
      type: String
    },
    //允许新增新选项
    allowCreate:{
      type:Boolean,
      default:false
    },
    valueProp: {
      type: String,
      default: "value",
    },
    labelProp: {
      type: String,
      default: "label",
    },
    popperAppendToBody:{
      type: Boolean,
      default: true
    },
    showTip:{
      type: Boolean,
      default: false
    },
    setFirst:{
      type: Boolean,
      default: false
    },
    //分页获取下拉框的数据 必传
    list:{
      type: Function,
      required: true
    },
    //外部传入的其他查询参数
    defaultParams:{
      type: Object,
      default: () => {}
    },
    pageSize:{
      type: Number,
      default: 30
    },
    requiredParams:{
      type: Array,
      default: () => []
    },
    formatLabel: {
      type: Function,
      default: (label,item) => label
    },
    idName:{
      default: null
    },
    //下拉列表打开时，进行检索
    visibleGetData:{
      type: Boolean,
      default: false
    },
    needFirstSearch:{
      type: Boolean,
      default: true
    },
    //自定义label 并且允许创建 需要添加的属性
    createLabel:{
      type: String,
      default: ""
    },
    defaultData:{
      type: Array,
      default: () => []
    },
    selfTop:{
      type: Number,
      default: 0
    }
  },
  data(){
    return  {
      searchParams:{
        pageSize: this.pageSize,
        pageNum: 1
      },
      data:[],
      loading:false,
      firstSearch: true,
      canGetBottomData: true,
      total:0,
      isMounted: true,
      inputValue: null,
      choiceItem:[]
    }
  },
  methods:{
    isBlank,
    focus(){
      this.$emit('focus')
    },
    handleChange(vals){
      let res = undefined;
      this.defaultData.splice(0, this.defaultData.length);
      if(this.multiple){
        //设置最后一个id,并把他设置在choiceItem中
        // this.data.some(item=>{
            // if (item[this.valueProp] === vals[vals.length-1]){
            //   this.defaultData.push(item);
            // }
        //});
        //多选

        res = []
        this.data.some(item=>{
          vals.some(val=>{
            if (item[this.valueProp] == val){
              this.defaultData.push(item);
              res.push(item);
              return true
            }
          })
        });
      }else {
        res = {}
        this.data.some(item=>{
          if (item[this.valueProp] == vals){
            this.defaultData.push(item);
            res = item;
            return true
          }
        });
      }
      // if(!flag && !isBlank(val)){
      //   this.data.push({[this.valueProp]:val,[this.labelProp]:val})
      // }else{
      //   // this.$set(this.$parent,[this.prop],res[this.valueProp])
      //   this.inputValue = null
      // }
      this.$nextTick(()=>{
        this.$emit('change',res)
      })
    },
    handleScroll(val) {

      //初底加载debugger
      if(val == 'bottom') {
        this.getBottomData()
      }
    },
    //触底记载获取数据
    async getBottomData(){
      if(this.total <= this.data.length){
        return;
      }
      if(this.loading){
        return
      }
      this.searchParams = {...this.searchParams,...this.defaultParams}
      this.loading = true
      let query = JSON.parse(JSON.stringify(this.searchParams));
      query.pageNum++
      if(this.checkSearchParams()){
        return ;
      }
      const {code,rows,total} = await this.list(query)
      this.loading = false
      if( code == 200){
        this.total = total
        if(rows){
          const arr = rows.filter(item => item[this.labelProp] !== null && item[this.labelProp]  !== undefined)
          this.data.push(...arr);
        }
        this.searchParams.pageNum++
      }
    },
    //初始分页数据
    async getDefaultData(){

      this.searchParams = {...this.searchParams,...this.defaultParams}
      this.canGetBottomData = true
      this.searchParams.pageNum = 1
      this.$set(this.searchParams,[this.labelProp],null)
      const idName = !!this.idName ? this.idName : this.valueProp
      if(this.formRef.model[this.prop] != null
        && this.formRef.model[this.prop] != ''
        && this.formRef.model[this.prop] != null
        && !Object.is(Number(this.formRef.model[this.prop]),NaN)){
        this.$set(this.searchParams,[this.idName],this.formRef.model[this.prop])
      }else{
        this.$set(this.searchParams,[this.idName],null)
      }
      if(!this.isMounted && this.checkSearchParams()){
        return ;
      }
      const {code,rows,total} = await this.list(this.searchParams)
      if( code == 200){
        this.total = total
        const arr = rows.filter(item => item[this.labelProp] !== null && item[this.labelProp]  !== undefined)
        this.data = arr
      }
      if(code == 200 && rows.length > 0){
        this.firstSearch = false
      }
      this.$set(this.searchParams,[this.idName],null)
    },
    //远程检索方法
    async filterMethod(val) {
      this.inputValue = val
      if(!this.multiple && val !== this.formRef.model[this.prop]){
        this.$set(this.formRef.model,[this.prop],val)
      }
      this.$set(this.searchParams,[this.labelProp],val)
      if(this.checkSearchParams()){
        return ;
      }
      this.searchParams = {...this.searchParams,...this.defaultParams}
      this.searchParams.pageNum = 1
      const {code,rows,total} = await  this.list(this.searchParams)
      if( code == 200){
        this.total = total
        let arr = rows.filter(item => item[this.labelProp] !== null && item[this.labelProp]  !== undefined);

        //添加已选中数据
        let addList= []
        this.defaultData.some(item=>{
          let existFlag = false;
          arr.some(row=>{

            if(item[this.valueProp] == row[this.valueProp]){
              existFlag = true;
            }

          })
          //存在不加入
          if(!existFlag){
            addList.push(item)
          }
        });
        arr = arr.concat(addList)

        this.data = arr
        if(this.data === null || this.data === undefined || this.data.length === 0 && this.allowCreate){
          this.addData(val)
        }
      }else if(this.allowCreate){
        this.addData(val)
      }
    },
    addData(val){
      if(this.createLabel !== null){
        this.data.push({[this.valueProp]:val,[this.labelProp]:val,[this.createLabel]:''})
      }else{
        this.data.push({[this.valueProp]:val,[this.labelProp]:val})
      }
    },
    checkSearchParams(){
      if(this.requiredParams.length > 0) {
        for (let key of this.requiredParams) {
          if (isBlank(this.searchParams[key.value])) {
            this.$message.error(key.label + '不能为空')
            return true
          }
        }
      }
    },
    async getData(){
      this.searchParams = {...this.searchParams,...this.defaultParams}
      let {code,rows,total} = await this.list(this.searchParams)
      if( code == 200){
        let addList= []
        this.total = total;
        this.defaultData.some(item=>{
          let existFlag = false;
          rows.some(row=>{
            if(item[this.valueProp] == row[this.valueProp]){
              existFlag = true;
            }
          })
          //存在不加入
          if(!existFlag){
            addList.push(item)
          }
        });
        rows = addList.concat(rows)
        this.data = rows
        console.log("点击获取数据选项")
        this.resSet()
      }
    },
    resSet(){
      console.log("重置数据选项")
      if(this.multiple) {
        console.log("重设选项")
        this.formRef.model[this.prop] = []
      }else {
        this.formRef.model[this.prop] = ""
      }
      // this.$nextTick(()=>{
      //
      // })

      setTimeout(() => {
        // if(this.showTip){
        //   console.log("强制刷新选项2")
        //   this.$refs.select2.$forceUpdate;
        // }else {
        //   console.log("强制刷新选项1")
        //   this.$refs.select1.$forceUpdate;
        // }
        if(this.defaultData&&this.defaultData.length>0){
          if(this.multiple){
            this.formRef.model[this.prop] = this.defaultData.map(it=>it[this.valueProp]+"")
          }else {
            this.formRef.model[this.prop] = this.defaultData[0][this.valueProp]+""
          }
        }
      }, 0)

    },
    visibleChange(val){
      if(val && this.visibleGetData){
        this.$set(this.searchParams,"pageNum",1)
        this.getData()
      }
      //关闭下拉框 如果检索内容存在且绑定值不存在
      if(!val){
        //重置查询id为1
        //this.searchParams.pageNum = 1
        //赋值所有选中的item List
        this.data = JSON.parse(JSON.stringify(this.defaultData));
      }
      // //关闭下拉框 初始分页数据
      // if(!val){
      //   if(this.formRef.model[this.prop] == undefined){
      //     this.getDefaultData()
      //   }
      // }
    },
    blur(){
      this.$refs.select.blur()
    },

  },
  mounted() {
    if(this.firstSearch && this.needFirstSearch){
      if(this.defaultData&&this.defaultData.length>0){
        setTimeout(()=>{
          console.log("重置数据选项")
          this.data = this.defaultData;
          this.data.some(it=>{
            it[this.valueProp] = it[this.valueProp]+""
          });
          if(this.multiple){
            this.formRef.model[this.prop] = this.data.map(it=>it[this.valueProp])
          }
          if(this.showTip){
            this.$refs.select2.$forceUpdate;
          }else {
            this.$refs.select1.$forceUpdate;
          }
        },500)
      }else {
        this.getDefaultData().then(()=>{
          this.isMounted = false
        })
      }
    }

  },
  computed:{
    initName() {
      let arr = this.formRef.model[this.prop]
      if (arr == null || arr == undefined) {
        return ""
      }
      let arr1 = []
      if (this.multiple) {
        this.data.forEach(item =>{
          let name = arr.includes(item[this.valueProp]) ?  item[this.labelProp] : ""
          if (!isBlank(name)) {
            arr1.push(name)
          }
        })
      } else {
        let data = this.data[this.valueProp];
        if (!isBlank(data)) {
          arr1.push(data)
        }
      }
      return arr1.join(",")
    },
  },
  directives: {
    loadMore: {
      bind(el, binding) {
        const select_dom  = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        select_dom.addEventListener('scroll', function () {
          console.log("scrollHeight: "+ this.scrollHeight)
          console.log("scrollTop: "+ this.scrollTop)
          console.log( "clientHeight: "+this.clientHeight)

          // const bottom = this.scrollHeight - this.scrollTop < (this.clientHeight + 1)
          const bottom =  Math.abs(this.scrollHeight - this.scrollTop - this.clientHeight)<= 1
          const top = this.scrollTop == 0
          if (bottom) {
            binding.value('bottom')
          }
          if(top) {
            binding.value('top')
          }
        })
      }
    }
  },
  watch:{

    defaultData: {
      handler(val) {
        const _this = this;
        if (val&&val.length>0) {
          this.$nextTick(function () {
            if(!_this.data || _this.data.length == 0){
              _this.data = val
            }
            _this.resSet();
          });
        } else {
          //
        }
      },
      immediate: true,
    },


   //  defaultData: function defaultData(val) {
   //    var _this = this;
   //    if (val&&val.length>0) {
   //      this.$nextTick(function () {
   //        if(!_this.data || _this.data.length == 0){
   //          _this.data = val
   //        }
   //        _this.resSet();
   //      });
   //    } else {
   // //
   //    }
   //  },
  }
}
</script>

<style scoped>

</style>
