<template>
    <div class="q-px-md q-pt-lg column full-height" ref="currentRootDom">
        <div class="q-pl-lg row q-mb-lg">
            <div class="col row items-center q-pl-md">
                <h5 class="row items-center">
                    <span class="pointer" v-if="queryObj.FileId > 0" @click="backInquireHandler">
                        <el-icon class="q-pt-md" size="20">
                            <ArrowLeft />
                        </el-icon>
                    </span>
                    <span class="q-pl-md" :class="[queryObj.FileId == 0 ? '' : 'row items-center']">
                        <span class="pointer" @click="clearNavigationHandler">分享</span>
                        <breadPeeling v-if="navigations && navigations.length>0" :navigations="navigations" @Inquire="breadPeelingInquire">
                        </breadPeeling>
                    </span>
                </h5>
                <div class="select-btn q-pl-lg pointer q-mt-sm">
                    <el-icon>
                        <RefreshRight v-if="!refreshLoading" @click="() => refreshHandler()" />
                        <Refresh v-else />
                    </el-icon>
                </div>
            </div>
            <div>
                <!-- <el-button v-if="selectedItems && selectedItems.length>0">
                    <el-icon><CopyDocument /></el-icon>
                    <span class="">批量复制</span>
                </el-button> -->
            </div>
        </div>
        <div class="col full-width q-ml-md">
            <el-table ref="dataTableRef" highlight-current-row class="sample-table" v-load-more="tableScrollHandler" :data="data" style="width: 100%" height="100%" v-loading="loading" @sort-change="sortHandler" :default-sort="{ prop: 'CreateTime', order: 'descending' }">
                <!-- <el-table-column type="selection" width="20" /> -->
                <el-table-column className="indentLeft">
                    <template #header>
                        <div class="row items-center">
                            <span>文档名称</span>
                            <el-popover :width="200" trigger="click" @before-enter="()=>filterFileNameStatus=true" @before-leave="()=>filterFileNameStatus=false">
                                <template #reference>
                                    <el-icon size="14px" class="q-ml-md cusor-pointer" :class="{'text-el-primary':queryObj.FileName!=''}">
                                        <ArrowDown v-if="!filterFileNameStatus"/>
                                        <ArrowUp v-else/>
                                    </el-icon>
                                </template>
                                <el-input v-model="tempFilterName" placeholder="请输入文档关键字" size="mini" class="full-width" />
                                <div class="q-mt-md text-right">
                                    <el-button link class="q-mr-sm">
                                        <span class="text-bolder pingfangr" @click="setFilterNameHandler(0)">重置</span>
                                    </el-button>
                                    <el-button link type="primary">
                                        <span class="text-bolder pingfangr" @click="setFilterNameHandler(1)">确认</span>
                                    </el-button>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        <div class="row items-center full-width" style="padding-left: 12px;">
                            <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708337830000_43.png" height="25" v-if="scope.row.FileType==1" />
                            <img src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708250377000_777.png" height="25" v-else-if="scope.row.FileType==2" />
                            <img src="@/assets/img/file.png" height="25" v-else />
                            <div class="temp-tr col q-ml-md" :class="{'cusor-pointer':scope.row.FileType==0}" @click="changeFolderHandler(scope.row)">
                                <el-tooltip effect="dark" :content="scope.row.FileName">
                                    <div class="file-name" v-html="queryObj.FileName!=''?(scope.row.FileName.replaceAll(queryObj.FileName,`<span class='text-waring'>${queryObj.FileName}</span>`)):scope.row.FileName"></div>
                                </el-tooltip>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="最近修改" width="150" sortable="custom" prop="CreateTime">
                    <template #default="scope">
                        {{ scope.row.FileType==0?'':formatDateTimeToRead(scope.row.UpdateTime&&scope.row.UpdateTime!=''?scope.row.UpdateTime:scope.row.CreateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="分享人" prop="CreateName" width="180" />
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <div class="row items-center" :class="{'hover':showItemId!=scope.row.FileId}">
                            <el-button type="primary" icon="View" size="small" @click.stop="openFileDocument(scope.row)" v-if="scope.row.FileType!=0">查看</el-button>
                            <el-dropdown v-if="scope.row.IsEdit||scope.row.IsDownload||scope.row.IsView" class="q-pl-md cusor-pointer" trigger="click" @visible-change="(val:boolean)=>dropdownChange(val,scope.row.FileId)">
                                <el-icon size="16" color="#b1b7cf"><MoreFilled /></el-icon>
                                <template #dropdown>
                                    <el-dropdown-menu class="q-pa-md">
                                        <el-dropdown-item v-if="scope.row.IsEdit && scope.row.FileType!=0" icon="EditPen" @click="editorFileHandler(scope.row)">编辑</el-dropdown-item>
                                        <el-dropdown-item v-if="scope.row.IsDownload && scope.row.FileType!=0" icon="Download" @click="exportDocument(scope.row)">导出</el-dropdown-item>
                                        <el-dropdown-item icon="CopyDocument" v-if="scope.row.IsView" @click="openCopyHandler(scope.row)">复制到</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty :image-size="150" v-if="(!data || data.length==0) && !loading" :description="(queryObj.FileId==0?'没有分享给我的文档':'文件夹里没有文件')" />
                </template>
            </el-table>
        </div>
    </div>
    <CopyFile v-if="openCopy" :details="copyObject" @close="() => openCopy=false"></CopyFile>
</template>
<script setup lang="ts">
import { ApiResult } from "@/configs/axios";
import ConfigService from "@/services/ConfigService";
import { ElMessage } from "element-plus";
import { PropType, inject, reactive, ref, watch } from "vue";
import {createPlayLink, createSaleEditorLink, formatDateTimeToRead, query} from '@/utils/common'
import breadPeeling from './components/breadPeeling.vue'
import CopyFile from './components/CopyFile.vue'
import { useScreenStore, useSellTemplateStore, useSlidesStore } from "@/store";
import { injectKeyTemplate } from "@/types/injectKey";
import FolderService from "@/services/FolderService";
import { ArrowDown,ArrowUp } from "@element-plus/icons-vue";
import { useUserStore } from '@/store/user';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';

const props = defineProps({
    position:{
        type:Object as PropType<{FileId:number,FileType:1|2,Position:{FileId:number,FileName:string}[]}|null>,
        default:null
    }
})
const emit = defineEmits<{
  (event: 'destroy-position'): void
}>()

const queryObj = reactive<any>({
    pageIndex: 1,
    pageSize: 50,
    pageCount: 0, //总页数
    FileType: 0,
    FileId: 0,
    OrderByType:2,
    FileName:'',
    QShareCreateBy:0
});
const refreshLoading = ref(false);
const navigations = ref<{ FileId: number; FileName: string }[]>([]);
const selectAll = ref(false);
const selectedDatas = ref<any[]>();
const data = ref<any[]>([])
const loading = ref(false)
const pageCount = ref(0)
const showItemId = ref(0)
const openCopy = ref(false)
const copyObject = ref<any>()
const searchData = ref({} as any);
searchData.value = inject(injectKeyTemplate);
const filterFileNameStatus = ref(false)
const tempFilterName = ref('')
const currentRootDom = ref()
const hgihlightId = ref(0)
const dataTableRef = ref()
const { userInfo } = storeToRefs(useUserStore())
const router = useRouter()

const backInquireHandler = () => {
    let Navigation = navigations.value[navigations.value.length - 2];
    if (Navigation && Navigation.FileId) breadPeelingInquire(Navigation.FileId, navigations.value.length - 2);
    else breadPeelingInquire(0, 0);
};
const breadPeelingInquire = (FileId: number, index: number) => {
    selectAll.value = false;
    selectedDatas.value = [];
    navigations.value.splice(index + 1, navigations.value.length - 1);
    queryObj.FileId = FileId;
    refreshHandler();
}
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;
    // searchData.value.ParentFileId = 0
    // if(item.IsDownload==0) searchData.value.noExportPermission = true
    // else searchData.value.noExportPermission = false
    // if(item.IsView==0) searchData.value.noCopyPermission = true
    // else searchData.value.noCopyPermission = false
    // SalesEditorStore.setSalesEditor(2);
    // marketStore.setMarket(false);
    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)
    router.push({
        path:url
    })
}
const getDocumentData = async () => {
    if(loading.value) return
    loading.value=true
    try {
        const response = await ConfigService.QueryGiveMeShareDocumentAsync(queryObj)
        if(response.data.resultCode == ApiResult.SUCCESS){
            pageCount.value = response.data.data.pageCount
            data.value = data.value.concat(response.data.data.pageData)
            if(hgihlightId.value!=0){
                let row = data.value.find(x=>x.FileId==hgihlightId.value && x.FileType!=0)
                if(row){
                    dataTableRef.value.setCurrentRow(row)
                }
                hgihlightId.value=0
            }
        }
    } catch (error) {
        ElMessage.error({
            message:'数据加载异常，请刷新页面'
        })
    }
    loading.value=false
    refreshLoading.value=false
}
const openFileDocument = (item:any) => {
    let param = query()
    const url = createPlayLink(item.FileId,0,2)//`${location.origin}/?uid=${param.uid}&sellId=${item.FileId}&ViewSlideshow=2`
    window.open(url);
}
const exportDocument = (item:any) => {
    let url = `https://fileservice.oytour.com/api/img/${item.FileId}/1/png/1/${item.HashInfo}`
    if(item.FileType==1) url = `https://fileservice.oytour.com/api/pdf/${item.FileId}/${item.HashInfo}`
    window.open(url);
}
const changeFolderHandler = async (item:any) =>{
    if(item.FileType==0){
        queryObj.FileId=item.FileId
        navigations.value.push({
            FileId:item.FileId,
            FileName:item.FileName
        })
        await refreshHandler()
    }
}
const dropdownChange = (val:boolean,id:number) => {
    showItemId.value = val?id:0
}
const clearNavigationHandler = async () => {
    navigations.value = []
    queryObj.FileId=0
    await refreshHandler()
}
const refreshHandler = async () => {
    queryObj.pageIndex=1
    queryObj.pageCount=1
    pageCount.value=1
    data.value=[]
    refreshLoading.value=true
    await getDocumentData()
}
const openCopyHandler = (item:any)=>{
    openCopy.value=true,
    copyObject.value = item
}
const sortHandler = (val:any)=>{
    queryObj.OrderByType = val.order=='descending'?2:1
    refreshHandler()
}
const setFilterNameHandler = (t:0|1)=>{
    if(!t) tempFilterName.value=''
    queryObj.FileName=tempFilterName.value
    currentRootDom.value.click()
    refreshHandler()
}
const collectHandler = async (row:any) => {
    if(loading.value) return
    let errmsg = ''
    loading.value=true
    try {
        let queryMsg = {
            FileId: row.FileId,
            FileType: row.FileType,
            IsCollect: row.IsCollect?0:1,
        }
        let response = await FolderService.SetFileCollect(queryMsg);
        if (response.data.resultCode == ApiResult.SUCCESS) {
            ElMessage.success({
                message: `${queryMsg.IsCollect?'收藏':'取消收藏'}${row.FileName}成功`
            });
            row.IsCollect=!row.IsCollect
        }else{
            errmsg = `收藏${row.FileName}失败,请刷新页面重试`
        }
    } catch (error) {
        errmsg = `收藏${row.FileName}失败,请刷新页面重试`
    }
    if(errmsg!=''){
        ElMessage.error({
            message:errmsg
        })
    }
    loading.value=false
}
const checkPositionHandler = (n:any)=>{
    if(n){
        if(n.Position && n.Position.length>0){
            navigations.value=n.Position
            queryObj.FileId = parseInt(n.Position[n.Position.length-1].FileId)
            queryObj.FileType = 0
        }else{
            navigations.value=[]
            queryObj.FileId = 0
            queryObj.FileType = 0
        }
        hgihlightId.value = n.FileId
        emit('destroy-position')
    }    
}
const tableScrollHandler = ()=>{
    if(pageCount.value>queryObj.pageIndex){
        queryObj.pageIndex++
        getDocumentData()
    }
}

watch(() => props.position,(n,o)=>{
  if(n){
    checkPositionHandler(n)
    refreshHandler()
  }
},{
  deep:true
})
checkPositionHandler(props.position)
getDocumentData()
</script>
<style lang="scss">
    .sample-table .el-table .el-table__cell{
        padding: 0;
    }
    .sample-table{
        font-size: 12px !important;
        font-family: microsoft yahei !important;
    }
    .sample-table .el-table-column--selection{
        border: none !important;
    }
    .sample-table .el-table-column--selection .cell{
        padding: 0 !important;
        padding-right: 5px !important;
        padding-left: 5px !important;
    }
    .sample-table th .cell{
        font-weight: normal !important;
    }
    .sample-table td, .sample-table th {
        border-bottom: 1px solid #f6f6f6 !important;
    }
    .sample-table td{
        /* color:#000; */
    }
    .sample-table tr td .el-checkbox,
    .sample-table tr td .hover{
        visibility: hidden !important;
    }
    .sample-table tr:hover td .el-checkbox,
    .sample-table tr td .is-checked,
    .sample-table tr:hover td .hover{
        visibility: visible !important;
    }
    .sample-table .indentLeft{
        border:none !important;
        padding: 0 !important;
    }
    .sample-table .indentLeft .cell{
        padding: 0 !important;
    }
    .sample-table .temp-tr,
    .sample-table th.indentLeft{
        border-bottom: 1px solid #f6f6f6 !important;
        padding: 8px 0 !important;
    }
    .sample-table th.indentLeft .cell{
        padding: 0 12px !important;
    }
    .sample-table .file-name{
        white-space:nowrap !important;
        overflow:hidden !important;
        text-overflow:ellipsis !important;
        width: 100%;
    }
    /* .sample-table th:nth-child(2) .cell{
        padding-left: 0 !important;
    } */
</style>
