<template>
  <view class="aSelect-combox">
    <view v-if="label" class="aSelect-combox__label" :style="labelStyle">
      <text>{{label}}</text>
    </view>
    <view v-if="selections.length > 0" class="textBorder" style="margin-left: 4px;">{{itemSelections[0][labelName]}}
    </view>
    <uni-tooltip :content="selectionLabel()" placement="bottom">
      <view v-if="selections.length > 1" class="textBorder" style="margin-left: 6px;">+{{selections.length - 1}}</view>
    </uni-tooltip>
    <view class="aSelect-combox__input-box" style="margin-left: 6px;">
      <input class="aSelect-combox__input" type="text" :placeholder="placeholder"
        placeholder-class="aSelect-combox__input-plac" v-model="inputVal" @input="onInput" @focus="onFocus" />
      <!--    @blur="showSelector=false" -->
      <!-- <uni-icons v-if="selections && selections.length > 0" type="closeempty" style="padding-right: 16px;" size="16"
        color="#999" @click="clearSelections">
      </uni-icons> -->
      <uni-icons v-if="inputVal" type="closeempty" style="padding-right: 16px;" size="16" color="#999"
        @click="clearSelections">
      </uni-icons>
      <uni-icons :type="showSelector? 'top' : 'bottom'" size="14" color="#999">
      </uni-icons>
    </view>
    <view class="aSelect-combox__selector" v-if="showSelector">
      <scroll-view scroll-y="true" class="aSelect-combox__selector-scroll" refresher-enabled="true"
        @scrolltolower="scrollLower">
        <view class="aSelect-combox__selector-empty" v-if="filterOptionsLength === 0">
          <text>{{emptyTips}}</text>
        </view>
        <view class="aSelect-combox__selector-item" v-for="(item,index) in options" :key="index">
          <template v-if="(item.disabled ? true : false)">
            <text
              :style="'color:'+disabledColor+';cursor: not-allowed;'">{{item[labelName]?item[labelName]:'字段'+labelName+'不存在'}}</text>
          </template>
          <template v-else>
            <text style="padding-left: 15px;" @click="onSelectorClick(index)"
              :style="selections.includes(item[valueName]) ? 'background-color: '+selectedBackground :''">{{item[labelName] ? item[labelName]: '字段'+labelName+'不存在'}}</text>
            <uni-icons v-if="selections.includes(item[valueName])" @click="onSelectorClick(index)"
              style="text-align: right;padding-right: 15px;"
              :style=" selections.includes(item[valueName]) ? 'background-color: '+selectedBackground :''"
              type="checkmarkempty" size="20" color="#00b00a"></uni-icons>
          </template>
        </view>
      </scroll-view>
      <view class="" style="line-height: 36px; text-align: center;background-color: aliceblue; " @click="closeSelector">
        关闭</view>
    </view>
  </view>
</template>

