<template>
    <el-dialog v-model="show" v-loading="loading" :show-close="false" 
    :close-on-press-escape="false" :close-on-click-modal="false" 
    style="width: 260px;">
        <template #header>
            <div class="row overflow-hide">
                <div>
                    <img v-if="details.FileType>0" class="q-px-md" 
                        :src="details.FileType==1?datas.pdfImg:datas.adsImg" 
                        style="height: 43px;" />
                    <img v-else class="q-px-md" 
                        src="@/assets/img/file.png" 
                        style="height: 43px;" />
                </div>
                <div class="q-pl-md col">
                    <div class="row flex-center">
                        <el-tooltip
                        placement="top-start">
                            <template #content><div class="text-center" style="width: 200px;">{{details.FileName}}</div></template>
                            <div class="TreeFile-Title pointer">{{details.FileName}}</div>
                        </el-tooltip>
                    </div>
                    <div class="text-small text-5B5D62 q-pt-sm">
                        <template v-if="details">
                            创建者：{{details.CreateName}}
                        </template>
                        <div v-else class="row items-center">
                            <!-- <el-tooltip
                                placement="top-start">
                                <template #content><div class="text-center" style="width: 200px;">移动文件 {{selectedDatas.join(',')}}</div></template>
                                <div class="TreeFile-Title text-sm pointer">移动文件 {{selectedDatas.join(',')}}</div>
                            </el-tooltip> -->
                            <div class="TreeFile-Title text-sm pointer">批量移动文件</div>
                        </div>
                    </div>
                </div>
            </div>
            
        </template>
        
        <div class="TreeFile-container">
            <!-- <el-input class="q-pb-md q-px-md" v-model="filterText" placeholder="关键词检索文件夹" />
            <el-tree 
            ref="treeRef"
            :data="dataList" 
            :props="defaultProps" 
            node-key="FileId"
            default-expand-all
            show-checkbox 
            check-strictly
            :filter-node-method="filterNode"
            @check="handleTreeNodeClick"/>-->
            <el-tree-select
            placeholder="请选择文件"
            node-key="FileId"
            :props="defaultProps" 
            v-model="datas.FolderId"
            :data="dataList"
            check-strictly
            :render-after-expand="false"
            style="width: 220px"
            filterable
            @current-change="handleTreeNodeClick"
            class="auto-width-tree"
            />
            
        </div>
        
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="()=>closedhandler()">关闭</el-button>
                <el-button :disabled="datas.FolderId==null" type="primary" @click="()=>MoveToFolder()"> 保存移动 </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ApiResult } from '@/configs/axios';
