<template>
    <div class="search-item">
        <el-popover
                placement="bottom"
                width="300"
                ref="popover"
                trigger="focus"
                :visible-arrow="false"
                style="padding-top: 0"
                v-model="visible"
                >
            <div class="search-content">
                <div class="search-his">
                    <div>
                        <span class="title">热搜榜</span>
<!--                        <span class="clear" @click="clearHistory" v-show="isShowClearHistory"><i class="el-icon-circle-close"></i>清空</span>-->
                    </div>
                    <div v-if="hotSearchKeyWords" v-for="(tag,index) in hotSearchKeyWords"
                         :key="index" v-show="isShowClearHistory">
                        <el-tag
                            :v-if="hotSearchKeyWords"
                            size="small"
                            style="margin-right: 10px; margin-top: 10px; cursor: pointer"
                            @click="handleSearch(tag)"
                        >
                            {{ tag }}
                        </el-tag>
                    </div>
                    <div v-if="!hotSearchKeyWords" v-show="isShowClearHistory">
                      <span  v-show="!searchResults" >暂无搜索结果...</span>
                    </div>
                    <div
                        v-show="!isShowClearHistory">
                        <span style="font-size: 15px">你还没有登录哦~</span>
                    </div>

                </div>
                <div class="search-his">
                    <div>
                        <span class="title">搜索历史</span>
<!--                        <span class="clear"  v-show="isShowClearHistory"><i class="el-icon-circle-close"></i>清空</span>-->
                    </div>
                    <div v-if="historySearch" v-show="isShowClearHistory">
                        <el-tag
                            :v-if="historySearch"
                            v-for="(tag,index) in historySearch"
                            :key="index"
                            size="small"
                            closable
                            @close="handleClose(tag)"
                            style="margin-right: 10px; margin-top: 10px; cursor: pointer"
                            @click="handleSearch(tag)"
                        >
                            {{ tag }}
                        </el-tag>
                    </div>
                    <div v-if="!historySearch" v-show="isShowClearHistory">
                      <span  v-show="!searchResults" >暂无搜索结果...</span>
                    </div>
                    <div
                        v-show="!isShowClearHistory">
                        <span style="color: var(--theme-color);font-size: 15px">你还没有登录哦~</span>
                    </div>

                </div>
                <div style="margin-top: 10px">
                    <div style="display: flex;flex-direction: row;justify-content: space-between">
                        <span class="title">搜索结果: {{searchResults.length}} 条</span>
                        <span class="clear" @click="clearSearchResults"><i class="el-icon-circle-close"></i>清空</span>
                    </div>
                    <div  style="max-height: 300px;overflow-y: scroll">
                        <el-scrollbar  v-show="searchResults">
                            <div  v-for="(item,index) in searchResults" :key="index">
                               <SearchResults :search-results="item"></SearchResults>
                            </div>
                        </el-scrollbar>
                        <span  v-show="!searchResults" >暂无搜索结果...</span>
                    </div>

                </div>
            </div>


        </el-popover>



        <el-input
                size="medium"
                :placeholder="tipsWord"
                style="width: 310px"
                clearable
                v-popover:popover
                @keyup.enter.native="searchByInput"
                v-model="search">
            <i slot="suffix" class="el-input__icon el-icon-search" style="cursor: pointer" @click="searchByInput"></i>
        </el-input>
    </div>
</template>


<script>
import axios from "axios";
import Vue from "vue";
import SearchResults from "@/components/home/SearchResults.vue";



