<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">
      <label v-for="tag in tags" class="lofty-suggestion-tag">
        <span class="lofty-tag-text">{{ tag.value}}</span>
        <i class="lofty_iconfont lofty-icon-close" @click.stop="removeTag(tag)"></i>
      </label>
      <input v-show="showInput" v-model="searchWord" type="text" class="lofty-search-input" @input="getSuggestion"
             ref="inputDom">
    </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 || group.type}}
        <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 { ref } from 'vue';
import util from "@/util/index.js";
import http from "@/api/index.js";
import directive from "@/common/directive/outsideclick.js";

const props = defineProps({
  config: {
    type: Object,
    default: ()=> ({})
  },
  initialCondition: {
    type: Object,
    default: ()=> ({})
  }
});
const { config } = props;

const emit=defineEmits(['update:condition']);
const condition=ref({...props.initialCondition}) // condition.value as modelValue

watch(()=>{
  return props.initialCondition
}, (newVal)=>{
  condition.value = {...newVal};
});


const vOutClick = directive

let [searchWord, suggestList, showInput, loading] = [ref(''), ref([]), ref(false), ref(false)]

showInput.value=Object.values(condition.value).length === 0

const updateCondition = newVal => {
  emit('update:condition', newVal)
}

// input start
function selectValue(group, item) {
  const type = group.type || item.type // if recently， type in item
  if(!condition.value[type]) {
    condition.value[type] = [item.value]
    updateCondition(condition.value)
  } else if(condition.value[type].indexOf(item.value) === -1) {
    condition.value[type].push(item.value)
    updateCondition(condition.value)
  }
  setRecently(group, item)
  showInput.value = false
  closeSuggestion()
}

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 = []
  // const raw=toRaw(condition)
  const raw={...condition.value};
  for(let type in raw) {
    if(type === 'mapPath'){
      res.push({ type:'Custom Boundary', value: 'Custom Boundary' });
      continue;
    }
    if(Object.prototype.hasOwnProperty.call(raw, type) && Array.isArray(raw[type])){
      raw[type].forEach((value) => {
        res.push({ type, value})
      })
    }
  }
  return res
})

function removeTag(tag) {
  if(tag.type === 'Custom Boundary'){
    delete condition.value.mapPath;
    updateCondition(condition.value);
    return;
  }
  const tags=condition.value[tag.type]
  tags.splice(tags.indexOf(tag.value), 1)
  if(tags.length === 0){
    delete condition.value[tag.type]
    showInput.value = true
  } else {
    showInput.value = false
  }
  updateCondition(condition.value)
}
// tag end

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

const recentKey = computed(()=> `${config.name}_recently`)
function setRecently(group, 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: group.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.value = []
}
</script>

<style lang="scss" scoped>
.lofty-search-suggestion {
  display: flex;
  border: 1px solid $gray-600;
  border-radius: $radius-small;
  position: relative;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  transition: border-color .3s;
  min-height: 40px;
  padding: 2px 12px;
  &:hover {
    border-color: $color-theme;
  }
  @include media-600 {
    min-height: 40px;
  }
  .lofty-icon-search {
    color: #A8A8A8;
  }
  .lofty-input-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
    flex: 1;
    padding: 0 5px;
    .lofty-search-input {
      border: none;
      outline: 0;
      width: 100%;
      flex: 1;
      height: 33px;
      margin: 0;
      font-family: inherit;
      font-size: inherit;
      line-height: inherit;
      background: inherit;
      text-overflow: ellipsis;
      white-space: nowrap;
      padding: 0 5px;
      @include media-600 {
        font-size: 14px;
        height: 28px;
      }
      &:focus{
        border: none!important;
        outline: none!important;
        box-shadow: none;
      }
    }
    .lofty-search-input:focus:focus-visible {
      outline: none!important;
      border: none !important;
    }
  }
  .lofty-suggestion-list {
    position: absolute;
    width: calc(100% - 20px);
    background-color: #fff;
    top: calc(100% + 10px);
    left: 0;
    box-shadow: 0 4px 30px 0 rgba(0, 0, 0, 0.10);
    max-height: 300px;
    border: 1px solid #fff;
    overflow-y: auto;
    z-index: 1;
    padding: 10px;
    .lofty-suggestion-loading {
      text-align: center;
      padding: 0 10px;
      font-size: 16px;
      font-weight: 400;
      line-height: 30px;
    }
    .lofty-suggestion-type {
      padding: 0 10px;
      font-size: 14px;
      font-weight: 600;
      line-height: 40px;
      .lofty-suggestion-item {
        padding: 0 10px;
        list-style: none;
        font-size: 14px;
        font-weight: 400;
        line-height: 40px;
        color: #111;
        cursor: pointer;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        &:hover {
          background: rgba(17, 17, 17, 0.05);
        }
      }
    }
  }
}
.lofty-suggestion-tag {
  cursor: pointer;
  white-space: nowrap;
  display: inline-flex;
  justify-content: space-between;
  align-items: center;
  column-gap: 8px;
  background-color: $color-theme-alpha-04;
  color: $color-theme;
  padding: 4px 8px;
  .lofty-tag-text {
    text-overflow: ellipsis;
    overflow: hidden;
    line-height: 20px;
  }
  .lofty-icon-close {
    font-size: 10px;
  }
}
</style>