<template>
  <div class="lofty-search-suggestion"  v-out-click="outClick">
    <i class="lofty_iconfont lofty-icon-search"></i>
    <div class="lofty-input-tags" ref="tagsDom" @click="clickInput">
      <span v-show="hideCount" class="lofty-suggestion-tag">
        <span class="lofty-tag-text">{{ hideCount }} More</span>
      </span>
      <span v-for="(tag, index) in tags" v-show="(index+1) > hideCount" class="lofty-suggestion-tag">
        <span class="lofty-tag-text">{{ tag.value}}</span>
        <i class="lofty_iconfont lofty-icon-close" @click.stop="removeTag(tag)"></i>
      </span>
      <input v-show="showInput" v-model="searchWord" type="text" class="lofty-search-input" @input="getSuggestion"
             @keyup.enter="selectNoneValue"  ref="inputDom" :placeholder="placeholder">
    </div>
    <ul v-show="suggestList.length || loading" class="lofty-suggestion-list">
      <li v-show="loading" class="lofty-suggestion-loading">loading...</li>
      <li v-for="group in suggestList" :key="group.type" class="lofty-suggestion-type">{{group.typeText}}
        <li v-for="item in group.list" :key="item.value" class="lofty-suggestion-item" @click.stop="selectValue(group,item)"> {{item.label}}</li>
      </li>
    </ul>
  </div>
</template>

<script setup>
import util from "@/util";
import http from "@/api/index.js";
import directive from "@/common/directive/outsideclick.js";
const { config, modelValue, customTag = [] } = defineProps({
  config: Object,
  modelValue: Object,
  customTag: Array
})
const emits = defineEmits(["removeCustomTag"]);
const vOutClick = directive
let [searchWord, suggestList, showInput, loading] = [ref(''), reactive([]), ref(false), ref(false)]
const model = defineModel({ default: {} })
/** modelValue: {
 "city": ["Washington, DC"],
 "country": ["AA", "bb"],
 }
 **/
model.value = modelValue || {}
if(modelValue) {
  model.value = modelValue
  showInput.value = (Object.values(model.value).length === 0 && customTag.length === 0)
}
// input start
function selectValue(group, item) {
  if(customTag.length > 0) {
    emits('removeCustomTag')
  }
  const type = group.type || item.type // if recently， type in item
  if(!model.value[type]) {
    model.value[type] = [item.value]
  } else if(model.value[type].indexOf(item.value) === -1) {
    model.value[type].push(item.value)
  }
  setRecently(type, item)
  showInput.value = false
  closeSuggestion()
}
function selectNoneValue(e) {
  if(customTag.length > 0) {
    emits('removeCustomTag')
  }
  const type = 'none'
  if(!model.value[type]) {
    model.value[type] = [e.target.value]
  } else if(model.value[type].indexOf(e.target.value) === -1) {
    model.value[type].push(e.target.value)
  }
  showInput.value = false
  setTimeout(closeSuggestion, 2000)
}
const inputRef = useTemplateRef('inputDom')
function clickInput() {
  showInput.value = true
  nextTick(()=>{
    inputRef.value.focus()
  })
}
function outClick() {
  showInput.value = tags.value.length === 0
  closeSuggestion()
}
// input end

// tag start
const tags = computed(()=>{
  const res = []
  if(customTag.length > 0) {
    return customTag.map(item => {
      return {
        type: 'custom',
        value: item
      }
    })
  } else if(model.value) {
    for(let type in model.value) {
      model.value[type].forEach((value) => {
        res.push({ type, value})
      })
    }
  }
  return res
})
const tagRef = useTemplateRef('tagsDom')
const hideCount = ref(0)
const placeholder = computed(()=>{
  return tags.value.length > 0 ? 'Enter another region': 'Type city, neighborhood, school, etc'
})
watch(()=>tags.value.length, calcHideCount)
watch(()=>customTag, ()=>{
  setTimeout(()=>{
    showInput.value = false
  }, 200)
})
calcHideCount()
function calcHideCount() {
  hideCount.value = 0
  calcCount()
  function calcCount() {
    nextTick(() => {
      if (tagRef.value.scrollHeight > 60 && hideCount.value < tags.value.length - 1) {
        hideCount.value++;
        calcCount();
      }
    });
  }
}
function removeTag(tag) {
  if(tag.type === 'custom') {
    emits('removeCustomTag')
    model.value = {}
    return
  }
  model.value[tag.type].splice(model.value[tag.type].indexOf(tag.value), 1)
  if(model.value[tag.type].length === 0){
    delete model.value[tag.type]
    showInput.value = true
  } else {
    showInput.value = false
  }
}
// tag end