export default {
    components: {SearchResults},
    data() {
        return {

            visible: false,
            isMouseOver: false,
            search: '',
            tipsWord: '',
            historySearch: [],
            searchResults:[],
            update:true,

            hotSearchKeyWords:[],

        }
    },

    methods: {
      isShowClearHistory(){
        return !!(localStorage.getItem('Authorization') && localStorage.getItem('userId'));
      },
        handleSearch(word) {
            this.search = word
            this.searchByInput()
        },
        clearSearchResults(){
          this.searchResults=[];
        },
        getHotSearchKeyWords() {
            var that=this;
            axios({
                method: 'post',
                // 请求的地址
                url: '/api/Search/getHotList',
                // URL 中的查询参数
                params: {
                  searchKey:this.search,
                }
            }).then((res)=>{
                if (res.data.code === 200) {
                  that.hotSearchKeyWords=res.data.data;

                } else {
                  return false;
                }
            }).catch((error)=>{

            })
        },
        // searchRequest() {
        //     const params = {
        //         word: this.search || this.tipsWord
        //     }
        //     const queryString = new URLSearchParams(params).toString();
        //     const url = `${window.location.origin}/video/search?${queryString}`;
        //     window.open(url, '_blank');
        // },
        gethistorySearch(){
            var that=this;
          if(localStorage.getItem('userId')&& localStorage.getItem('Authorization') ){
            axios({
              method: 'post',
              // 请求的地址
              url: '/api/Search/getSearchHistoryByUserId',
              // URL 中的查询参数
              params: {
                userId:localStorage.getItem('userId')
              }
            }).then((res)=>{
              if(res.data.code===200){
                that.historySearch=res.data.data;
              }else{
                return false;
              }


            }).catch((error)=>{

            })
          }else{
            Vue.prototype.$notify.info({
              title: '提示',
              message: ('i', {style: 'color: teal'}, "登录状态失效，请重新登录！"),
              offset: 50
            });
          }

        },
        handleClose(tag){
            var that=this;
          if(localStorage.getItem('userId')&& localStorage.getItem('Authorization') ){
            axios({
              method: 'post',
              // 请求的地址
              url: '/api/Search/delSearchHistoryByUserId',
              // URL 中的查询参数
              params: {
                searchKey:tag,
                userId:localStorage.getItem('userId')
              }
            }).then((res)=>{
              if(res.data.code===200){
                // Vue.prototype.$notify({
                //   title: '成功',
                //   message: ('i', {style: 'color: teal'}, "删除成功！"),
                //   type: 'success',
                //   offset: 50
                // });

                that.gethistorySearch();

              }else{
                Vue.prototype.$notify.error({
                  title: '错误',
                  message: "删除失败！",
                  offset: 50
                });
              }
            }).catch((error)=>{

            })
          }else{
            Vue.prototype.$notify.info({
              title: '提示',
              message: ('i', {style: 'color: teal'}, "登录状态失效，请重新登录！"),
              offset: 50
            });
          }


        },
        searchByInput(){
            var that=this;
            if(localStorage.getItem('userId')&& localStorage.getItem('Authorization') ){
              if(this.search!==''){
                axios({
                  method: 'post',
                  // 请求的地址
                  url: '/api/Search/searchByInput',
                  // URL 中的查询参数
                  params: {
                    searchKey:this.search,
                    userId:localStorage.getItem('userId')
                  }
                }).then((res)=>{
                  if(res.data.code!==200){
                    Vue.prototype.$notify.error({
                      title: '错误',
                      message: "查询失败！",
                      offset: 0
                    });
                    that.reload()
                  }else{
                    Vue.prototype.$notify({
                      title: '成功',
                      message: ('i', {style: 'color: teal'}, "查询成功"),
                      type:"success",
                      offset: 50
                    });
                    that.getHotSearchKeyWords();
                    that.searchResults=res.data.data;
                    setTimeout(() => {
                      that.visible = true;
                      that.gethistorySearch();
                    }, 200);
                  }
                }).catch((error)=>{
                  Vue.prototype.$notify.error({
                    title: '错误',
                    message: error,
                    offset: 50
                  });
                })
              }else{
                Vue.prototype.$notify.info({
                  title: '提示',
                  message: '请输入搜索内容',
                  offset: 50
                });
              }
            }else{
              Vue.prototype.$notify.info({
                title: '提示',
                message: "登录状态失效，请重新登录！",
                offset: 0
              });
            }



        },
        reload() {
            // 移除组件
            this.update = false
            // 在组件移除后，重新渲染组件
            // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
            this.$nextTick(() => {
                this.update = true
            })
        }
    },
    mounted() {
        this.tipsWord = "搜索书签";
        this.gethistorySearch();

    },

};
</script>

<style scoped>
.search-item ::v-deep .el-input .el-input__inner {
    border-radius: 8px !important;
}


.search-content span.title {
    display: inline-block;
    font-size: 15px;
    font-weight: bold;
}

.search-content .search-his span.clear {
    float: right;
    cursor: pointer;
}

.search-content .search-his span.clear:hover {
    color: #ec0014;
}
.clear{
    cursor: pointer;
}
.clear:hover{
    color: #ec0014;
}
.search-content .mt {
    margin-top: 10px;
}

.search-content .search-hot {
    width: 100%;
}

.search-content .search-hot ul.hot-list {
    width: 100%;
    display: flex;
    padding: 0;
    flex-wrap: wrap;
    margin-top: 5px;
    list-style: none;
}

.search-content .search-hot ul.hot-list li.hot-item {
    width: 50%;
    height: 30px;
    font-size: 15px;
    display: flex;
    cursor: pointer;
    align-items: center;
}

.search-content .search-hot ul.hot-list li.hot-item span:first-child {
    width: 10%;
    color: #999999;
    text-align: center;
    display: inline-block;
}

.search-content .search-hot ul.hot-list li.hot-item span:last-child {
    margin-left: 5px;
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.search-content .search-hot ul.hot-list li.hot-item span.top {
    color: #EA322BFF;
}

.search-content .search-hot ul.hot-list li.hot-item:hover {
    background-color: #f2f2f2;
}

</style>

