<template>
    <div v-if="!excelShow">
        <div>
            <a @click="gohome()" style="font-size: large;">主目录</a>
            /<a v-for="item in path" @click="choicePath(item)" style="font-size: large;">{{ item }}/</a>
        </div>
        <div class="fileBox" @contextmenu.prevent @click.right="rightclick" @click="leftclicek">
            <div v-for="item in contents" class="file" :style="{ 'background-color': each_color(item) }"
                @click='changechoice($event, item)' @dblclick="dbcli(item)">
                <img :src="getImage(item)" width="100px" height="100px" style="margin-top: 15px;">
                <p v-if="!(renamestatu && choice == item)">{{ getname(item.name) }}</p>
                <input v-else v-model="lishiname" style="width: 150px" autofocus @keyup.enter="rename" />
            </div>
        </div>
        <div v-if="edit" class="pop" :style="{ 'left': mouse.left + 'px', 'top': mouse.top + 'px' }">
            <div v-if="choice && !choice.floder && elements.indexOf('7-7')!=-1" class="editbutton" @click="downloadFile()">下载</div>
            <div v-if="elements.indexOf('7-5')!=-1" class="editbutton" @click="moveModal = true; this.edit = false">移动</div>
            <div v-if="elements.indexOf('7-3')!=-1" class="editbutton" @click="lishiname = this.choice.name; this.renamestatu = true; this.edit = false">
                重命名
            </div>
            <div v-if="elements.indexOf('7-2')!=-1" class="editbutton" @click="deletefile()">删除</div>
        </div>
        <div v-if="add" class="pop" :style="{ 'left': mouse.left + 'px', 'top': mouse.top + 'px' }">
            <div v-if="elements.indexOf('7-1')!=-1" class="editbutton" @click="addinfo.type = 'file'; this.add = false; addmoadl = true">新建文件</div>
            <div v-if="elements.indexOf('7-1')!=-1" class="editbutton" @click="addinfo.type = 'floder'; this.add = false; addmoadl = true">新建文件夹</div>
            <div v-if="elements.indexOf('7-6')!=-1" class="editbutton" @click="uploadfile = true; this.add = false;">上传文件</div>
        </div>
    </div>
    <div v-if="excelShow">
        <luexcel v-if="excelShow" ref="execlbox" :data="test_data"></luexcel>
        <div style="text-align: left;margin-top: 5px;">
            <Button type="primary" @click="saveExecl()">保存</Button>
            <Button style="margin-left: 5px;" @click="exitExecl()">关闭</Button>
        </div>
    </div>
    <Modal v-model="addmoadl" :closable="false">
        <Input v-model="addinfo.name" />
        <template #footer>
            <Button @click="closeShow()">取消</Button>
            <Button type="primary" @click="send()">确认</Button>
        </template>
    </Modal>
    <Modal v-model="uploadfile" :closable="false">
        <Upload multiple type="drag" :before-upload="handleUpload" action="">
            <div style="padding: 20px 0">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p v-if="!file">请选择上传文件</p>
                <div v-else style="color: #19be6b;">{{ file.name }}</div>
            </div>
        </Upload>
        <template #footer>
            <Button type="primary" @click="upload()">上传</Button>
            <Button @click="uploadfile = false; this.file = null">关闭</Button>
        </template>
    </Modal>
    <Modal v-model="moveModal" :closable="false">
        <div class="fileBox" @contextmenu.prevent>
            <div class="file" v-if="!canback" @dblclick="dbcli(homeobj, 1)" @click='changechoice($event, homeobj, 1)'
                :style="{ 'background-color': each_color(homeobj, 1) }">
                <img :src="getImage({ floder: true })" width="100px" height="100px" style="margin-top: 15px;">
                <p>主目录</p>
            </div>
            <div v-else>
                <div class="fileBox" @contextmenu.prevent>
                    <div v-for="item in moveContents">
                        <div v-if="item.floder && (!choice.floder || (choice.floder && !(item.name == choice.name && JSON.stringify(path) == JSON.stringify(movepath))))"
                            class="file" :style="{ 'background-color': each_color(item, 1) }"
                            @click='changechoice($event, item, 1)' @dblclick="dbcli(item, 1)">
                            <img :src="getImage(item)" width="100px" height="100px" style="margin-top: 15px;">
                            <p>{{ getname(item.name) }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <Button v-if="canback" type="primary" @click="moveback">返回上级目录</Button>
            <Button type="primary" @click="movetrue">确认</Button>
            <Button @click="closemove">关闭</Button>
        </template>
    </Modal>
</template>
<script>
import LuExcel from '@/components/LuExcel.vue'

import LuckyExcel from 'luckyexcel';



export default {
    props: ['isCollapsed',],
    components: {
        luexcel: LuExcel
    },
    data() {
        return {
            excelShow: false,
            openname: null,
            elements:[],
            page_id: 26,
            edit: false,
            add: false,
            renamestatu: false,
            file: null,
            moveModal: false,
            addinfo: {
                type: null,
                name: null,
            },
            uploadfile: false,
            lishiname: null,
            choice: null,
            contents: [],
            choiceTarget: null,
            addmoadl: false,
            mouse: {
                left: 0,
                top: 0
            },
            homeobj: { floder: true, name: null },
            title: "测试用例",
            path: [],
            movechoice: null,
            movepath: [],
            moveContents: [],
            canback: false
        }
    },
    methods: {
        each_color(item, type = null) {
            if (!type) {
                if (item == this.choice) return 'rgb(198, 226, 255)'
            }
            else if (item == this.movechoice) return 'rgb(198, 226, 255)'
        },
        getImage(item) {
            if (item.floder) return require('@/assets/floderblue.svg')
            var suffix = item.name.substring(item.name.lastIndexOf(".") + 1).toLowerCase()
            if (['txt', 'log', 'py', 'js', 'php', 'java', 'log', 'sh', 'csv'].indexOf(suffix) != -1) {
                item.type = 'txt'
                return require('@/assets/txt.svg')
            }
            if (['xlsx'].indexOf(suffix) != -1) {
                item.type = 'xlsx'
                return require('@/assets/excel.svg')
            }
            if (['jpg', 'png', 'svg', 'gif', 'psd', 'webp'].indexOf(suffix) != -1) {
                item.type = 'image'
                return require('@/assets/IMAGE.svg')
            }
            if (['wav', 'flac', 'ape', 'alac', 'wavpack', 'wv', 'mp3', 'aac', 'opus'].indexOf(suffix) != -1) {
                item.type = 'aduio'
                return require('@/assets/mp3.svg')
            }
            if (['pdf'].indexOf(suffix) != -1) {
                item.type = 'pdf'
                return require('@/assets/pdf.svg')
            }
            if (['mp4', 'avi', 'mov', 'wmv', 'mkv', 'flv', 'webm'].indexOf(suffix) != -1) {
                item.type = 'video'
                return require('@/assets/video.svg')
            }
            if (['docx', 'doc'].indexOf(suffix) != -1) {
                item.type = 'doc'
                return require('@/assets/word.svg')
            }
            if (['pptx', 'ppt'].indexOf(suffix) != -1) {
                item.type = 'ppt'
                return require('@/assets/ppt.svg')
            }
            if (['rar', 'tar', 'zip', '7z', 'gz', 'bz2', 'z'].indexOf(suffix) != -1) {
                item.type = 'zip'
                return require('@/assets/zip-file-01.svg')
            }
            item.type = 'unknow'
            return require('@/assets/file-unknown.svg')
        },
        closeShow() {
            this.addinfo = {
                type: null,
                name: null
            }
            this.addmoadl = false
        },
        handleUpload(file) {
            this.file = file;
        },
        send() {
            if (!this.addinfo.name) return this.$Message.error('请输入名称')
            this.$request("post", "/apptool/case/create", { path: this.path.join('/'), name: this.addinfo.name, type: this.addinfo.type }, this, () => { this.closeShow(); this.changePath() })
        },
        rename() {
            if (this.lishiname == this.choice.name || !this.lishiname) return this.canclerename()
            this.$request("post", "/apptool/case/rename", { path: this.path.join('/'), oldname: this.choice.name, newname: this.lishiname }, this, () => { this.canclerename(); this.changePath() })
        },
        deletefile() {
            this.$request("post", "/apptool/case/delete", { path: this.path.join('/'), name: this.choice.name }, this, () => { this.changePath() })
        },
        getname(name) {
            let a = name.split('.')
            if (a.length > 1) {
                const houzhui = a.pop()
                let qian = a.join("")
                if (17 - houzhui.length - 1 < qian.length) {
                    return qian.slice(0, 13 - houzhui.length - 3) + "...." + houzhui
                }
            } else {
                if (name.length > 13) return name.slice(0, 15) + "..."
            } return name
        },
        upload() {
            const formData = new FormData();
            formData.append('file', this.file);
            formData.append("path", this.path.join("/"));
            this.$http.post('/apptool/case/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(() => {
                this.changePath();
                this.file = null
            }).catch(() => {
                this.$Message.error("上传文件失败")
            })
        },
        downloadFile() {
            window.location.href = '/api/apptool/case/download?path=' + this.path.join('/') + '&name=' + this.choice.name;
            this.edit = false;
        },
        canclerename() {
            this.lishiname = null;
            this.renamestatu = false;
        },
        changechoice(event, item, type = null) {
            if (!type) {
                if (item == this.choice) return
                this.choice = item
                this.choiceTarget = event.currentTarget
                if (this.edit) this.edit = false
                if (this.add) this.add = false
                if (this.renamestatu) this.canclerename()
            } else {
                if (item == this.movechoice) return
                this.movechoice = item
            }
        },
        dbcli(item, type = null) {
            if (item.floder) {
                if (!type) {
                    this.path.push(item.name)
                    this.changePath()
                } else {
                    if (item && item.name) {
                        this.movepath.push(item.name)
                    }
                    if (this.movechoice) this.movechoice = null
                    this.changePath(type)
                    this.canback = true
                }
            } if (item.type == 'xlsx') {
                if (this.elements.indexOf("7-4")==-1) return
                this.openname = item.name
                const url = '/api/apptool/case/download?path=' + this.path.join('/') + '&name=' + this.openname
                this.render_execl(url, this.openname)
            }
        },
        choicePath(item) {
            if (this.path.findIndex((each) => { return each == item }) == this.path.length - 1) return
            else {
                this.path = this.path.slice(0, this.path.findIndex((each) => { return each == item }) + 1)
                this.changePath()
            }
        },
        moveback() {
            if (this.canback && this.movepath.length == 0) {
                this.canback = false
            } else {
                this.movepath.pop()
                this.changePath(1)
            }
        },
        movetrue() {
            if (!this.movechoice) return this.$Message.error("请选择移动路径")
            let path = null
            if (!this.movechoice.name) path = ''
            else path = this.movepath.join('/') ? this.movepath.join('/') + '/' + this.movechoice.name : this.movechoice.name
            console.info(this.movechoice)
            this.$request("post", "/apptool/case/move", { path: this.path.join('/'), name: this.choice.name, targetPath: path }, this, () => { this.closemove(); this.changePath() })
        },
        closemove() {
            this.moveModal = false;
            this.canback = false;
            this.moveContents = [];
            this.movepath = [];
            this.movechoice = null;
        },
        gohome() {
            this.path = []
            this.changePath();
        },
        changePath(type = null) {
            const relpath = this.path.join("/")
            const mvPath = this.movepath.join("/")
            this.$request("get", "/apptool/case/filelist?path=" + (type ? mvPath : relpath), null, this, (data) => { type ? (this.moveContents = data.data) : (this.contents = data.data) })
        },
        rightclick(e) {
            this.mouse.left = e.pageX;
            this.mouse.top = e.pageY;
            if (!this.choiceTarget) return this.add = true
            const target = this.choiceTarget.getBoundingClientRect()
            if (this.mouse.left >= target.left && this.mouse.left <= target.left + target.width && this.mouse.top >= target.top && this.mouse.top <= target.top + target.height) {
                return this.edit = true
            }
            this.add = true
        },
        leftclicek(e) {
            if (this.add) this.add = false
            if (this.edit) this.edit = false
            this.mouse.left = e.pageX;
            this.mouse.top = e.pageY;
            if (!this.choiceTarget) return
            const target = this.choiceTarget.getBoundingClientRect()
            if (!(this.mouse.left >= target.left && this.mouse.left <= target.left + target.width && this.mouse.top >= target.top && this.mouse.top <= target.top + target.height)) {
                if (this.renamestatu) this.canclerename()
            }
        },
        closeEdit() {
            this.edit = false
        },
        async fetchExcelFile(url, filename) {
            try {
                const response = await fetch(url);
                const blob = await response.blob();
                return new File([blob], filename);
            } catch (error) {
                console.error('获取文件失败', error);
            }
        },

        render_execl(url, filename) {
            this.fetchExcelFile(url, filename).then(file => {
                if (file) {
                    LuckyExcel.transformExcelToLucky(file, (data) => {
                        this.test_data = data;
                        this.excelShow = true;
                        this.$nextTick(() => {
                            this.$refs.execlbox.render()
                        })
                    })
                }
            })
        },


        saveExecl() {
            const transToFile = async (blob, fileName) => {
                return new File([blob], fileName)
            }

            const savefile = (blod) => {
                transToFile(blod, this.openname).then(file => {
                    let formData = new FormData();
                    console.info(file)
                    formData.append('file', file);
                    formData.append("path", this.path.join("/"));
                    this.$http.post('/apptool/case/upload', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then(() => {
                        this.$Message.success("保存成功")
                        this.file = null
                        const url = '/api/apptool/case/download?path=' + this.path.join('/') + '&name=' + this.openname
                        this.render_execl(url, this.openname)
                    }).catch(() => {
                        this.$Message.error("保存失败")
                    })
                })


            }
            this.$refs.execlbox.getuploadBlob(savefile)
        },
        exitExecl() {
            this.excelShow = false
        }
    },
    created() {
        this.$getElements(this.page_id, this, (data) => this.elements = data.data);
        this.changePath()
    }
};
</script>

<style>
a {
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

.editbutton:hover {
    background-color: rgb(198, 226, 255);
}

.fileBox {
    display: flex;
    flex-wrap: wrap;
    margin-top: 20px;
    min-height: 170px;
    background-color: beige;
}

.file {
    height: 150px;
    width: 150px;
    margin: 10px 10px 10px 10px;
    text-align: center;
    border-radius: 10px;
}

.pop {
    position: absolute;
    background: white;
    box-shadow: 1px 1px 4px #888;
    font-size: 12px;
    border-radius: 5px;
    z-index: 999;
}

.pop>div {
    margin: 15px 10px;
    cursor: pointer;
}

#sheet {
    /** The height of the Union uses the height of the parent container */
    flex: 1;
}
</style>