<template>
    <div class="main">
        <div class="headerNav">
            <div class="leftNav">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item
                        v-for="(breadcrumbItem, index) of breadcrumb"
                        :key="index"
                        @click.native="backCrumb(index)">
                            {{ breadcrumbItem.label }}
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="rightNav">
                <el-select style="margin:2px 15px 0 0" class="timer-select" v-show="currentIsFiLe" v-model="timeSelect" placeholder="请选择">
                    <el-option
                        v-for="item in termOptions"
                        :key="item.ID"
                        :label="item.TeamName"
                        :value="item.ID">
                    </el-option>
                </el-select>
                <search></search>
                <div class="feature" v-show="!currentIsFiLe">
                    <div :class="{'icon-sel': bigMode}" class="icon-ctn" @click="bigMode = true">
                        <i class="el-icon-picture"></i>
                    </div>
                    <div :class="{'icon-sel': !bigMode}" class="icon-ctn" @click="bigMode = false">
                        <i class="el-icon-s-operation"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="folderCtn" @contextmenu.prevent="showMenu">
                <component :is="(bigMode && currentIsFiLe === false)?'big-folder':'small-folder'"
                    :file-list="currentFileList"
                    :currentIsFiLe="currentIsFiLe"
                    :pagination-query="paginationQuery"
                    @showMenu="showMenu"
                    @intoFolder="intoFolder"
                    @dragUploadFile="dragUploadFile"
                    @tableIntoFile="intoFolder"
                    @getSizeChange="handleSizeChange"
                    @getCurrentPage="handleCurrentChange">
                </component>
        </div>

        <!-- 右键菜单栏 -->
        <myupload-ctx-menu
            ref="contextMenu"
            :menuVisible="menuVisible"
            :currentIsFiLe="currentIsFiLe"
            :uploadVisible="uploadVisible"
            :rightMenuData="rightMenuData"
            :coordinate="coordinate"
            :menuMode="menuMode"
            @doShareFile="doShareFile"
            @showUploadMenu="showUploadMenu"
            @selectUploadPath="selectUploadPath"
            @menuOpenFile="intoFolder"
            @updateOrCreateFolder="updateOrCreateFolder"
            @handleDeleteFolder="handleDeleteFolder">
        </myupload-ctx-menu>

        <upload-file
            :list-data="curSelectList"
            :selectFolderVisible="selectFolderVisible"
            @selectUploadFile="selectUploadFile"
            @closeSelectFolderVisible="selectFolderVisible = false"
        />

        <!-- 侧滑块查看普通文档 -->
        <el-drawer
            title="查看"
            :visible.sync="documentDrawer"
            :size="'80%'">
            <iframe :src="documentUrl" width="100%" height= "100%" name="topFrame" noresize="noresize" frameborder="0" id="topFrame"></iframe>
        </el-drawer>

        <input v-show="false" type="file" ref="fileUpload" @change="uploadfileChange"/>
        <button v-show="false" ref="btn" @click="currentIsFiLe = true">设置当前页面为文件模式</button>
    </div>
</template>

<script>

