<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 @click="OffEdit">
                    <img v-if="details.FileType ==1 " class="q-px-md"
                        :src="!details.ConfigId?datas.pdfImg:datas.pdfImgConfig" style="height: 43px" />
                    <img v-else-if="details.FileType == 2" class="q-px-md"
                        :src="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 v-if="!datas.editTitle" placement="top-start">
                            <template #content>
                                <div class="text-center" style="width: 200px">
                                    {{ details.FileName }}
                                </div>
                            </template>
                            <div class="TreeFile-Title pointer" @click.stop="datas.editTitle = true">
                                {{ details.FileName }}
                            </div>
                        </el-tooltip>
                        <el-input v-model="details.FileName" autosize type="textarea"
                            placeholder="Please input" maxlength="500" size="small" v-if="datas.editTitle"
                            @blur="OffEdit" />
                    </div>
                    <div class="text-small text-5B5D62 q-pt-sm" v-if="details.CreateByName||details.CreateName"
                    @click="OffEdit">
                        创建者：
                        <template v-if="type == 1">
                            {{ details.CreateByName }}
                        </template>
                        <template v-else>
                            {{ details.CreateName }}
                        </template>
                    </div>
                </div>
            </div>
        </template>
        
        <div class="TreeFile-container">
            <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
            @node-click="handleTreeNodeClick"
            class="auto-width-tree" 
            />
            
        </div>

        <template #footer>
            <div @click="OffEdit">
                <span class="dialog-footer">
                    <el-button @click.stop="() => closedhandler()">关闭</el-button>
                    <el-button type="primary" @click.stop="() => save()">
                        保存<template v-if="type">另存</template>
                        <template v-else>复制</template>
                    </el-button>
                </span>
            </div>
        </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";
import ConfigService from "@/services/ConfigService";

const props = defineProps({
    details: {
        type: Object,
        required: "",
    },
    hisObj: {
        type: Object,
        required: {},
    },
    type: {
        type: Number,
        required: 0,
    },
});
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",
    pdfImgConfig:"https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/20240805163740.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,
    editTitle: false,
});
const show = ref(true);
const loading = ref(true);
const deleteLoading = ref<any>(null);
const dataList = ref([]);

const OffEdit = () => {
    datas.editTitle = false;
};

const closedhandler = () => {
    emit("close");   
};
const handleTreeNodeClick = (data: any, checkObj: any) => {
    datas.FolderObj = data;
    OffEdit();
};
const save = () => {
    let title = props.details.FileName;
    if (props.type) title = "另存";
    else title = title + "复制";
    ElMessageBox.confirm(
        `此操作将${title}到${datas.FolderObj.FileName ? datas.FolderObj.FileName : "根目录"
        }，是否确定?`,
        "提示",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(async () => {
            try {
                if (props.type==1) SaveOverlay(title);
                else if(props.type==2) {
                    let FolderId = datas.FolderId!=null?datas.FolderId:0
                    emit('success',props.details.type,FolderId);
                }
                else if(!props.type) CopyId();
            } catch (error) { }
        })
        .catch(() => { });
};
const SaveOverlay = async (title: String) => {
    let queryMsg = {
        LogId: props.hisObj.LogId,
        FileId: props.hisObj.FileId,
        UpdateType: props.type,
        FolderId: datas.FolderId,
    };
    deleteLoading.value = ElLoading.service({
        lock: true,
        text: "正在处理",
    });
    let pageRes = await ConfigService.UpdateOtherByHistory(queryMsg);
    if (pageRes.data.resultCode == ApiResult.SUCCESS) {
        ElMessage({
            showClose: true,
            message: `${title}文件${props.details.FileType ? "" : "夹"}成功`,
            type: "success",
        });
        emit("close");
        emit("success");
    } else {
        ElMessage({
            showClose: true,
            message: `${title}文件${props.details.FileType ? "" : "夹"}失败`,
            type: "warning",
        });
    }
    deleteLoading.value.close();
    deleteLoading.value = null;
};

const CopyId = async () => {
    let queryMsg = {
        FileId: props.details.FileId,
        FileType: props.details.FileType,
        FileName: props.details.FileName,
        TargetFolderId: datas.FolderId,
    };
    deleteLoading.value = ElLoading.service({
        lock: true,
        text: "正在处理",
    });
    let pageRes = await FolderService.CopyFile(queryMsg);
    if (pageRes.data.resultCode == ApiResult.SUCCESS) {
        ElMessage({
            showClose: true,
            message: `复制文件${props.details.FileType ? "" : "夹"}成功`,
            type: "success",
        });
        emit("close");
        emit("success");
    } else {
        ElMessage({
            showClose: true,
            message: `复制文件${props.details.FileType ? "" : "夹"}失败`,
            type: "warning",
        });
    }
    deleteLoading.value.close();
    deleteLoading.value = null;
};
const getFile = async () => {
    let FileType
    if(props.details.FileType>0) FileType = props.details.FileType
    else FileType = props.details.FolderType
    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 = false;
            Object.assign(x, { disabled: isDisableds });
            if (x.ChildList.length > 0) {
                recursionChild(x, isDisableds);
            }
        });
    else {
        isDisableds = 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.details, (val) => {
    getFile()
});
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>
