const copyProject = (function () {
    const projectType = commonConstants.projectType;
    let curCopySelTree = null;  //拷贝工程建设项目选项树
    function setEng(projID){
        let engQuery = {$or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], projType: projectType.Engineering, userID: userID, ParentID: projID};
        CommonAjax.post('/pm/api/getProjectsByQuery', {user_id: userID, query: engQuery, options: '-_id -property'}, function (rstData) {
            $('#copyShare_selectEng').empty();
            for(let eng of rstData){
                let opt = $('<option>').val(eng.ID).text(eng.name);
                $('#copyShare_selectEng').append(opt);
            }
        });
    }

    function getFileHierarchyInfo(treeData){
        curCopySelTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1});
        curCopySelTree.loadDatas(treeData);
        let items = curCopySelTree.items;
        let rst = [];
        function getFileHierarchyName(node){
            let nodeName = node.data.name;
            let name = [];
            while (node.parent){
                name.push(node.parent.data.name ? node.parent.data.name : '');
                node = node.parent;
            }
            name = name.reverse();
            name.push(nodeName);
            return name.join('\\');
        }
        for(let node of items){
            if(node.children.length === 0 ){//project
                rst.push({ID: node.data.ID, fileHierarchyName: getFileHierarchyName(node)})
            }
        }
        return rst;
    }

 //设置拷贝工程下拉选择
    //@return {void}
    function setCopyModal(){
        //获取建设项目
        let projQuery = {$or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], projType: {$in: [projectType.Project, projectType.Folder]}, userID: userID};
        CommonAjax.post('/pm/api/getProjectsByQuery', {user_id: userID, query: projQuery, options: '-_id'}, function (rstData) {
            let fileHierarchyData = getFileHierarchyInfo(rstData);
            $('#copyShare_selectProj').empty();
            for(let proj of fileHierarchyData){
                let opt = $('<option>').val(proj.ID).text(proj.fileHierarchyName);
                $('#copyShare_selectProj').append(opt);
            }
            //初始选择
            if(fileHierarchyData.length > 0){
                setEng(fileHierarchyData[0].ID);
            }
        });
    }

//拷贝分享的工程
    //@param {Object}selected {Number}parentID @return {void}
    async function copyShareProject(projectInfo, projID, engID){
        try {
            if(!engID || !projectInfo){
                return;
            }
            let copyMap = {copy: null, update: null};
            let newName = $('#copyShare_name').val();
            if (!newName) {
                $('#copyShareTender-info').text('单位工程名称不可为空');
                $('#copyShareTender-info').show();
                return;
            }
            //获取单项工程的单位工程
            let tenderQuery = {$or: [{deleteInfo: null}, {'deleteInfo.deleted': false}], userID: userID, ParentID: engID};
            const rstData = await ajaxPost('/pm/api/getProjectsByQuery', {user_id: userID, query: tenderQuery, options: '-_id -property'}, false, 10000);
            let updateTender = null;
            for(let tender of rstData){
                if(tender.name === newName){
                    $('#copyShareTender-info').text('已存在同名单位工程');
                    $('#copyShareTender-info').show();
                    return;
                }
                if(tender.NextSiblingID == -1){
                    updateTender = tender;
                }
            }
            //更新前节点
            if(updateTender){
                copyMap.update = {query: {ID: updateTender.ID}};
            }
            //拷贝
            let copyData = {
                userID: userID,
                ID: projectInfo.ID,
                NextSiblingID: -1,
                ParentID: engID,
                name: newName,
                shareInfo: [],
                compilation: projectInfo.compilation,
                createDateTime: projectInfo.createDateTime,
                fileVer: projectInfo.fileVer ? projectInfo.fileVer : '',
                projType: projectInfo.projType,
                property: {},
                recentDateTime: projectInfo.recentDateTime,
                fullFolder: projectInfo.fullFolder
            };
            copyData.property.rootProjectID = projID;
            copyMap.copy = {document: copyData};
            $('#copyShare').modal('hide');
            $.bootstrapLoading.progressStart('拷贝项目', true);
            $("#progress_modal_body").text('正在拷贝项目，请稍候……');
            await ajaxPost('/pm/api/copyProjects', {projectMap: copyMap, user_id: userID, tenderCount: 1});
            const compilationID = projectInfo.compilation;
            importProcessChecking(null, null, ()=> socket.emit('pmTreeChange', { userID, compilationID}));
        } catch (err) {
            alert(err);
        }

    }

    async function importProcessChecking(key, processingFunc = null, completeFunc = null, immediately = false) {
        let count = 0;
        immediately ? checking() : setTimeout(checking, 2000);
        async function checking() {
            let result = await ajaxPost("/pm/api/importProcessChecking", { key: key, user_id: userID });
            if (result.error == 1) {
                let message = result.msg ? result.msg : result.message;
                setTimeout(function () {
                    $.bootstrapLoading.progressEnd();//不做这个的话太快，页面不会自动关闭
                }, 500);
                alert(message);
                if (completeFunc) {
                    completeFunc(result.data);
                }
            } else if (result.error == 0) {
                if (result.status == "processing") {
                    // 只调用一次
                    if (processingFunc && count === 0) {
                        processingFunc(result);
                    }
                    count++;
                    setTimeout(checking, 2000);
                } else if (result.status == "complete") {
                    if (completeFunc) {
                        completeFunc(result.data);
                    }
                    $.bootstrapLoading.progressEnd();
                    //refreshAllPage();
                }
            }
        }
    }

    function eventListener(){
           //关闭拷贝工程
        $('#copyShare').on('hidden.bs.modal', function () {
            $('#copyShareProj-info').hide();
            $('#copyShareEng-info').hide();
        });
        //打开拷贝工程
        $('#copyShare').on('shown.bs.modal', function () {
            setCopyModal();
            //更改显示名称
            $('#copyShare_name').val(projectObj.project.projectInfo.name);
        });
         //拷贝工程改变选择建设项目
         $('#copyShare_selectProj').change(function () {
            $('#copyShareProj-info').hide();
            $('#copyShareEng-info').hide();
            $('#copyShareTender-info').hide();
            let curSelID = $(this).select().val();
            setEng(parseInt(curSelID));
        });
        //拷贝工程改变选择单项工程
        $('#copyShare_selectEng').change(function () {
            $('#copyShareTender-info').hide();
        });


         //确认拷贝
         $('#copyShare_confirm').click(function () {
            let selProj = $('#copyShare_selectProj').select().val();
            if(!selProj){
                $('#copyShareProj-info').show();
                return;
            }
            //目标建设项目的计税方法与单位工程的一致时，才可拷贝
            if (curCopySelTree) {
                let projectNode = curCopySelTree.nodes[curCopySelTree.prefix + selProj];
                if (!projectNode || !projectNode.data.property || projectNode.data.property.taxType != projectObj.project.property.taxType){
                    alert('当前单位工程计税方法与目标建设项目不一致，不可复制。');
                    return;
                }
            }
            let selEng = $('#copyShare_selectEng').select().val();
            if(!selEng){
                $('#copyShareEng-info').show();
                return;
            }
            copyShareProject(projectObj.project.projectInfo, parseInt(selProj), parseInt(selEng));
        });
    }
    return{eventListener}
})()
$(document).ready(function () {
    console.log("hehe")
    copyProject.eventListener();
});