import { ossUpload } from '@/assets/utils/ossTool.js'
import ossPaths from '@/assets/ossPaths.js'
export default {
    name: 'MyUpload',
    components: {
        Search: () => import('./components/Search'),
        BigFolder: () => import('./components/BigFolder'),
        SmallFolder: () => import('./components/SmallFolder'),
        MyuploadCtxMenu: () => import('./components/MyuploadCtxMenu'),
        UploadFile: () => import('./components/UploadFile')
    },
    data () {
        return {
            currentComponent: 'BigFolder', // BigFolder 大图标模式，SmallFolder 小图标模式
            bigMode: true, // 文件夹大小图标模式
            currentIsFiLe: false, // 当前层次是否为文档列表
            timeSelect: 'allItem', // 学期选择框数据
            termOptions: [{ // 学期选择options
                value: 'allItem',
                label: '全部学期'
            }],
            menuVisible: false, // 右键菜单栏
            menuMode: '', // 菜单根据模式显示对于内容
            uploadVisible: false, // 上传菜单栏
            documentUrl: '', // 文档在线地址
            documentDrawer: false, // 查看文档抽屉
            rightMenuData: {}, // 右键选中文件夹或文件数据
            coordinate: { // 菜单栏坐标
                menuX: '0px',
                menuY: '0px',
                uploadX: '0px',
                uploadY: '0px'
            },
            currentFileList: [],
            curSelectList: [], // 当前选择需要上传的文件夹当前路径列表
            selectFolderVisible: false, // 查看文件侧滑框
            selectFolderList: [], // 上传文件选择文件夹列表
            breadcrumb: [], // 面包屑
            uploadData: { // 储存待上传的文件信息
                file: null,
                folderId: '',
                isdrag: false // 当时是否是拖拽获得文件信息
            },
            paginationQuery: { // 分页信息
                amount: 0,
                pageSize: 50,
                pageIndex: 1
            }
        }
    },
    mounted () {
        this.getFolderList()
        this.getTermList()
    },
    created () {
    },
    methods: {
        getFolderList () {
            this.$api.schoolBasedResourcesApi.GetFolderList().then(res => {
                this.$handleResponse(res).then(data => {
                    this.initFromBreadcrumb(data)
                })
            })
        },
        getTermList () {
            /* 获取学期列表 */
            this.$api.commonApi.getTermInfoList().then(res => {
                this.$handleResponse(res).then(data => {
                    this.termOptions = data
                    this.timeSelect = data[0].ID
                })
            })
        },
        initFromBreadcrumb (data) {
            /* 通过面包屑初始化数据 */
            this.currentIsFile = false
            let breadcrumb = this.breadcrumb
            if (breadcrumb.length <= 1) {
                this.breadcrumb = [{ label: '首页', listData: data, parent: { b_id: '0', parent_id: '0' }, currentIsFiLe: false }]
                this.currentFileList = data
            } else {
                let newBreadcrumb = [{ label: '首页', listData: data, parent: { b_id: '0', parent_id: '0' }, currentIsFiLe: false }]
                let currentList = data
                for (let i = 1; i < breadcrumb.length; i++) {
                    let hasThisFile = false
                    for (let j = 0; j < currentList.length; j++) {
                        if (currentList[j].b_id === breadcrumb[i].parent.b_id) {
                            let isFile = (!currentList[j].children || currentList[j].children.length === 0) && currentList[j].file_count > 0
                            this.currentIsFile = isFile
                            this.addCrumb(newBreadcrumb, currentList[j], isFile)
                            if (isFile) {
                                this.getFileList(currentList[j])
                            } else {
                                currentList = currentList[j].children
                            }
                            hasThisFile = true
                            break
                        }
                    }
                    if (hasThisFile === false) {
                        break
                    }
                }
                this.breadcrumb = newBreadcrumb
                if (!this.currentIsFile) {
                    this.currentFileList = currentList
                }
            }
        },
        getFileList (file) {
            this.$refs.btn.click()
            const folderId = file.b_id
            const selType = file.folder_type
            let data = {
                data: { folder_id: folderId, sel_type: selType },
                PageSize: this.paginationQuery.pageSize,
                PageNumber: this.paginationQuery.pageIndex
            }
            this.$api.schoolBasedResourcesApi.GetFileList(data).then(res => {
                this.$handleResponse(res).then(data => {
                    this.currentFileList = data.Data
                    this.paginationQuery.amount = data.TotalRecords
                })
            })
        },
        backCrumb (index) {
            /* 点击面包屑返回前几级 */
            let breadcrumb = this.breadcrumb
            let item = breadcrumb[index]
            this.currentIsFiLe = false
            if (index < breadcrumb.length - 1) {
                this.currentFileList = item.listData
                this.breadcrumb = breadcrumb.slice(0, index + 1)
            }
        },
        addCrumb (breadcrumb, file, currentIsFiLe) {
            /* 添加面包屑 */
            breadcrumb.push({ label: file.folder_name, listData: file.children, parent: file, currentIsFiLe })
        },
        intoFolder (file) {
            /* 进入下一级文件夹 */
            if ((file.children && file.children.length > 0 && this.currentIsFiLe === false) || (file.file_count === 0 && this.breadcrumb.length < 3)) {
                // 进入文件夹
                this.currentIsFiLe = false
                this.addCrumb(this.breadcrumb, file, this.currentIsFiLe)
                this.currentFileList = file.children || []
            } else {
                // 获取当前文件夹的文档列表
                if (this.currentIsFiLe === false) {
                    this.currentIsFiLe = true
                    this.addCrumb(this.breadcrumb, file, this.currentIsFiLe)
                    this.getFileList(file)
                } else {
                    let url = 'https://onlinepreview.vschool100.cn/onlinePreview?url=' + encodeURIComponent(file.file_path)
                    this.documentUrl = url
                    this.documentDrawer = true
                }
            }
        },
        dragUploadFile (fileData, file) {
            /* 拖拽文件选择上传位置 */
            this.uploadData.isdrag = true
            if (fileData.length > 1) {
                this.$message({
                    message: '每次只能上传一个文件',
                    type: 'error'
                })
                return
            }
            this.uploadData.file = fileData[0]
            if (file.children && file.children.length > 0) {
                this.curSelectList = file.children
                this.selectFolderVisible = true
            } else {
                this.uploadData.folderId = file.b_id
                this.uploadByOss()
            }
        },
        selectUploadPath (file) {
            /* 点击上传选择上传位置 */
            this.uploadData.isdrag = false
            if (file.children && file.children.length > 0) {
                this.curSelectList = file.children
                this.selectFolderVisible = true
            } else {
                this.uploadData.folderId = file.b_id
                this.$refs.fileUpload.click()
            }
        },
        selectUploadFile (file) {
            /* 选择本地文件 */
            this.uploadData.folderId = file.b_id
            this.selectFolderVisible = false
            if (this.uploadData.isdrag) {
                this.uploadByOss()
            } else {
                this.$refs.fileUpload.click()
            }
        },
        uploadfileChange (e) {
            /* 当file input选择文件改变时触发 */
            let file = e.target.files[0]
            this.uploadData.file = file
            this.uploadByOss()
        },
        uploadByOss () {
            /* 通过oss上传文件 */
            let file = this.uploadData.file
            ossUpload({
                path: ossPaths.schoolBasedResources,
                file,
                progress: (percent) => {
                    console.log(percent)
                }
            }).then(res => {
                this.uploadToApi(res)
            })
        },
        uploadToApi (data) {
            /* 将oss返回的文件信息储存到后端 */
            let uploadData = {
                folder_info_id: this.uploadData.folderId,
                file_name: data.name,
                file_path: data.url
            }
            this.$api.schoolBasedResourcesApi.uploadFile(uploadData).then(res => {
                if (res.data.Status === true) {
                    this.$message({
                        message: '上传成功',
                        type: 'success'
                    })
                    this.getFolderList()
                } else {
                    this.$message({
                        message: res.data.ResponseError.LongMessage,
                        type: 'error'
                    })
                }
            })
        },
        doShareFile (params) {
            /* 分享文件 */
            this.$api.schoolBasedResourcesApi.fileShare(params).then(res => {
                if (res.data.Status === true) {
                    this.$message({
                        message: '分享成功',
                        type: 'success'
                    })
                    this.$refs.contextMenu.shareVisible = false
                } else {
                    this.$message({
                        message: res.data.ResponseError.LongMessage,
                        type: 'error'
                    })
                }
            })
        },
        updateOrCreateFolder (isFile, params, message) {
            /* 新增或编辑个人文件夹 */
            let updateApi
            if (isFile) { // 对象是文件
                updateApi = this.$api.schoolBasedResourcesApi.updateFileName
                params.folder_info_id = this.breadcrumb[this.breadcrumb.length - 1].parent.b_id
            } else { // 对象是文件夹
                updateApi = this.$api.schoolBasedResourcesApi.CreateOrUpdateFolder
            }
            updateApi(params).then(res => {
                if (res.data.Status === true) {
                    this.$message({
                        message: message,
                        type: 'success'
                    })
                    this.$refs.contextMenu.newFolderVisible = false
                    this.$refs.contextMenu.renameVisible = false
                    this.getFolderList()
                } else {
                    this.$message({
                        message: res.data.ResponseError.LongMessage,
                        type: 'error'
                    })
                }
            })
        },
        handleDeleteFolder (isFile, params) {
            /* 删除文件或文件夹 */
            let deleteApi
            if (isFile) { // 对象是文件
                deleteApi = this.$api.schoolBasedResourcesApi.deleteFile
            } else { // 对象是文件夹
                deleteApi = this.$api.schoolBasedResourcesApi.deleteFolder
            }
            deleteApi(params).then(res => {
                if (res.data.Status === true) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                    if (isFile && this.currentFileList.length === 1) {
                        this.backCrumb(this.breadcrumb.length - 2)
                    }
                    this.$refs.contextMenu.deleteVisible = false
                    this.getFolderList()
                } else {
                    this.$message({
                        message: res.data.ResponseError.LongMessage,
                        type: 'error'
                    })
                }
            })
        },
        showMenu (MouseEvent, currentIsFiLe, row) {
            /* 右键文件夹或文件时触发 */
            if (row) {
                // 右键文件夹或者文件
                if (currentIsFiLe) {
                    this.menuMode = 'file'
                } else {
                    this.menuMode = 'personal'
                }
                this.rightMenuData = row
                // this.rightMenuFolder = []
            } else {
                // 右键空白处
                this.menuMode = 'blank'
                // this.rightMenuFolder = this.currentFileList
                this.rightMenuData = this.breadcrumb[this.breadcrumb.length - 1].parent
            }
            this.menuVisible = false
            this.uploadVisible = false
            this.menuVisible = true
            let coordinate = this.coordinate
            coordinate.menuX = MouseEvent.pageX + 5 + 'px'
            coordinate.menuY = MouseEvent.pageY + 'px'
            coordinate.uploadX = MouseEvent.pageX + 130 + 'px'
            coordinate.uploadY = MouseEvent.pageY + 'px'
            document.addEventListener('click', this.foo) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
        },
        foo () {
            /* 取消鼠标监听事件 菜单栏 */
            this.menuVisible = false
            this.uploadVisible = false
            document.removeEventListener('click', this.foo) // 关掉监听
        },
        showUploadMenu () {
            this.uploadVisible = !this.uploadVisible
        },
        handleSizeChange (val) {
            this.paginationQuery.pageSize = val
            this.getFileList(this.breadcrumb[this.breadcrumb.length - 1].parent)
        },
        handleCurrentChange (val) {
            this.paginationQuery.pageIndex = val
            this.getFileList(this.breadcrumb[this.breadcrumb.length - 1].parent)
        }
    }
}
</script>

