<template>
    <div class="q-pa-md rounded search-area" style="display: inline-block;" :class="{'search-range-box':isSearchFocus}" @keypress.enter="searchHandler" v-click-outside="()=>isSearchFocus=false"><!-- v-click-outside="()=>isSearchFocus=false" -->
        <el-input size="large" @focus="()=>isSearchFocus=true" v-model="searchKey" placeholder="搜索行程，广告，分享文件" style="width: 38vw;">
            <template #prefix>
                <el-icon><Search style="color:var(--el-color-primary);"/></el-icon>
            </template>
        </el-input>
        <div v-if="isSearchFocus">
            <el-tabs v-model="searchType" class="q-mt-md q-mx-md" @tab-change="()=>changeSearchType()">
                <el-tab-pane label="全部" name="0"></el-tab-pane>
                <el-tab-pane label="行程" name="1"></el-tab-pane>
                <el-tab-pane label="广告" name="2"></el-tab-pane>
            </el-tabs>

            <el-skeleton :rows="5" v-if="loading" animated />

            <el-empty :image-size="150" v-if="searchResult && searchResult.length==0" :description="`没有查询到与 ‘${lastKeyword}’ 相关内容`" />

            <el-scrollbar max-height="300px">
                <div class="search-result-block" :class="{'q-mt-lg':i>0}" v-for="(x,i) in searchResult">
                    <div class="text-h6 text-left text-bolder q-mx-md q-mb-sm">{{x.type==1?'行程文档':'广告图'}}</div>
                    <div class="items row items-center q-pa-md" v-for="(item) in x.pageData"  @click="item.IsEdit?editorFileHandler(item):openFilePositionHandler(item)" 
                    v-click-outside="()=>showRightContent=0" @contextmenu="()=>showRightContent=item.FileId">
                        <img v-if="x.type==1" class="biao" :src="(!x.ConfigId?'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708337830000_43.png':'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/20240805163740.png')" />
                        <img v-if="x.type==2" class="biao" src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708250377000_777.png" />
                        <el-popover :width="200" trigger="contextmenu" :visible="showRightContent==item.FileId">
                            <template #reference>
                                <div class="right col text-left q-pb-md">
                                    <div class="file-name" truncated v-html="item.FileName.replaceAll(lastKeyword,`<span class='text-waring'>${lastKeyword}</span>`)"></div>
                                    <div class="text-small q-mt-sm row items-center text-info">
                                        <el-tooltip effect="dark" :content="`${x.type==1?'行程文档':'广告图'}${item.FolderName=='/'?'':'/'+item.FolderName}`">
                                            <span class="folder-path">{{x.type==1?'行程文档':'广告图'}}{{item.FolderName=='/'?'':'/'+item.FolderName}}</span>
                                        </el-tooltip>
                                        <span class="q-mx-md col"> {{formatDateTimeToRead((item.UpdateTime && item.UpdateTime!=''?item.UpdateTime:item.CreateTime))}} {{ item.UpdateTime&&item.UpdateTime!=''?'修改过':'创建' }}</span>
                                        
                                        <span>{{item.IsCreate?'我 创建的':`${item.CreateName} 分享的`}}</span>
                                    </div>
                                </div>
                            </template>
                            <el-menu mode="vertical">
                                <el-menu-item v-if="item.IsEdit" index="1" @click="editorFileHandler(item)">打开文件</el-menu-item>
                                <el-menu-item index="2-4-1" @click="openFilePositionHandler(item)">打开文件所在位置</el-menu-item>
                            </el-menu>
                        </el-popover>
                        
                    </div>
                    <div class="text-info cusor-pointer q-mt-md text-small text-left q-mx-md" v-if="searchType=='0' && x.count>3" @click="()=>changeSearchType(x.type.toString())">更多</div>
                </div>
            </el-scrollbar>
        </div>
    </div>
</template>
<script setup lang="ts">
import { inject, ref } from 'vue';
import { Search } from '@element-plus/icons-vue';
import ConfigService from '@/services/ConfigService';
import { useUserStore } from '@/store/user';
import { storeToRefs } from 'pinia';
import {formatDateTimeToRead,createSaleEditorLink, openNewBlank } from '@/utils/common'
import { useScreenStore, useSellTemplateStore, useSlidesStore } from '@/store';
import { injectKeyTemplate } from '@/types/injectKey';
import { useRouter } from 'vue-router';
import { pl } from 'element-plus/es/locale';