<script>
  /**
   * Combox 组合输入框
   * @description 组合输入框一般用于既可以输入也可以选择的场景
   * @property {String} label 左侧文字
   * @property {String} labelWidth 左侧内容宽度
   * @property {String} placeholder 输入框占位符
   * @property {Array} options 候选项列表
   * @property {String} emptyTips 筛选结果为空时显示的文字
   * @property {String} selectedBackground 选中项背景颜色
   * @property {String} selectedColor 选中项文字颜色
   * @property {String} valueName value的key值
   * @property {String} labelName label的key值
   * @property {String} disabledColor 禁用项文字颜色
   */
  export default {
    name: 'wlSelectCombox',
    emits: ['onSelect'],
    props: {
      optUrl: {
        type: String,
        default: 'url'
      },
      disabledColor: {
        type: String,
        default: '#ababac'
      },
      valueName: {
        type: String,
        default: 'value'
      },
      labelName: {
        type: String,
        default: 'label'
      },
      selectedBackground: {
        type: String,
        default: '#f5f7fa'
      },
      selectedColor: {
        type: String,
        default: '#409eff'
      },
      border: {
        type: Boolean,
        default: true
      },
      label: {
        type: String,
        default: ''
      },
      labelWidth: {
        type: String,
        default: 'auto'
      },
      placeholder: {
        type: String,
        default: '请输入'
      },
      defaultSelection: {
        type: Array,
        default () {
          return []
        }
      },
      emptyTips: {
        type: String,
        default: '无匹配项'
      },
    },
    data() {
      return {
        time: null,
        pageConfig: {
          pageSize: 20,
          pageNum: 1,
          keyWord: '',
          totalCount: 0
        },
        selections: [],
        itemSelections: [],
        options: [],
        isInput: false,
        showSelector: false,
        isSelector: false,
        inputVal: ''
      }
    },
    computed: {
      labelStyle() {
        if (this.labelWidth === 'auto') {
          return ""
        }
        return `width: ${this.labelWidth}`
      },
      filterOptionsLength() {
        return this.options.length
      }
    },
    watch: {
      defaultSelection: {
        immediate: true,
        handler(val, old) {
          let arr = val ? val : []
          this.itemSelections = arr
          this.selections = arr.map(item => item[this.valueName])
        }
      },
    },
    mounted() {
      this.queryData(true)
    },
    methods: {
      selectionLabel() {
        return this.itemSelections.map(item => item[this.labelName]).join('\n')
      },
      scrollLower(e) {
        console.log('eeee', e)
        if (this.optUrl) {
          this.queryData(false)
        }

      },
      queryData(isRefresh) {
        var that = this;
        setTimeout(() => {
          let options = []
          for (let i = 0; i < this.pageConfig.pageSize; i++) {
            let number = Math.floor(Math.random() * 100)
            let obj = {}
            obj[this.labelName] = `${this.inputVal}随机数${number}`
            obj[this.valueName] = number
            options.push(obj)
          }
          if (isRefresh) {
            this.options = options //
          } else {
            this.options = [...this.options, ...options]
          }

        }, "500")

      },
      clearSelections() {
        this.selections = []
        this.itemSelections = []
        this.inputVal = ''
        this.onInput();
        this.$emit('onSelect', null);
      },
      closeSelector() {
        this.showSelector = false
        // this.inputVal = ''
        this.onInput()
      },
      onFocus() {
        this.showSelector = true
        this.isInput = false
      },
      onSelectorClick(index) {
        // debugger
        let item = this.options[index]
        // if (this.selections.includes(item[this.valueName])) {
        //   let index = this.selections.indexOf(item[this.valueName])
        //   this.selections.splice(index, 1)
        //   this.itemSelections.splice(index, 1)
        // } else {
        //   this.itemSelections.push(item)
        //   this.selections.push(item[this.valueName])
        // }
        // console.log('this.selections', this.selections)
        //this.inputVal = '';

        // this.$emit('onSelect', valueArr, selArr);
        this.inputVal = item.label;
        this.$emit('onSelect', item);

        this.showSelector = false
      },
      debounce(fn, delay) {
        if (this.time !== null) {
          clearTimeout(this.time)
        }
        this.time = setTimeout(() => {
          fn()
        }, delay)
      },
      onInput() {
        this.debounce(() => {
          this.queryData(true)
        }, 500);


      }
    }
  }
</script>

<style lang="scss" scoped>
  .textBorder {
    font-size: 12px;
    font-size: 12px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding: 0px 10px;

  }

  .aSelect-combox {
    font-size: 14px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding: 6px 10px;
    position: relative;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    // height: 40px;
    flex-direction: row;
    align-items: center;
    // border-bottom: solid 1px #DDDDDD;
  }

  .aSelect-combox__label {
    font-size: 16px;
    line-height: 24px;
    padding-right: 10px;
    color: #999999;
  }

  .aSelect-combox__input-box {
    position: relative;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex: 1;
    flex-direction: row;
    align-items: center;
    cursor: pointer;
  }

  .aSelect-combox__input {
    flex: 1;
    font-size: 14px;
    height: 24px;
    line-height: 24px;
  }

  .aSelect-combox__input-plac {
    font-size: 14px;
    color: #ccc;
  }

  .aSelect-combox__selector {
    /* #ifndef APP-NVUE */
    box-sizing: border-box;
    /* #endif */
    position: absolute;
    top: calc(100% + 12px);
    left: 0;
    width: 100%;
    background-color: #FFFFFF;
    border: 1px solid #EBEEF5;
    border-radius: 6px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 2;
    padding: 4px 0;
  }

  .aSelect-combox__selector-scroll {
    /* #ifndef APP-NVUE */
    max-height: 200px;
    box-sizing: border-box;
    /* #endif */
  }

  .aSelect-combox__selector-empty,
  .aSelect-combox__selector-item {
    /* #ifndef APP-NVUE */
    display: flex;
    cursor: pointer;
    /* #endif */
    line-height: 36px;
    font-size: 14px;
    text-align: left;
    padding: 0px 0px;
  }

  .aSelect-combox__selector-empty text,
  .aSelect-combox__selector-item text {
    width: 100%;
  }

  .aSelect-combox__selector-item:hover {
    background-color: #f9f9f9;
  }

  .aSelect-combox__selector-empty:last-child,
  .aSelect-combox__selector-item:last-child {
    /* #ifndef APP-NVUE */
    border-bottom: none;
    /* #endif */
  }

  ::v-deep .uni-tooltip-popup {
    z-index: 100;
    width: 80px;
    white-space: pre-wrap;
  }
</style>