//文档管理,语义分析管理 目录的逻辑
export default {
    directives: {
        //拖拽左侧目录栏
        drag(el, bindings) {
            el.onmousedown = function (e) {
                let init = e.clientX;
                let left = $('#left')[0];
                let initWidth = left.offsetWidth;
                document.onmousemove = function (e) {
                    let end = e.clientX;
                    let newWidth = end - init + initWidth;
                    left.style.width = newWidth + 'px';
                };
                document.onmouseup = function () {
                    document.onmousemove = document.onmouseup = null;
                    e.releaseCapture && e.releaseCapture();
                };
                e.setCapture && e.setCapture();
                return false;
            };
        },
    },
    data() {
        return {
            model: 'list', //当前是展示目录列表还是文档详情
            searchTitle: '', //搜索文字
            searchOptions: [], //搜索结果
            listData: [], //目录信息
            expandKeys: [], //当前展开的目录
            catalogList: [], //列表信息
            selectNodeKey: '', //当前选择的节点Id
            selectNode: {}, //当前选择的节点
        }
    },
    methods: {
        //节点展开时触发
        handleNodeExpand(data) {
            !this.expandKeys.includes(data.nodeKeyId) && this.expandKeys.push(data.nodeKeyId)
        },
        //节点收起时触发
        handleNodeCollapse(data) {
            const index = this.expandKeys.findIndex(i => i === data.nodeKeyId)
            index !== -1 && this.expandKeys.splice(index, 1)
        },
        //节点改变
        nodeChange(data, node) {
            const model = node.level === 1 ? 'list' : 'file'
            this.changeModel(model, data)
        },
        //切换展示模式
        changeModel(model, data) {
            //console.log('data',data)
            this.model = model
            this.$refs.catalogTree.setCurrentKey(data.nodeKeyId)
            this.selectNodeKey = this.$refs.catalogTree.getCurrentKey()
            this.selectNode = this.$refs.catalogTree.getCurrentNode()
            if (model === 'list') {
                //get list detail
                this.catalogList = data.children || []
                //因为不确定是哪个页面,所以两个都设置为空
                this.docInfo = {}
                this.semanticInfo = {}
            } else {
                //get file detail
                this.getDetail(data)
            }
        },
        //节点操作
        clickNodeHandle(type, data, model) {
            const handleMap = {
                'edit': this.handleEdit,
                'del': this.handleDelete
            }
            handleMap[type](model ? model : this.model, data)
        },
        //列表项操作
        handleOperateCommand({
            key,
            data
        }) {
            this.clickNodeHandle(key, data, 'file')
        },
        //编辑节点
        handleEdit(model, data) {
            //根据model判断编辑list还是file
            if (model === 'list') {
                this.classifyForm = {
                    classify_id: data.nodeKeyId,
                    classify_name: data.label,
                    /* classify_img: data.CoverImg */
                }
                this.isModifyClassifyShow = true
            } else {
                //打开编辑文档页面(新增一页?)
                /* this.$router.push({
                  path:'/editDocument',
                  query:{fileId:data.nodeKeyId}
                }) */
                //window.open(`/editDocument?fileId=${data.nodeKeyId}`)
                this.toPage('editFile', {
                    fileId: data.nodeKeyId
                })
            }

        },
        //删除节点
        handleDelete(model, data) {
            //根据model判断删除list还是file
            if (model === 'list') {
                this.deleteList(data)
            } else {
                this.deleteFile(data)
            }
        },
        deleteList(data) {
            if (this.catalogList && this.catalogList.length !== 0) {
                this.$message.error('该分类下有关联文档,不允许删除')
                return
            }
            this.$confirm('删除操作不可恢复，确认删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () => {
                //delete list
                await this.deleteClassify(data)
                //清空currentKey 和 catalogList
                this.clearNodeInfo()
                //done getList
                this.getListData()
            }).catch(() => {}).finally(() => {})
        },
        deleteFile(data) {
            if (data.UseNum > 0) {
                this.$message.error('已关联对比结果，不允许删除')
                return
            }
            this.$confirm('删除操作不可恢复，确认删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () => {
                //delete file
                await this.deleteDocument(data)
            }).catch(() => {}).finally(() => {})
        },
        async chooseDataClassify(data) {
            await this.getListData()
            //done 选中所属目录
            const catalog = this.listData.find(item => {
                return Number(item.nodeKeyId) === data.parentId
            })
            catalog && this.nodeChange(catalog, {
                level: 1
            })
            this.handleNodeExpand({
                nodeKeyId: data.parentId + ''
            })
        },
        clearNodeInfo() {
            if (this.model === 'list') {
                this.catalogList = []
            }
            this.selectNodeKey = ''
            this.selectNode = {}
        },
        clearForm() {
            this.$refs.formRef && this.$refs.formRef.resetFields();
            this.classifyForm = {}
            this.isModifyClassifyShow = false;
        },
        /*tree 节点移动相关 */
        //判断节点是否能拖拽 绑定allow-drag
        checkAllowDrag(node) {
            //只有二级节点可以拖拽
            return node.level === 2
        },
        //判断节点是否能放入 绑定allow-drop
        /**
         * 
         * @param {node} draggingNode 拖拽的节点
         * @param {node} dropNode 要放入的节点
         * @param {String} type 放入的类型 before after inner 
         */
        checkAllowDrop(draggingNode,dropNode,type) {
            //一级节点可放入,inner
            //二级节点可放入,before after
            return (dropNode.level===1&&type==='inner')||(dropNode.level===2&&type!=='inner')
        },
        //节点放入时触发 绑定node-drop
        /**
         * 
         * @param {node} draggingNode 拖拽的节点
         * @param {node} dropNode 要放入的节点
         * @param {String} type 放入的类型 before after inner 
         */
        handleDropOver(draggingNode, dropNode, type) {
            //确保draggingNode为二级节点
            if(draggingNode.level!==2) return 
            const draggingNodeId = draggingNode.data.nodeKeyId.split('_')[1]
            let preLeafId=0,//同一目录下,前一个文档的id,若拖拽至不同目录或拖拽至第一个,该值为0
                nextLeafId=0,//同一目录下,后一个文档的id,若拖拽至不同目录或拖拽至最后一个,该值为0
                GroupId=0, //文档所属目录id,若拖拽至不同目录,则为新目录的目录id
                group=[] //文档所属目录
            //dropNode为一级节点时
            if(dropNode.level===1){
                preLeafId=0
                nextLeafId=0
                //取nodeKeyId是为了兼容文档列表和文档对比列表,它们的目录id字段不同
                //文档列表(SaDocClassifyId) 文档对比列表(SaCompareClassifyId)
                GroupId = dropNode.data.nodeKeyId
            }
            //dropNode为二级节点时
            if(dropNode.level===2){
                //确定GroupId,并找到对应目录
                GroupId = draggingNode.data.parentId===dropNode.data.parentId
                    ?draggingNode.data.parentId
                    :dropNode.data.parentId
                group = this.listData.find(i=>Number(i.nodeKeyId)===GroupId)
                //确定dropNode在group里的位置
                let targetIndex = group.Children.findIndex(i=>i.nodeKeyId===dropNode.data.nodeKeyId)
                //拖动后,draggingNode在该目录下置顶
                if(type==='before'&&targetIndex===0){
                    preLeafId=0
                    //二级节点的nodeKeyId格式为 children_xxx,只需要xxx部分
                    nextLeafId=group.Children[targetIndex].nodeKeyId.split('_')[1]
                }
                //拖动后,draggingNode在该目录下置底
                if(type==='after'&&targetIndex===group.children.length-1){
                    preLeafId = group.Children[targetIndex].nodeKeyId.split('_')[1]
                    nextLeafId=0
                }
                //拖动后,draggingNode不在目录第一个
                if(type==='before'&&targetIndex!==0){
                    preLeafId = group.Children[targetIndex-1].nodeKeyId.split('_')[1]
                    nextLeafId = group.Children[targetIndex].nodeKeyId.split('_')[1]
                }
                if(type==='after'&&targetIndex!==group.children.length-1){
                    preLeafId = group.Children[targetIndex].nodeKeyId.split('_')[1]
                    nextLeafId = group.Children[targetIndex+1].nodeKeyId.split('_')[1]
                }
            }
            //调移动接口
            console.table([{
                'GroupId':Number(GroupId),//21
                'preLeafId':Number(preLeafId),//60
                'nextLeafId':Number(nextLeafId),//58
                'draggingNode':draggingNode.data.nodeKeyId+','+draggingNode.data.parentId,
                'dropNode':dropNode.data.nodeKeyId+','+dropNode.data.parentId,
                'type':type //after
            }])
            if (this.$route.path === '/documentPage'){
                this.moveDocument({
                    SaDocId:Number(draggingNodeId),
                    SaDocClassifyId:Number(GroupId),
                    PrevSaDocId:Number(preLeafId),
                    NextSaDocId:Number(nextLeafId)
                })
            }else{
                this.moveCompare({
                    SaCompareClassifyId:Number(GroupId),
                    SaCompareId:Number(draggingNodeId),
                    PrevSaCompareId:Number(preLeafId),
                    NextSaCompareId:Number(nextLeafId)
                })
            }

        },

    },
    async mounted() {
        await this.getListData()
        if (this.listData.length) {
            const fileClassify = sessionStorage.getItem('fileClassify') || ''
            const fileId = sessionStorage.getItem('fileId') || ''
            //添加/编辑文档or文档对比完成时,需要回到列表页并选中对应文档or文档对比
            if (fileClassify.length && fileId.length) {
                this.handleNodeExpand({
                    nodeKeyId: fileClassify
                })
                if (this.$route.path === '/documentPage')
                    this.nodeChange({
                        SaDocId: Number(fileId),
                        nodeKeyId: `children_${fileId}`
                    }, {
                        level: 2
                    })
                else
                    this.nodeChange({
                        SaCompareId: Number(fileId),
                        nodeKeyId: `children_${fileId}`
                    }, {
                        level: 2
                    })
                sessionStorage.removeItem('fileClassify')
                sessionStorage.removeItem('fileId')
            }
        }
    }
}