<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 class="biao" :src="(x.type==1 ?'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/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>{{userInfo.EmployeeId==item.CreateBy?'我 创建的':`${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} from '@/utils/common'
import { useScreenStore, useSellTemplateStore, useSlidesStore } from '@/store';
import { injectKeyTemplate } from '@/types/injectKey';
import { pl } from 'element-plus/es/locale';

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

const {userInfo} = storeToRefs(useUserStore())
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)=>{
    let list:any = [{
        id: "test-slide-1",
        pageType: 0,
        elements: [],
        background: {
            type: "solid",
            color: "#ffffff",
        },
    }];
    const SalesEditorStore = useSellTemplateStore();
    useSlidesStore().setSlides(list);
    const marketStore = useScreenStore();
    searchData.value.sellId = item.FileId;
    searchData.value.sellTempId = item.TempId;
    searchData.value.TemplateType = item.FileType;
    if(loggedder.value!=row.CreateName){
        searchData.value.ParentFileId = 0
    }else searchData.value.ParentFileId = item.FolderId
    SalesEditorStore.setSalesEditor(2);
    marketStore.setMarket(false);
}
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:userInfo.value.EmployeeId!=item.CreateBy,
        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)
}
</script>
<style>
.search-area{
    position: relative;
    left: calc(50% - 31.8vw - 10px);
    /* position: absolute;
    left: calc(50% - 19vw - 10px); */
    top:0px;
    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>