const emit = defineEmits<{
  (event: 'open-position',playload:any): void
}>()

const {userInfo} = storeToRefs(useUserStore())
const router = useRouter()
const searchKey = ref<string>('')
const isSearchFocus = ref(false)
const searchType = ref<string>('0')
const loading = ref(false)
const searchResult = ref<any[]|null>(null)
const lastKeyword = ref('')
const searchData = ref({} as any);
searchData.value = inject(injectKeyTemplate);
const showRightContent = ref(0)

const loggedder = ref('')
loggedder.value = userInfo.value.nickname

const searchHandler = ()=>{
    if(loading.value) return
    loading.value = true

    searchResult.value=null
    if(searchKey.value!=''){
        lastKeyword.value = searchKey.value
        let task:any[] = []
        if(searchType.value=='0'||searchType.value=='1') task.push(searchByType(1,searchType.value=='0'?3:1000))
        if(searchType.value=='0'||searchType.value=='2') task.push(searchByType(2,searchType.value=='0'?3:1000))
        Promise.all(task).then(r=>{
            if(r && r.length>0){
                searchResult.value=[]
                r.forEach((x,i)=>{
                    if(x.data.data && x.data.data.count>0){
                        x.data.data.type = i==0 && searchType.value!='2'?1:2
                        searchResult.value!.push(x.data.data)
                    }
                })
            }
            loading.value = false
        }).catch(()=>{
            loading.value = false
        })
    }else{
        loading.value = false
    }
    
}

const editorFileHandler = (item:any)=>{
    if(item.IsEdit==0){
        ElMessage.error({
            message:'你没有权限执行这个操作，请联系分享者'
        })
        return
    }
    const cp = item.IsView==0?0:1
    const ep = item.IsDownload==0?0:1
    //@TODO:返回字段中缺少CreateBy,
    const url = createSaleEditorLink(item.FileId,item.TempId,item.FileType,0,ep,cp)
    openNewBlank(url)
    // router.push({
    //     path:url
    // })
}
const searchByType = (t:1|2,count:number)=>{
    return ConfigService.SearchFileAsync({
            FileType:t,
            FileName:searchKey.value,
            pageSize:count
        })
}
const changeSearchType = (val:string='')=>{
    if(val!='') searchType.value=val
    searchHandler()
}
const openFilePositionHandler = (item:any)=>{
    let playload = {
        FileId:item.FileId,
        FileType:item.FileType,
        FormShare:!item.IsCreate,
        Position:[] as any[]
    }
    if(item.FolderPath && item.FolderPath!='/'){
        let fp = item.FolderPath.split('/')
        let fn = item.FolderName.split('/')
        let posis:any[] = []
        fp.forEach((x:string,i:number)=>{
            posis.push({
                FileId:x,
                FileName:fn[i]
            })
        })
        playload.Position=posis
    }
    emit('open-position',playload)
    showRightContent.value = 0
}
</script>
<style>
.search-area{
    position:absolute;
    top:0px;
    left: calc(50% - 19vw - 10px);
    z-index:9;
}
.search-range-box{
    background-color: #FFF;
    box-shadow: 0px 0px 20px 0px rgba(76,87,125,0.2)!important;
}
.search-area .el-tabs__nav-wrap::after{
    height:0px !important;
}
.search-result-block{}
.search-result-block .items{
    background:#FFF;
    border-radius:8px;
    cursor:pointer;
    padding-bottom:0px !important;
}
.search-result-block .items:hover{
    background:#F1f1f1;
}
.search-result-block .items .biao{
    width:25px;
    margin-right:8px;
}
.search-result-block .items .right{
    border-bottom:1px solid #f5f5f5;
    min-width: 0;
    width: 0;
}
.search-result-block .items .right .file-name{
    font-size:14px;
    color:#000;
    margin-bottom:3px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}
.search-result-block .items:hover .right{
    border-bottom-color: transparent;
}
.search-result-block .items .right .folder-path{
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    max-width: 30%;
}
.el-menu,
.el-popper.is-light{
    border:none !important;
}
.el-menu-item{
    height: 35px !important;
}
</style>