/**
 * Created by Mai on 2017/6/1.
 */

ProjectController = {
    /* sc: tree_sheet_controller */
    syncDisplayNewNode: function (sc, newNode,callback) {
        TREE_SHEET_HELPER.massOperationSheet(sc.sheet, function () {
            var sels = sc.sheet.getSelections();
            sc.sheet.addRows(newNode.serialNo(), 1);
            TREE_SHEET_HELPER.refreshTreeNodeData(sc.setting, sc.sheet, [newNode], false);
            sc.setTreeSelected(newNode);
            sc.sheet.setSelection(newNode.serialNo(), sels[0].col, 1, 1);
            //不显示到中间
            //sc.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
            cbTools.refreshFormulaNodes();
            if(callback) callback();
        });
    },
    syncDisplayNewNodes: function (sc, newNodes,withOutSelect=false,callback) {//withOutSelect 不需要自动选中，外面自已处理
        TREE_SHEET_HELPER.massOperationSheet(sc.sheet, function () {
            var sels = sc.sheet.getSelections();
            newNodes.sort(function (a, b) {
                let rst = 0;
                if(a.serialNo() > b.serialNo()){
                    rst = 1;
                }
                else {
                    rst = -1;
                }
                return rst;
            });
            let lastNode = null;
            for(let newNode of newNodes){
                sc.sheet.addRows(newNode.serialNo(), 1);
                TREE_SHEET_HELPER.refreshTreeNodeData(sc.setting, sc.sheet, [newNode], false);
                lastNode = newNode
               // sc.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
            }
            if(withOutSelect==false&& lastNode){
                sc.setTreeSelected(lastNode);
                sc.sheet.setSelection(lastNode.serialNo(), sels[0].col, 1, 1);
            }

            cbTools.refreshFormulaNodes();
            if(callback) callback();
        });
    },
    syncDisplayNewRationGljNode:function (sc,newNode) {
        TREE_SHEET_HELPER.massOperationSheet(sc.sheet, function () {
            sc.sheet.addRows(newNode.serialNo(), 1);
            TREE_SHEET_HELPER.refreshTreeNodeData(sc.setting, sc.sheet, [newNode], false);
           // sc.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
            cbTools.refreshFormulaNodes();
        });
    },
    /* addBillsByData: async function (postData, insertFunc) {
        await ajaxPost('/bills/insertBills', { postData });
        // 插入
        const insertData = postData.filter(item => item.updateType === 'create');
        const treeData = insertData.map(item => item.updateData);
        // 插入清单节点
        if (!insertFunc) {
            insertFunc = projectObj.project.Bills.tree.insertByDatas;
        }
        projectObj.project.Bills.tree.insertByDatas(treeData);
        projectObj.project.Bills.datas = projectObj.project.Bills.datas.concat(treeData);
        // 插入主树节点
        const newNodes = projectObj.project.mainTree.insertByDatas(treeData);
        for (const node of newNodes) {
            node.source = projectObj.project.Bills.tree.nodes[projectObj.project.Bills.tree.prefix + node.getID()];
            node.data = node.source.data;
            node.sourceType = projectObj.project.Bills.getSourceType();
        }
        ProjectController.syncDisplayNewNodes(projectObj.mainController, newNodes, true);
        return newNodes;
    }, */
    addBillsByData: async function (postData, isSameDepth = false) {
        await ajaxPost('/bills/insertBills', { postData });
        // 插入
        const insertData = postData.filter(item => item.updateType === 'create');
        const treeData = insertData.map(item => item.updateData);
        // 插入清单节点和主树节点
        projectObj.project.Bills.datas = projectObj.project.Bills.datas.concat(treeData);
        let newNodes;
        if (isSameDepth) {
            const pre = postData.find(item => item.updateType === 'update');
            const preID = pre && pre.updateData.ID || null;
            projectObj.project.Bills.tree.multiInsert(treeData, preID);
            newNodes = projectObj.project.mainTree.multiInsert(treeData, preID);
        } else {
            projectObj.project.Bills.tree.insertByDatas(treeData);
            newNodes = projectObj.project.mainTree.insertByDatas(treeData);
        }
        for (const node of newNodes) {
            node.source = projectObj.project.Bills.tree.nodes[projectObj.project.Bills.tree.prefix + node.getID()];
            node.data = node.source.data;
            node.sourceType = projectObj.project.Bills.getSourceType();
        }
        ProjectController.syncDisplayNewNodes(projectObj.mainController, newNodes, true);
        return newNodes;
    },
    getBillsPostData: function (number) {
        const project = projectObj.project;
        const target = project.getParentTarget(project.mainTree.selected, 'sourceType', project.Bills.getSourceType());
        const baseParentID = target.depth() === 0 ? target.source.getID() : target.source.getParentID();
        const baseNextID = target.depth() === 0 ? -1 : target.source.getNextSiblingID();
        const updateNode = target.depth() === 0 ? target.source.children[target.source.children.length - 1] : target;
        const insertData = [];
        for (let i = 0; i < number; i++) {
            const data = {
                type: billType.BILL,
                projectID: project.ID(),
                ID: uuid.v1(),
                ParentID: baseParentID,
            };
            const pre = insertData[i - 1];
            if (pre) {
                pre.NextSiblingID = data.ID;
            }
            if (i === number - 1) {
                data.NextSiblingID = baseNextID;
            }
            insertData.push(data);
        }
        const postData = insertData.map(item => ({
            updateType: 'create',
            updateData: item
        }));
        if (updateNode) {
            postData.push({ updateType: 'update', updateData: { ID: updateNode.getID(), NextSiblingID: insertData[0].ID } });
        }
        return postData;
    },
    addBills: function (project, sheetController, std) {
        if (!project || !sheetController) { return null; }
        let target = project.getParentTarget(project.mainTree.selected, 'sourceType', project.Bills.getSourceType());
        let newSource = null, newNode = null, parentID, nextSiblingID, nodeParentID, nodeNextSiblingID;
        if (target) {
            if(target.depth() === 0){
                parentID = target.source.getID();
                nextSiblingID = project.Bills.tree.setting.rootId;
                nodeParentID = target.getID();
                nodeNextSiblingID = project.mainTree.rootID();
            } else{
                parentID = target.source.getParentID();
                nextSiblingID = target.source.getNextSiblingID();
                nodeParentID = target.getParentID();
                nodeNextSiblingID = target.getNextSiblingID();
            }
            parentID = target.depth() === 0 ? target.source.getID() : target.source.getParentID();
            nextSiblingID = target.depth() === 0 ? project.Bills.tree.setting.rootId : target.source.getNextSiblingID();

            if (std) {
                let fixedNode = getRootFixedNode(target);
                if(!isFlag(fixedNode.data) || (fixedNode.data.flagsIndex.fixed.flag !== fixedFlag.SUB_ENGINERRING && fixedNode.data.flagsIndex.fixed.flag !== fixedFlag.MEASURE)){
                    return false;
                }
                //焦点行属于分部分项
                if(fixedNode.data.flagsIndex.fixed.flag === fixedFlag.SUB_ENGINERRING){
                    std.type = billType.FX;
                    //焦点行是分部分项
                    let subType = getSubType(target);
                    if(target.sourceType === project.Bills.getSourceType() && target.data.type === billType.DXFY && subType === billType.FB){
                        return false;
                    } else if(target.sourceType === project.Bills.getSourceType() && target.data.type === billType.FB){//焦点行是分部
                        if(!subType || subType === billType.FX){
                            parentID = target.source.getID();
                            nextSiblingID = project.Bills.tree.setting.rootId;
                            nodeParentID = target.getID();
                            nodeNextSiblingID = project.mainTree.rootID();
                        } else{
                            return false;
                        }
                    }
                } else {
                    std.type = billType.BILL;
                }

                let newCode = project.Bills.newFormatCode(std.code);
                newSource = project.Bills.insertStdBills(parentID, nextSiblingID, std, newCode);
            } else {
                newSource = project.Bills.insertBills(parentID, nextSiblingID);
            }
            newNode = project.mainTree.insert(nodeParentID, nodeNextSiblingID, newSource.data.ID);
        } else {
            alert('不可添加清单');
        }

        if (newNode) {
            newNode.source = newSource;
            newNode.sourceType = project.Bills.getSourceType();
            newNode.data = newSource.data;

            this.syncDisplayNewNode(sheetController, newNode);
            return newNode;
        }
        function getSubType(node){
            for(let sub of node.children){
                if(sub.sourceType === project.Bills.getSourceType() && sub.data.type === billType.FB){
                    return billType.FB;
                }
                else if(sub.sourceType === project.Bills.getSourceType() && sub.data.type === billType.FX){
                    return billType.FX;
                }
            }
            return null;
        }
    },
    addRootBill:function (project, sheetController) {//添加大项费用
        if (!project || !sheetController) { return null; }
        this.addSpecialBill(project, sheetController,null, project.mainTree.selected.nextSibling,true,billType.DXFY);
    },
    addFB:function(project, sheetController) {//添加分部
        if (!project || !sheetController) { return null; }
        let selected = project.mainTree.selected;
        if(selected.parent==null&&isFlag(selected.data)&&selected.data.flagsIndex.fixed.flag==fixedFlag.SUB_ENGINERRING){//选中的是分部分项，则插入做为最后一个子项
            return this.addSpecialBill(project, sheetController,selected, null,true,billType.FB);
        }
        if(selected.parent){
            return this.addSpecialBill(project, sheetController,selected.parent, selected.nextSibling,true,billType.FB);
        }

    },
    addFX:function(project, sheetController) {//添加分项
        if (!project || !sheetController) { return null; }
        let selected = project.mainTree.selected;
        console.log(selected);
        if(selected.data.type==billType.FB||(selected.parent==null&&isFlag(selected.data)&&selected.data.flagsIndex.fixed.flag==fixedFlag.SUB_ENGINERRING)){//选中的是分部或者是分部分项工程，则插入做为最后一个子项
            return this.addSpecialBill(project, sheetController,selected, null,true,billType.FX);
        }
        if(selected.parent){
            if(selected.data.type==billType.FX||selected.data.type==billType.BX){
                return this.addSpecialBill(project, sheetController,selected.parent, selected.nextSibling,true,billType.FX);
            }
        }
    },
    addSpecialBill(project,sheetController,parent,nextSibling,isUserAdd,type){
        let newNode = null;
        let b_nexID = nextSibling==null?-1:nextSibling.source.getID();//主树和清单树，对应的树节点ID不一样
        let m_nexID = nextSibling==null?-1:nextSibling.getID();
        let b_parent = parent==null?-1:parent.source.getID();
        let m_parent = parent==null?-1:parent.getID();

        let newSource = project.Bills.insertSpecialBill(b_parent, b_nexID,isUserAdd,type);
        newNode = project.mainTree.insert(m_parent,m_nexID, newSource.data.ID);
        if (newNode) {
            newNode.source = newSource;
            newNode.sourceType = project.Bills.getSourceType();
            newNode.data = newSource.data;
            this.syncDisplayNewNode(sheetController, newNode);
            return newNode;
        }
    },

    addRation: function (project, sheetController, rationType, std) {
        if (!project || !sheetController) { return; }

        let selected = project.mainTree.selected, newSource = null, newNode = null;
        if (selected === null) { return; }

        if (selected.sourceType === project.Bills.getSourceType() && selected.depth() > 0) {
            if (selected.source.children.length > 0) {
                alert('当前清单已有清单子项，不能套用定额。');
            } else if (selected.data.calcBase&&selected.data.calcBase!="") {
                alert('当前有基数计算，不能插入定额/量价/人材机。');
            } else {
                if(selected.data.type === billType.FB){
                    return;
                }
                if (std) {
                    newSource = project.Ration.insertStdRation(selected.source.getID(), null, std);
                    project.ration_glj.addRationGLJ(newSource,std);
                } else {
                    newSource = project.Ration.insertRation(selected.source.getID(),null, rationType);
                }
                newNode = project.mainTree.insert(selected.getID(), selected.tree.rootID(), newSource.ID);
            }
        } else if (selected.sourceType === project.Ration.getSourceType()) {
            if (std) {
                newSource = project.Ration.insertStdRation(selected.source[project.masterField.ration], selected.source, std);
                project.ration_glj.addRationGLJ(newSource,std);
            } else {
                newSource = project.Ration.insertRation(selected.source[project.masterField.ration], selected.source, rationType);
            }
            newNode = project.mainTree.insert(selected.getParentID(), selected.getNextSiblingID(), newSource.ID);
        };
        if (newNode) {
            newNode.source = newSource;
            newNode.sourceType = project.Ration.getSourceType();
            newNode.data = newSource;

            this.syncDisplayNewNode(sheetController, newNode);

        }
    },
    replaceRation: function (project, sheetController, std) {
        if (!project || !sheetController) { return; }

        let selected = project.mainTree.selected, newSource = null, newNode = null;
        if (selected === null) { return; }

        if (  selected.sourceType === project.Ration.getSourceType()) {
            project.Ration.replaceRation(selected.source, std);
            project.ration_glj.addRationGLJ(selected.source, std);
            sheetController.refreshTreeNode([selected], false);
        } else {
            alert('当前焦点行不是定额，无法替换。');
        }
    },
    addNewNodes:function (updateData){
        let controller = projectObj.mainController;
        let Bill = projectObj.project.Bills;
        let newAddNode = [];
        let newRationNodes = [];
        for(let nb of updateData.bills.add){
            let newSource = Bill.tree.insertByData(nb, nb.ParentID, -1, true);//按顺序插入的情况下，nextID为-1，树节点
            let newNode = projectObj.project.mainTree.insert(nb.ParentID, -1, newSource.data.ID);
            newNode.source = newSource;
            newNode.sourceType = Bill.getSourceType();
            newNode.data = newSource.data;
            controller.sheet.addRows(newNode.serialNo(), 1);
           // controller.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
            newAddNode.push(newNode);
            Bill.datas.push(nb);
        }
        for(let nr of updateData.ration.add){
            let newNode = projectObj.project.mainTree.insert(nr.billsItemID, -1, nr.ID);
            newNode.source = nr;
            newNode.sourceType = projectObj.project.Ration.getSourceType();
            newNode.data = nr;
            controller.sheet.addRows(newNode.serialNo(), 1);
           // controller.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
            newAddNode.push(newNode);
            newRationNodes.push(newNode);
            projectObj.project.Ration.datas.push(nr);
        }
        TREE_SHEET_HELPER.refreshTreeNodeData(controller.setting, controller.sheet, newAddNode, false);
        return newRationNodes;
    }
/*    addVolumePrice: function (project, sheetController) {
        if (!project || !sheetController) { return null; }

        var selected = project.mainTree.selected;
        var newSource = null, newNode = null;
        if(selected === null) {
            return;
        }

        if (selected.sourceType === project.Bills.getSourceType() && selected.source.children.length === 0) {
            newSource = project.VolumePrice.insertVolumePrice(selected.source.getID());
            newNode = project.mainTree.insert(selected.getID(), selected.tree.rootID());
        } else if (selected.sourceType === project.Ration.getSourceType() || selected.sourceType === project.VolumePrice.getSourceType()) {
            newSource = project.VolumePrice.insertVolumePrice(selected.source[project.masterField.volumePrice], selected.source);
            newNode = project.mainTree.insert(selected.getParentID(), selected.getNextSiblingID());
        }
        if (newNode) {
            newNode.source = newSource;
            newNode.sourceType = project.VolumePrice.getSourceType();
            newNode.data = newSource;

            this.syncDisplayNewNode(sheetController, newNode);
        }
    },*/
/*    calculateAll: function (project, sheetController, CalcType) {
        this.project.setCalcFlag(CalcType);
        let calc = new BillsCalcHelper(project);
        calc.calcAll();
        sheetController.showTreeData();
        project.Bills.updateAll();
        calc = null;
    }*/
}