// suggestion start
const getSuggestion = util.debounce(async () => {
  if(!searchWord.value) {
    suggestList = []
    return
  }
  loading.value = true
  const data = { key: searchWord.value || '' }
  const res = await http.get(config.suggestionUrl, { data })
  suggestList = [getRecently()].concat(res).filter(item => item.list.length > 0)
  loading.value = false
}, 300)

const recentKey = computed(()=> `${config.name}_recently`)
function setRecently(type, item) {
  const result = getRecently();
  if (result.list.length > 2) {
    result.list.pop();
  }
  if(result.list.findIndex(t => t.value === item.value) === -1) {
    result.list.push({
      type: type,
      label: item.label,
      value: item.value
    })
  }
  util.setStorage(recentKey.value, result)
}

function getRecently() {
  return util.getStorage(recentKey.value) || {
    typeText: 'Recently Search',
    list: []
  }
}

function closeSuggestion() {
  searchWord.value = ''
  suggestList = []
}
</script>
<style lang="scss">
.lofty-search-suggestion {
  display: flex;
  border: 1px solid #dddddd;
  position: relative;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  transition: border-color .3s;
  &:hover {
    border-color: #111;
  }
  @include media-600 {
    min-height: 40px;
  }
  .lofty-icon-search {
    margin-left: 10px;
    color: #A8A8A8;
  }
  .lofty-input-tags {
    flex: 1;
    padding: 5px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 15px 5px;
    .lofty-search-input {
      border: none;
      outline: none!important;
      box-shadow: none;
      width: 100%;
      flex: 1;
      margin: 0;
      font-family: "font-regular";
      font-size: 16px;
      line-height: 20px;
      text-overflow: ellipsis;
      white-space: nowrap;
      padding: 0 5px;
      background: transparent;
      &::placeholder {
        color: #aaaaaa;
      }
      @include media-600 {
        font-size: 14px;
        height: 28px;
      }
    }
  }
  .lofty-suggestion-list {
    position: absolute;
    width: 100%;
    background-color: #fff;
    top: calc(100% + 10px);
    box-shadow: 0 4px 30px 0 rgba(0, 0, 0, 0.10);
    max-height: 300px;
    border: 1px solid #fff;
    overflow-y: auto;
    z-index: 10000;
    padding: 10px;
    margin: 0;
    .lofty-suggestion-loading {
      text-align: center;
      padding: 0 10px;
      font-size: 12px;
      font-weight: 400;
      line-height: 30px;
      color: #AAAAAA;
    }
    .lofty-suggestion-type {
      padding: 0 10px;
      font-size: 14px;
      font-weight: 600;
      line-height: 44px;
      font-family: "font-bold";
      .lofty-suggestion-item {
        padding: 0 10px;
        list-style: none;
        font-size: 14px;
        font-weight: 400;
        line-height: 44px;
        color: #111;
        cursor: pointer;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        &:hover {
          background: rgba(17, 17, 17, 0.05);
        }
      }
    }
  }
}
.lofty-suggestion-tag {
  height: 28px;
  cursor: pointer;
  white-space: nowrap;
  border: solid 1px #DADADA;
  font-size: 14px;
  color: #282828;
  display: inline-flex;
  justify-content: space-between;
  align-items: center;
  .lofty-tag-text {
    text-overflow: ellipsis;
    overflow: hidden;
    margin-left: 5px;
    margin-right: 10px;
    @include media-600 {
      max-width: 105px;
    }
  }
  .lofty-icon-close {
    width: 26px;
    height: 26px;
    color: #fff;
    background: #505050;
    text-align: center;
    line-height: 26px;
    font-size: 11px;
    &:hover {
      background: #111;
    }
  }
}
</style>