import OrgService from '@/services/OrgService';
import { ref,reactive,watch } from 'vue';
import { View,Download,EditPen,Delete } from '@element-plus/icons-vue';
import { ElMessage,ElTree } from 'element-plus';
import FolderService from "@/services/FolderService";

    const props = defineProps({
        details:{
            type:Object,
            required:''
        },
        selectedDatas:{
            type: Array,
            required:[]
        },
        setFileList:{
            type: Array,
            required:[]
        },
        fileType: {
            type:Number,
            required: 1
        },
        fileId:{
            type: Number,
            required: '' 
        }
    })
    const emit = defineEmits<{
        (event: 'close'): void,
        (event: 'success'): void
    }>()

    interface Tree {
        [key: string]: any
    }
    const filterText = ref('')
    const treeRef = ref<InstanceType<typeof ElTree>>()
    const defaultProps = {
        children: 'ChildList',
        label: 'FileName',
        disabled: 'disabled',
    }
    const datas = reactive({
        pdfImg: 'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708337830000_43.png',
        adsImg: 'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1708250377000_777.png',
        fileList: [] as Tree[],
        FolderId: null as Number,
        FolderObj: {},
        checkedKeys: null as any
    })
    datas.FolderId = props.fileId
    const show=ref(true)
    const loading = ref(true)
    const deleteLoading = ref<any>(null);
    const dataList=ref([])

    const closedhandler=()=>{
        emit('close')
    }
    const handleTreeNodeClick = (data:any,checkObj:any) => {
        // 共两个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象
        // 树目前的选中状态对象，包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
        datas.FolderObj = data
    }
    const filterNode = (value: string, data: Tree) => {
        if (!value) return true
        return data.FileName.includes(value)
    }
    const MoveToFolder = () => {
        let title = ''
        let FileList = []
        if(!props.details) {
            title = `批量`
            for(let i=0;i<props.setFileList.length;i++){
                FileList.push(
                    {
                        FileId: props.setFileList[i].FileId,
                        FileType: props.setFileList[i].FileType
                    }
                )
            }
            FileList = props.setFileList
        }else {
            title = props.details.FileName
            FileList.push({
                FileId: props.details.FileId,
                FileType: props.details.FileType
            })
        }
        
        ElMessageBox.confirm(`此操作将${title}移动到${datas.FolderObj.FileName?datas.FolderObj.FileName:'根目录'}，是否确定?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
            try {
                let queryMsg = {
                    FileList: FileList,
                    TargetFolderId: datas.FolderId,
                };
                deleteLoading.value = ElLoading.service({
                    lock: true,
                    text: "正在处理",
                });
                let pageRes = await FolderService.UpdateTripOtherFolder(queryMsg);
                if (pageRes.data.resultCode == ApiResult.SUCCESS) {
                    ElMessage({
                        showClose: true,
                        message: `移动文件成功`,
                        type: "success",
                    });
                    emit('close')
                    emit('success')
                } else {
                    ElMessage({
                        showClose: true,
                        message: `移动文件失败`,
                        type: "warning",
                    });
                }
                deleteLoading.value.close();
                deleteLoading.value = null;
            } catch (error) {}
            })
            .catch(() => {});
        }

    const getFile = async () => {
        let FileType = props.details.FileType>0?props.details.FileType:props.details.FolderType
        if(props.setFileList&&props.setFileList.length>0) FileType = props.fileType
        let querys = {
            FileType: FileType
        }
        let pageRes = await FolderService.GetMyFolderTree(querys);
        if (pageRes.data.resultCode == ApiResult.SUCCESS) {
            dataList.value = pageRes.data.data
            recursive(dataList.value)
        }
    }

    
    const recursive = (arrs:Array,disabled:any) =>{
        let isDisableds:Boolean
        if(arrs.length>0) arrs.forEach(x => {
            isDisableds = (props.selectedDatas&&props.selectedDatas.indexOf(x.FileId)!=-1&&!props.details)||props.details.FileId==x.FileId||disabled?true:false
            if(props.details.FileType>0&&x.FileId==props.details.FileId) isDisableds = false
            if(!props.details){
                for(let i =0;i<props.setFileList.length;i++){
                    if(props.setFileList[i].FileType&&props.setFileList[i].FileId==x.FileId)  isDisableds = false
                }
            }
            if((props.details.ParentFileId!=undefined&&props.details&&x.FileId==props.details.ParentFileId)||(props.setFileList&&props.setFileList[0].ParentFileId==x.FileId)) datas.FolderObj = x
            Object.assign(x,{disabled:isDisableds})
            if(x.ChildList.length>0){
                recursionChild(x,isDisableds)
            }
        })
        else {
            isDisableds = (props.selectedDatas.indexOf(arrs.FileId)!=-1&&!props.details)||props.details.FileId==arrs.FileId||disabled?true:false
            Object.assign(arrs,{disabled:isDisableds})
        }
    }
    const recursionChild = (arrs:any,disabled:any) => {
        if(arrs&&arrs.ChildList.length>0) {
            recursive(arrs.ChildList,disabled)
        }
    }

    watch(filterText, (val) => {
        treeRef.value!.filter(val)
    })
    watch(props.selectedDatas, (val) => {
        recursive(dataList.value)
    })
    getFile()
</script>
<style scoped>
    .TreeFile-Title{
        width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        font-size: 15px;
        position: relative;
    }
    .TreeFile-Title.text-sm{
        font-size: 12px;
    }
    .TreeFile-container th{
        padding: 0 10px 5px 10px;
        border-bottom: 1px solid #f6f6f6;
        background: #fff;
        position: sticky;
        top: 0px;
        z-index: 2;
    }
    .TreeFile-container td{
        padding:  8px 10px;
        border-bottom: 1px solid #f6f6f6;
    }
    .TreeFile-table {

    }
</style>