<style lang="less" scoped>
.main {
    min-height: 100%;

    .headerNav {
        display: flex;
        justify-content: space-between;
        height: 45px;
        line-height: 45px;
        background: #e7e7e7;

        /deep/ .leftNav {
            padding: 0 20px;
            font-size: 18px;

            .el-breadcrumb {
                font-size: 15px;
                line-height: 45px;
                .el-breadcrumb__item {
                    &:not(:last-child) .el-breadcrumb__inner{
                        cursor: pointer;
                        &:hover {
                            color: #1890FF;
                        }
                    }

                    &:last-child .el-breadcrumb__inner{
                        color: black;
                    }
                }

            }
        }

        .rightNav {
            padding: 0 30px;
            display: flex;

            .feature {
                height: 32px;
                margin: 7px 0 0 35px;
                padding-left: 35px;
                border-left: 1px solid #9e9e9e;
                display: flex;

                div {
                    width: 27px;
                    height: 27px;
                    margin: 3px 5px;
                    text-align: center;
                    line-height: 55px;
                    display: flex;
                    background: #f5f5f5;
                    cursor: pointer;
                    &:hover {
                        border: 1px solid #1890FF;
                    }
                    &:active {
                        opacity: 0.7;
                    }

                    i {
                        display: block;
                        align-self: center;
                        margin: 0 auto;
                        font-size: 18px;
                    }
                }
            }
        }
    }

    .folderCtn{
        min-height: 500px;
    }

}
.icon-sel {
    border: 1px solid #1890FF;
}
</style>
