/**
 * Created by zhang on 2018/1/22.
 */
let zlfb_object={
    sectionInfo:null,
    getSectionInfo:function () {
        let controller = projectObj.mainController, project = projectObj.project;
        let Bill = project.Bills;
        let FBFX = Bill.getFBFXNode(controller);//取分部分项工程节点;
        let all_sub_nodes=[],FB_nodes =[],FX_nodes =[], query={};
        let codeMap = {};
        let reorganize = false;
        controller.tree.getAllSubNode(FBFX,all_sub_nodes);//取分部分项工程节点下的所有节点，不包括定额和工料机节点;
        for(let tem_node of all_sub_nodes){
            if(tem_node.sourceType==Bill.getSourceType()){
                if(tem_node.data.type == billType.FB){
                    FB_nodes.push(tem_node);
                }
                if(tem_node.data.type == billType.FX||tem_node.data.type == billType.BX){
                    FX_nodes.push(tem_node);
                    let l_code = zlfb_object.getLibCode(tem_node.data.code);
                    if(tem_node.data.billsLibId&&l_code!=false){
                        reorganize = true;
                        if(codeMap[l_code]){
                            codeMap[l_code].push(tem_node);
                        }else {
                            codeMap[l_code]=[tem_node];
                        }
                        if(query[tem_node.data.billsLibId]){
                            query[tem_node.data.billsLibId][l_code]=true;
                        }else {
                            query[tem_node.data.billsLibId]={};
                            query[tem_node.data.billsLibId][l_code]=true;
                        }
                    }
                }
            }
        }
        if(reorganize==true){
            zlfb_object.sectionInfo = {
                'codeMap':codeMap,
                'FB_nodes':FB_nodes,
                'FX_nodes':FX_nodes
            }
            CommonAjax.post('/bills/getSectionInfo',query,function (data) {
                if(data){
                    zlfb_object.sectionInfo.fxMap = data.fxMap;
                    zlfb_object.sectionInfo.sectionMap = data.sectionMap;
                }
                $("#zlfb").modal({show:true});
            });
        }else {
            $("#zlfb").modal({show:true});
        }
    },
    getLibCode:function (billCode) {//根据清单编号得到清单库中的编号
        if(billCode&&billCode.length>=9){
            return billCode.substr(0,9);
        }else {
            return false;
        }
    },
    reorganizeNodes:function () {
        let me = this;
        let controller = projectObj.mainController, project = projectObj.project;
        let Bill = project.Bills;
        let FBFX = Bill.getFBFXNode(controller);//取分部分项工程节点;
        let resort = true,recode=false,first=$('#bill_first').prop('checked');//清单排序和重新编码放到另外的页面
        let second =$('#bill_second').prop('checked'), third =$('#bill_third').prop('checked');
        let needSelf = first==true||second==true||third==true;//需要补充分部节点;
        if(me.sectionInfo){
            let FX_nodes =me.sectionInfo.FX_nodes,fxMap = me.sectionInfo.fxMap,FB_nodes =me.sectionInfo.FB_nodes;
            let codeMap = {},sectionNodeMap={},allNewNode=[],updateData={},newDataMap={};
            let first_FX_ID = -1;
            if(FB_nodes.length>0){
                updateData.delete = me.getDeleteData(FB_nodes);
            }
            Bill.deleteAllSubNodes();//在造价书树结构上先删除所有节点
            if(resort){
                FX_nodes = _.sortBy(FX_nodes,'data.code');
            }
            for(let tem_node of FX_nodes){
                let isStd = true;//是标准工料机
                let l_code = me.getLibCode(tem_node.data.code);
                let parentNode = FBFX;
                let newCode = tem_node.data.code;
                if(l_code!=false&&fxMap[l_code]){//能找到说明是标准工料机
                    let tem_sectionInfo = fxMap[l_code].sectionInfo;
                    if(first&&tem_sectionInfo['first']){//需要专业分部标题
                        parentNode= me.createSectionNode(sectionNodeMap,tem_sectionInfo['first'],parentNode,allNewNode,newDataMap,true);
                    }
                    if(second&&tem_sectionInfo['second']){//需要章分部标题
                        let isRoot = first==true?false:true;
                        parentNode= me.createSectionNode(sectionNodeMap,tem_sectionInfo['second'],parentNode,allNewNode,newDataMap,isRoot);
                    }
                    if(third&&tem_sectionInfo['third']){//需要章分部标题
                        let isRoot = first==true||second==true?false:true;
                        parentNode= me.createSectionNode(sectionNodeMap,tem_sectionInfo['third'],parentNode,allNewNode,newDataMap,isRoot);
                    }
                    if(recode==true){//需要重新编号
                        if(codeMap[l_code]){
                            codeMap[l_code]+=1;
                        }else {
                            codeMap[l_code]=1;
                        }
                        newCode = l_code+me.getEndCode(codeMap[l_code],3);
                    }
                }else {//自定义分项
                    if(needSelf==true){
                        parentNode= me.createSectionNode(sectionNodeMap,"customer",parentNode,allNewNode,newDataMap,true);
                    }
                    isStd = false;
                }
                let nextID=-1;
                if(needSelf==false){//如果章节信息三项都不勾选的情况下，要插在自定义分项前
                    if(isStd==false&&first_FX_ID==-1){//如果是自定义分项，并且是第一个，要记住ID
                        first_FX_ID = tem_node.getID();
                    }
                   if(isStd==true){//如果是标准的分部，则要插入到第一个自定义分部前面
                       nextID = first_FX_ID;
                    }
                }
                let newFXNode  = controller.tree.insert(parentNode.getID(), nextID,tem_node.getID());
                let newSource = Bill.tree.insertByData(tem_node.data,parentNode.getID(), nextID, true);
                newFXNode.source = newSource;
                newFXNode.sourceType = project.Bills.getSourceType();
                newFXNode.data = newSource.data;
                allNewNode.push(newFXNode);
                newFXNode.data.code = newCode;
                newFXNode.data.ParentID = parentNode.getID();
                newFXNode.data.NextSiblingID=nextID;
                newDataMap[newFXNode.getID()]={
                    code:newCode,
                    ParentID:parentNode.getID(),
                    NextSiblingID:nextID
                }
                if(newFXNode.preSibling){
                    newFXNode.preSibling.data.NextSiblingID = newFXNode.getID();
                    newDataMap[newFXNode.preSibling.getID()].NextSiblingID=newFXNode.getID();
                }
                //生成定额或工料机节点
                if(tem_node.children.length>0){
                    me.addSubNode(newFXNode,tem_node.children,allNewNode,controller)
                }
            };
            me.submitRequest(newDataMap,allNewNode,updateData,FBFX,controller);
        }
    },
    ZLQD:async function(){//只清单排序或者重新编码
        //
        let me = this;
        let selected = projectObj.project.mainTree.selected;
        let resort = $('#bill_resort').prop('checked'),recode=$('#bill_recode').prop('checked')
        let startNum = parseInt($('#bill_recode_start').val());
        let FBNodes = [],updateMap = {},codeMap={};
        let recoverMap = {};//排序失败后用来恢复原状的缓存
        let tree = projectObj.mainController.tree;
        if(resort||recode){
            //先找出需要排序和重新编码的节点
            for(let node of tree.items){
                if(node.sourceType===ModuleNames.bills){
                    if(node.data.type == billType.FB && node.children.length > 1){//有两个以上的才需要排序
                        let subType = node.children[0].data.type;
                        if(subType ===  billType.FX || subType ===  billType.BX){
                            FBNodes.push(node);
                            recoverMap[node.data.ID] = node.children;
                        } 
                   } 
                } 
            }   
            try {
                if(resort){//如果需要重新排序  -- 重新排序还必须得先改变缓存，如果勾选了重新编码，顺序依赖于排好序的清单
                    for(let FB of FBNodes){
                        me.resortChildren(FB,updateMap)
                    }
                    tree.sortTreeItems(tree);
                }
        
                if(recode){
                    if(!(startNum >= 1)){
                        return alert("起始编码必须大于1！")
                    } 
                    for(let node of tree.items){
                        if(node.data.billsLibId){
                            let l_code = me.getLibCode(node.data.code); 
                            if(l_code !== false){
                                if(codeMap[l_code]){
                                    codeMap[l_code]+=1;
                                }else {
                                    codeMap[l_code]=startNum;
                                }
                                newCode = l_code+me.getEndCode(codeMap[l_code],3);
                                if(updateMap[node.data.ID]){
                                    updateMap[node.data.ID].data.code = newCode;
                                }else{
                                    updateMap[node.data.ID] =  {
                                        type:'bills',
                                        data:{
                                               projectID:node.data.projectID,
                                               ID:node.data.ID,
                                               code :newCode
                                            } 
                                        };
                                }
                            }
                        }
                    }

                }
        
                let datas = [];
                for(let ID in updateMap){
                    datas.push(updateMap[ID]);
                }
               if(datas.length > 0) await projectObj.project.syncUpdateNodesAndRefresh(datas);

               projectObj.mainController.refreshTreeNode(FBNodes,true);
               this.refreshVisable(FBNodes);
               let sel = projectObj.mainController.sheet.getSelections()[0];
               sel.row = selected.serialNo();
               projectObj.mainController.sheet.setSelection(sel.row,sel.col,sel.rowCount,sel.colCount);
               projectObj.mainController.setTreeSelected(selected);
            } catch (error) {
                alert('清单排序/重新编码失败，请重试！');
                console.log(error);
                //恢复排序
                for(let FB of FBNodes){
                    me.resortChildren(FB,{},recoverMap[FB.data.ID]);
                }
                tree.sortTreeItems(tree);
                this.refreshVisable(FBNodes);
            } 
         
         
        }
    },
    refreshVisable:function (FBNodes) {
      let sheet =  projectObj.mainController.sheet;
      let tree = projectObj.mainController.tree;
      sheet.suspendPaint();
      sheet.suspendEvent();
      for(let pnode of FBNodes){
        TREE_SHEET_HELPER.refreshChildrenVisiable(sheet,tree,pnode,pnode.serialNo());
        for(let node of pnode.children){
            TREE_SHEET_HELPER.refreshChildrenVisiable(sheet,tree,node,node.serialNo());
        }  
      } 
      sheet.resumeEvent();
      sheet.resumePaint();  
    },


    resortChildren:function(node,updateMap,recoverChildren){
        if(recoverChildren){
            node.children = recoverChildren;
        }else{
            node.children = _.sortBy(node.children,'data.code');
        } 
       for(let i=0;i<node.children.length;i++){
           let subNode = node.children[i];
           let tem = {
            type:'bills',
            data:{
                projectID:subNode.data.projectID,
                ID:subNode.data.ID,
                } 
            }; 
            if(i===0){
                subNode.preSibling == 0;
            }else{
                subNode.preSibling = node.children[i-1];
            }

           if(i == node.children.length-1){//如果是最后一个节点
            tem.data.NextSiblingID=-1;
            subNode.nextSibling = null
           }else{
            tem.data.NextSiblingID= node.children[i+1].data.ID;
            subNode.nextSibling = node.children[i+1];
           }
          updateMap[subNode.data.ID] = tem
       } 
    },

    addSubNode:function (parentNode,oldChildren,allNewNode,controller) {
        for(let c of oldChildren){
            let newChild = controller.tree.insert(parentNode.getID(), -1,c.getID());
            newChild.source = c.data;
            newChild.sourceType = c.sourceType;
            newChild.data = c.data;
            allNewNode.push(newChild);
            if(c.children.length>0){
                zlfb_object.addSubNode(newChild,c.children,allNewNode,controller);
            }
        }
    },
    getDeleteData:function (FB_nodes) {
        let fbIDs=[];
        for(let fb of FB_nodes){
            fbIDs.push(fb.getID());
        }
        return fbIDs;
    },
    createSectionNode:function (sectionNodeMap,ID,parentNode,allNewNode,newDataMap,isRoot) {
        let sectionMap = zlfb_object.sectionInfo.sectionMap;
        let controller = projectObj.mainController;
        if(sectionNodeMap[ID]){//如果这个节点已经存在
            parentNode = sectionNodeMap[ID];
        }else {//不存在就生成一个
            let nodeID = uuid.v1();
            let nextID=-1;
            if(isRoot==true&&ID!='customer'&&sectionNodeMap['customer']){//如果自定义分部存在，插入到自定文分部前面
                nextID=sectionNodeMap['customer'].getID();
            }
            let newNode  = controller.tree.insert(parentNode.getID(), nextID,nodeID);
            let data ={
                ID:nodeID,
                projectID:parseInt(projectObj.project.ID()),
                ParentID:parentNode.getID(),
                NextSiblingID:nextID,
                type:billType.FB
            };
            if(newNode.preSibling){
                newDataMap[newNode.preSibling.getID()].NextSiblingID=newNode.getID();
                newNode.preSibling.data.NextSiblingID=newNode.getID();
            }
            if(ID=='customer'){
                data.name = '补充分部';
            }else {
                if(sectionMap[ID]==undefined){
                    console.log(ID);
                }
                data.code = sectionMap[ID].code;
                data.name = sectionMap[ID].name;
            }

            let newSource = projectObj.project.Bills.tree.insertByData(data,parentNode.getID(), nextID, true);
            newNode.source = newSource;
            newNode.sourceType = projectObj.project.Bills.getSourceType();
            newNode.data = newSource.data;
            sectionNodeMap[ID]=newNode;
            parentNode = newNode;
            allNewNode.push(newNode);
            newDataMap[nodeID]=data;
        }
        return parentNode;
    },
    getEndCode:function (number,length) {
        let preString = '000000000000';
        preString = preString+number;
        return preString.substr(preString.length-length,length);
    },
    submitRequest:function(newDataMap,allNewNode,updateData,FBFX,controller){
        for(let ID in newDataMap){ //生成更新数据
            if(newDataMap[ID].type==billType.FB){//分部类型是插入
                if(updateData['create']){
                    updateData['create'].push(newDataMap[ID]);
                }else {
                    updateData['create']=[newDataMap[ID]];
                }
            }else {
                if(updateData['update']){
                    let u_data = {
                        ID:ID,
                        data:newDataMap[ID]
                    };
                    updateData['update'].push(u_data);
                }else {
                    let u_data = {
                        ID:ID,
                        data:newDataMap[ID]
                    };
                    updateData['update'] = [u_data];
                }
            }
        }
        updateData.projectID = FBFX.data.projectID;
        updateData.user_id = userID;
        $.bootstrapLoading.start();
        CommonAjax.post('/bills/reorganizeFBFX',updateData,async function (data) {
            $.bootstrapLoading.end();
            //更新前端缓存
            let billDatas = projectObj.project.Bills.datas;
            let quantity_detail_datas = projectObj.project.quantity_detail.datas;
            let mainTree = projectObj.mainController.tree;
            if(updateData.delete && updateData.delete.length > 0){//删除
                for( let d_ID of updateData.delete){
                    _.remove(billDatas,{'ID':d_ID});
                    _.remove(quantity_detail_datas,{'billID':d_ID});
                }
            }
            if(updateData.update && updateData.update.length > 0){//更新数据
                for(let u_data of updateData.update){
                    let m_node = mainTree.findNode(u_data.ID);
                    if(m_node){
                        let m_data = m_node.data;
                        for(let u_key in u_data.data){
                            m_data[u_key] = u_data.data[u_key];
                        }
                    }
                }
            }
            if(updateData.create && updateData.create.length > 0){
                for(let n_data of updateData.create){
                    billDatas.push(n_data);
                }
            }
            controller.sheet.addRows(1, allNewNode.length);
            for(let c of FBFX.children){
                TREE_SHEET_HELPER.massOperationSheet(controller.sheet, function () {
                    TREE_SHEET_HELPER.refreshTreeNodeData(controller.setting, controller.sheet, [c], true);
                    controller.sheet.showRow(1, GC.Spread.Sheets.VerticalPosition.center);
                });
            }
            mainTree.preSelected = null;
            let selected = mainTree.findNode(mainTree.selected.getID());
            if(!selected){
                selected = controller.tree.items[0];
            }
            let sel = controller.sheet.getSelections()[0];
            sel.row = selected.serialNo();
            controller.sheet.setSelection(sel.row,sel.col,sel.rowCount,sel.colCount);
            controller.setTreeSelected(selected);
            cbTools.refreshFormulaNodes();
            projectObj.project.installation_fee.calcInstallationFee(function () {
                //重新计算
                projectObj.project.Bills.getEngineeringCostNode(controller).changed = true;
                projectObj.project.calcProgram.calcAllNodesAndSave();
            });
            await OVER_HEIGHT.reCalcOverHeightFee();
        },function () {
            //errorCallback
        });
    }
}


$(function () {

    $('#zlfb_confirm').click(function (){
        $("#zlfb").modal('hide');
        zlfb_object.reorganizeNodes();
    });
    $('#zlfb').on('hidden.bs.modal', function (e) {
        zlfb_object.sectionInfo=null;
    })

    $('#ZLQD_btn').click(function () {
        $("#zlqd").modal('show');
    });
    $('#zlqd_confirm').click(function (){
        $("#zlqd").modal('hide');
        zlfb_object.ZLQD();
    });
});