/**
 * Created by Mai on 2017/4/1.
 */
var quantity_detail = {
    createNew: function (project) {
        // 用户定义private方法
        var tools = {};

        // 所有通过this访问的属性，都不应在此单元外部进行写入操作
        var quantity_detail = function (proj) {
            this.gljTree = cacheTree.createNew(this);
           // this.project = proj;
            this.datas = [];

            var sourceType = ModuleNames.quantity_detail;
            this.getSourceType = function () {
                return sourceType;
            }
            proj.registerModule(ModuleNames.quantity_detail, this);
            this.temList=[];
        };

        // prototype用于定义public方法
        quantity_detail.prototype.loadData = function (datas) {
            this.datas = datas;
        };

        quantity_detail.prototype.getListByID = function (ID,field) {
             let condition={};
            condition[field] = ID;
             let details = _.filter(this.datas, condition);
            details = _.sortBy(details, 'seq');
            return details;
        };

        // 提交数据后返回数据处理
        quantity_detail.prototype.doAfterUpdate = function(err, data){
            if(!err){
                if(data.updateTpye=='ut_update'){
                    this.refreshAfterUpdate(data);
                }else if(data.updateTpye=='ut_delete'){
                    this.refreshAfterDelete(data);
                } else {
                    this.refreshAfterSave(data);
                }
            }else {
                alert(err.message);
                this.refreshSheetData();
            }
        };
        quantity_detail.prototype.refreshAfterSave=function(data,batchCallback){
            var me = this;
            let newData = null;
            if(data.hasOwnProperty('resort')){
                this.resortData(data.doc,1);
                _.forEach(data.update_task,function (item) {
                    me.refreshEachItme(item.query,item.doc);
                })
                newData = data.doc;
            }else {
                newData = data;
            }
            this.datas.push(newData);
            if(batchCallback){
                gljOprObj.detailData.push(newData);
            }else {
                this.refreshSheetData();
            }

        };
        quantity_detail.prototype.resortData=function(data,req){

            for(var i =0;i<gljOprObj.detailData.length;i++){
                var item = gljOprObj.detailData[i];
                if(item.seq>=data.seq){
                    item.seq=item.seq+req;
                }
            }
        };
        quantity_detail.prototype.refreshAfterUpdate=function(data,batchCallback){
            var me = this;
            var filter_object;
            if(data.hasOwnProperty('refreshList')){
                _.forEach(data.refreshList,function (item) {
                    filter_object= me.refreshEachItme(item.query,item.doc);
                })
            }else {
                filter_object = me.refreshEachItme(data.query,data.doc);
            }
            var showList = _.filter(this.datas,filter_object);
            gljOprObj.detailData=showList;
            gljOprObj.detailData=_.sortBy(gljOprObj.detailData,'seq');
            if(batchCallback == undefined){
                this.refreshSheetData();
            }

        };
        quantity_detail.prototype.refreshEachItme = function(query,doc){
            var detail_list = this.datas;
            var detail_index= _.findIndex(detail_list,function(detail){
                return detail.ID==query.ID;
            })
            _.forEach(doc, function(n, key) {
                detail_list[detail_index][key] = n;
            });
            var filter_object;
            if(detail_list[detail_index].hasOwnProperty('rationID')){
                filter_object={'rationID':detail_list[detail_index].rationID};
            }else {
                filter_object={'billID':detail_list[detail_index].billID};
            }
            return filter_object;
        };
        quantity_detail.prototype.refreshAfterDelete=function(data){
            var me = this;
            if(data.doc.seq != gljOprObj.detailData.length - 1){
                this.resortData(data.doc,-1);
            }
            _.forEach(data.update_task,function (item) {
                me.refreshEachItme(item.query,item.doc);
            });
            _.remove(this.datas,{ID:data.doc.ID});
            this.refreshSheetData();
        };
        quantity_detail.prototype.refreshSheetData=function () {
            gljOprObj.showQuantityDetailData();
        };
        quantity_detail.prototype.saveQuantityDetail=function (args,dataCode,selected,batchCallback) {
            var me = this;
            var doc={};
            var selected = selected?selected:projectObj.project.mainTree.selected;
            if(selected.sourceType==ModuleNames.ration){
                doc.rationID=selected.data.ID;
            }
            if(selected.sourceType==ModuleNames.bills){
                doc.billID=selected.data.ID;
            }
            doc.projectID = selected.data.projectID;
            doc[dataCode]=args.editingText;
            doc.seq=args.row;
            if(dataCode=='regex'){//  if(this.checkAndCalcResult(args.editingText,args.row,doc) === false){
                if(this.checkAndCalcResult(args.editingText,args.row,doc) === false){
                    gljOprObj.showQuantityDetailData();
                    return;
                }
                doc.refreshQuantity=true;
                if(!selected.data.hasOwnProperty('isFromDetail')||selected.data.isFromDetail==0){
                    if(!args.replace){//为了批量粘贴时不重复提示，普通编辑时不受影响
                        hintBox.infoBox('操作确认', '确定要使用工程量明细替换原工程量吗？', 2, function () {
                            args.replace = true;
                            me.doSaveAction(doc,args,batchCallback);
                        }, function () {
                            doc.refreshQuantity=false;
                            me.doSaveAction(doc,args,batchCallback);
                        },['确定','取消'],false);
                        return;
                    }
                }
            }
            me.doSaveAction(doc,args,batchCallback);
        };

        quantity_detail.prototype.doSaveAction = function(doc,args,batchCallback){
            let url="",me = this;
            $.bootstrapLoading.start();
            if(args.hasOwnProperty("insertRecode")){//右键插入或者是通过直接编辑保存
                url = "/quantity_detail/insertRecode";
            }else{
                url = "/quantity_detail/save";
            }
            CommonAjax.post(url,doc,function (data) {
                $.bootstrapLoading.end();
                if(doc.refreshQuantity==false){//清空数据
                    me.cleanQuantityDetail();
                }else {
                    data.newRecord?me.refreshAfterSave(data.newRecord,batchCallback):me.refreshAfterSave(data,batchCallback);
                    if(batchCallback){
                        batchCallback(args);
                    }else if(data.node){
                        me.refreshRationOrBillNodes(data.node);
                    }
                    //gljOprObj.detailSheet.setActiveCell(0,0);
                    //gljOprObj.detailSheet.clearSelection();
                }
            },function () {
                $.bootstrapLoading.end();
            });
        };



        quantity_detail.prototype.refreshRationOrBillNodes=function(node){//工程量明细更新后触发定额或清单工程量改变，进行相应的更新
            let treeNode = gljOprObj.updateDataNodeProperty(node.ID,node.data);
            if(treeNode){//触发计算
                if(treeNode.sourceType === project.Bills.getSourceType()){
                    this.updateBillQuantity(treeNode.data.quantity,treeNode,treeNode.data.quantityEXP);
                }else {//更新定额所使用的值要用还没转换前的
                    node.data? this.updateRationQuantity(node.data.r_quantity,treeNode,treeNode.data.quantityEXP):"";
                }
            }
        };

        quantity_detail.prototype.insertQuantityDetail = function (row) {
            var args = {
                row:row,
                editingText:1
            };
            if(row < gljOprObj.detailData.length){
                args.insertRecode = true;
            }
            this.saveQuantityDetail(args,'isSummation');
        };

        quantity_detail.prototype.deleteQuantityDetail = function (row) {
           var me = this;
           var deleteable = this.checkReference(row);
           if(deleteable){
               var recode = gljOprObj.detailData[row];
               $.bootstrapLoading.start();
               var callback=function (result) {
                   me.refreshAfterDelete(result.data);
                   if(result.node){//触发计算
                       me.refreshRationOrBillNodes(result.node);
                   }
                   $.bootstrapLoading.end();
               }
               CommonAjax.post("/quantity_detail/deleteRecode",recode,callback,function () {
                   $.bootstrapLoading.end();
               });
           }else {
               alert("当前行已被引用，不可删除。");
           }
        };

        quantity_detail.prototype.checkReference = function (row) {
            var deleteable = true;
           for(var i =0;i<gljOprObj.detailData.length;i++){
                var item = gljOprObj.detailData[i];
                if(_.includes(item.referenceIndexs,row+1)){
                    deleteable = false;
                    break;
                }
            }
            return deleteable;
        };

        quantity_detail.prototype.moveDown = function (row) {
            let sel =  gljOprObj.detailSheet.getSelections()[0];
            this.swapRow(row);
            gljOprObj.detailSheet.setSelection(row+1,sel.col,sel.rowCount,sel.colCount);//更改选中行
        };
        quantity_detail.prototype.moveUp = function (row) {
            let sel =  gljOprObj.detailSheet.getSelections()[0];
            this.swapRow(row-1);
            gljOprObj.detailSheet.setSelection(row-1,sel.col,sel.rowCount,sel.colCount);//更改选中行
        };
        quantity_detail.prototype.swapRow = function (preRow) {
            let me = this;
            let update_task = [];
            let a_row = gljOprObj.detailData[preRow];//
            let b_row = gljOprObj.detailData[preRow +1];//
            let temA = a_row.seq;
            let temB = b_row.seq;
            a_row.seq = temB;
            update_task.push({query:{ID:a_row.ID,projectID:a_row.projectID},doc:{seq:a_row.seq}});
            b_row.seq = temA;
            update_task.push({query:{ID:b_row.ID,projectID:b_row.projectID},doc:{seq:b_row.seq}});
            gljOprObj.detailData.forEach(function (item) {
                if(_.includes(item.referenceIndexs,temA+1)||_.includes(item.referenceIndexs,temB+1)){
                    var regex = item.regex;
                    for (var i=0;i<item.referenceIndexs.length;i++){
                        if(item.referenceIndexs[i]==temA+1){
                            regex = me.replaceAll('C'+item.referenceIndexs[i],'B'+(temB+1),regex);
                            regex = me.replaceAll('c'+item.referenceIndexs[i],'b'+(temB+1),regex);
                            item.referenceIndexs[i]=temB+1;
                        }else if(item.referenceIndexs[i]==temB+1){
                            regex = me.replaceAll('C'+item.referenceIndexs[i],'B'+(temA+1),regex);
                            regex = me.replaceAll('c'+item.referenceIndexs[i],'b'+(temA+1),regex);
                            item.referenceIndexs[i]=temA+1;
                        }
                    }
                    regex =  me.replaceAll('B','C',regex);
                    regex =  me.replaceAll('b','c',regex);
                    update_task.push({query:{ID:item.ID,projectID:item.projectID},doc:{regex:regex,referenceIndexs:item.referenceIndexs}});
                }
            });
            me.commonUpdate("/quantity_detail/swapRow",update_task);
        };
        quantity_detail.prototype.replaceAll=function(FindText, RepText,str) {
            /*let regExp = new RegExp(FindText, "g");
            return str.replace(regExp, RepText);*/
            return replaceAll(FindText, RepText,str);
        };

        quantity_detail.prototype.calcResult = function (doc) {//return false 代表输入有误
            let field = doc.billID?"billID":"rationID";// doc.rationID
            let detailList = this.getListByID(doc[field],field);
            let result = this.getEvalResult(doc.referenceIndexs,detailList,doc.regex);
            if(result === null){
                return false;
            }else {
                doc.result = result;
                return true;
            }
        };
        quantity_detail.prototype.getEvalResult = function(referenceIndexs,detailList,regex) {
            try {
                let decimal = getDecimal("quantity_detail");
                for(let i of referenceIndexs){
                    regex = this.replaceReference(i,detailList,regex)
                }
                console.log('replace all C reference -----'+regex);
                regex = this.replaceSqr(regex);
                console.log('replace all sqar reference -----'+regex);
                return scMathUtil.roundTo(eval(regex), -decimal);
            }catch (error){
                alert('输入的表达式有误，请重新输入！');
                return null;
            }
        };
        quantity_detail.prototype.replaceReference = function(index,detailList,str) {
            str=str.toUpperCase();
            let rstr= detailList[index-1].regex==null?'0':'('+detailList[index-1].regex+')';
            str=this.replaceAll('C'+index,rstr,str);
            if(detailList[index-1].referenceIndexs.length>0){
                for (let i of detailList[index-1].referenceIndexs){
                    str =this.replaceReference(i,detailList,str);
                }
            }
            return str;
        };

        quantity_detail.prototype.replaceSqr=function(text) {
            var squarRegex = /\([^\^]+\)\^\d+/g;
            var sqararr = text.match(squarRegex);

            var squarRegex2 = /C[0-9]+\^\d+|[0-9]+([.]{1}[0-9]+){0,1}\^\d+/g; //匹配没有括号的
            var sqararr2=text.match(squarRegex2);
            if(sqararr){
                text=this.converSqrByArr(sqararr,text);
            }
            if(sqararr2){
                text=this.converSqrByArr(sqararr2,text);
            }
            return text;
        };

        quantity_detail.prototype.converSqrByArr  = function(sqararr,text) {
            var temp = text;
            sqararr.forEach(function (item) {
                var arr = item.split('\^');
                var y = parseInt(arr[1]);
                var x_arr = [];
                for (var i = 0; i < y; i++) {
                    x_arr.push(arr[0]);
                }
                var temStr = x_arr.join('*');
                temp = temp.replace(item, temStr);
            });
            return temp;
        };

        quantity_detail.prototype.checkAndCalcResult = function (regex,row,doc) {//return false 表示没有通过检查
            if(!this.regexChecking(regex)||!this.referenceChecking(regex,row,doc)||!this.calcResult(doc)){
                return false;
            }
            return true;
        };

        quantity_detail.prototype.updateQuantityDetail=function (args,dataCode,recode,selected,batchCallback) {
            var doc ={},me = this;
            var query={
                ID:recode.ID,
                projectID:recode.projectID
            };
            var selected = selected?selected:projectObj.project.mainTree.selected;
            doc[dataCode]=args.editingText;
            if (dataCode == 'regex') {
                if(recode.hasOwnProperty('rationID')){
                    query.rationID=recode.rationID;
                    doc.rationID=recode.rationID;
                }else {
                    query.billID = recode.billID;
                    doc.billID=recode.billID;
                }
                if(gljUtil.isDef(args.editingText)&&this.checkAndCalcResult(args.editingText,args.row,doc) === false){
                    gljOprObj.showQuantityDetailData();
                    return;
                }
                query.refreshQuantity=true;
                if(!selected.data.hasOwnProperty('isFromDetail')||selected.data.isFromDetail==0){
                    if(!args.replace){//为了批量粘贴时不重复提示，普通编辑时不受影响
                        hintBox.infoBox('操作确认', '确定要使用工程量明细替换原工程量吗？', 2, function () {
                            args.replace = true;
                            query.index = args.row;
                            me.updateQuantityRegex(query,doc,args,batchCallback)
                        }, function () {
                            me.cleanQuantityDetail(selected,true);
                        },['确定','取消'],false);
                        return;
                    }
                }
                query.index = args.row;
                me.updateQuantityRegex(query,doc,args,batchCallback);

            }else {
                me.normalUpdate(query,doc,args,batchCallback);
            }
        };
        quantity_detail.prototype.updateQuantityRegex=function(query,doc,args,batchCallback){
            var needupdate = false;
            if(args.editingText==null){
                needupdate =true;
            }else {
                args.editingText = _.trim(args.editingText,/\r\n/);
                if(this.regexChecking(args.editingText)&&this.referenceChecking(args.editingText,args.row,doc)){
                    needupdate = true;
                }
            }
            if(needupdate){
                this.commonUpdate("/quantity_detail/updateRegex",{query:query,doc:doc},args,batchCallback);
            }else {
                var sheet = subSpread.getActiveSheet();
                sheet.getCell(args.row,args.col).value(gljOprObj.detailData[args.row].regex);
            }
        };

        quantity_detail.prototype.isSummationUpdate=function (args,detailList,newval) {
            var query={
                ID:detailList[args.row].ID,
                projectID:detailList[args.row].projectID
            };
            var selected = projectObj.project.mainTree.selected;
            query.refreshQuantity=true;
            if(!selected.data.hasOwnProperty('isFromDetail')||selected.data.isFromDetail==0){
                hintBox.infoBox('操作确认', '确定要使用工程量明细替换原工程量吗？', 2, function () {
                    summationUpdate(args,detailList,newval,query);
                }, function () {
                    query.refreshQuantity=false;
                    summationUpdate(args,detailList,newval,query);
                },['确定','取消'],false);
                return;
            }
            summationUpdate(args,detailList,newval,query);

            function summationUpdate(args,detailList,newval,query) {
                if(detailList[args.row].hasOwnProperty('rationID')){
                    query.rationID=detailList[args.row].rationID;
                }else {
                    query.billID = detailList[args.row].billID
                }
                var doc={
                    isSummation:newval
                };
                projectObj.project.quantity_detail.normalUpdate(query,doc);
            }

        };
        quantity_detail.prototype.commonUpdate = function (url,postData,args,batchCallback) {
            var me = this;
            $.bootstrapLoading.start();
            var callback = function (data) {
                $.bootstrapLoading.end();
                me.refreshAfterUpdate(data,batchCallback);
                if(batchCallback){
                    batchCallback(args)
                }else if(data.node){
                    me.refreshRationOrBillNodes(data.node);
                }
            }
            CommonAjax.post(url,postData,callback,function () {
                $.bootstrapLoading.end();
            });
        };
        quantity_detail.prototype.normalUpdate=function(query,doc,args,batchCallback){
            var url = "/quantity_detail/update";
            this.commonUpdate(url,{query:query,doc:doc},args,batchCallback);
        };
        quantity_detail.prototype.regexChecking=function(text){
            var regex=/^[0-9Cc\+\-\*\^/\(\)\.]*$/g;
            if(!regex.test(text)){
                alert("输入了非法字符，请重新输入！")
                return false;
            }else {
                return true;
            }
        };
        quantity_detail.prototype.referenceChecking=function (text,row,doc) {
            text = text.toUpperCase();
            //text= this.replaceSqr(text);
            var me = this;
            var refReg = /C\d+/g;
            var self ='C'+(row+1);

            var refList = text.match(refReg);
            var invalidate = _.includes(refList,self);
            var referenceIndexs = [];
            var indexOut = false;
            _.forEach(refList,function (item) {
                var ref_index = parseInt(item.substring(1));
                if(ref_index>gljOprObj.detailData.length){
                    indexOut=true;
                    return;
                }else {
                    referenceIndexs.push(ref_index);
                }
            });
            if(indexOut){
                alert("引用有误，请重新输入！");
                return false;
            }
            referenceIndexs=_.uniq(referenceIndexs);
            doc.referenceIndexs = referenceIndexs;

            this.temList = referenceIndexs;

            invalidate=this.getAllReferenceList((row+1),referenceIndexs);

            if(invalidate){
                alert("计算式中产生了循环引用，请重新输入！");
                return false;
            }
            return true;
        };

        quantity_detail.prototype.getAllReferenceList=function(original,refList){
            var me =this;
            var invalidate=false;
            _.forEach(refList,function (item) {
                if(me.getReferenceList(item,original)){
                    invalidate=true;
                }
            })
            return invalidate;

        };

        quantity_detail.prototype.getReferenceList=function(item,original) {
            var invalidate =false;
            if(gljOprObj.detailData.length>=item){
                var recode = gljOprObj.detailData[item - 1];
                if (recode.referenceIndexs.length > 0) {
                    if(_.includes(recode.referenceIndexs,original)){
                        invalidate = true;
                        return invalidate;
                    }
                    this.temList = this.temList.concat(recode.referenceIndexs);
                    _.forEach(recode.referenceIndex, function (item) {
                        if(this.getReferenceList(item,original)){
                            invalidate = true;
                        }
                    })
                }
            }
            return invalidate;
        };

        quantity_detail.prototype.replaceSqr = function(text) {
            var squarRegex = /\([^\^]+\)\^\d+/g;
            var sqararr = text.match(squarRegex);

            var squarRegex2 = /C[0-9]+\^\d+|[0-9]+([.]{1}[0-9]+){0,1}\^\d+/g; //匹配没有括号的
            var sqararr2=text.match(squarRegex2);
            if(sqararr){
                text=converSqrByArr(sqararr,text);
            }
            if(sqararr2){
                text=converSqrByArr(sqararr2,text);
            }
            return text;
        };
        quantity_detail.prototype.converSqrByArr = function (sqararr,text) {
            var temp = text;
            sqararr.forEach(function (item) {
                var arr = item.split('\^');
                var y = parseInt(arr[1]);
                var x_arr = [];
                for (var i = 0; i < y; i++) {
                    x_arr.push(arr[0]);
                }
                var temStr = x_arr.join('*');
                temp = temp.replace(item, temStr);
            });
            return temp;
        };
        quantity_detail.prototype.getDetailByRationID = function (rationID) {
          return _.filter(this.datas,{'rationID':rationID});
        };
        quantity_detail.prototype.getDetailByBillID = function (billID) {
            return _.filter(this.datas,{'billID':billID});
        };
        quantity_detail.prototype.addDatasToList = function (datas) {
            let  me = projectObj.project.quantity_detail;
            if(datas&&datas.length>0){
                if (me.datas && Array.isArray(me.datas)) {
                    me.datas = me.datas.concat(datas);
                } else {
                    me.datas = datas;
                }
            }
        };
        quantity_detail.prototype.deleteByRation = function(ration){
            var detail_list = this.datas;
            _.remove(detail_list,{'rationID':ration.ID});
        };
        quantity_detail.prototype.deleteByBills=function(deleteData){
            var detail_list = this.datas;
            var billIDList = [];
            for(var i=0;i<deleteData.length;i++){
                if(deleteData[i].type=='delete'){
                    billIDList.push(deleteData[i].data.ID);
                }
            }
            var newList =_.filter(detail_list,(d)=>{
                return !_.includes(billIDList,d.billID);
            });
            if(newList!=undefined){
                this.datas = newList;
            }
        };
        quantity_detail.prototype.cleanQuantityDetail = function (node,needSave) {
           node =node?node:projectObj.project.mainTree.selected;
           let query={projectID:node.data.projectID};
            if(node.sourceType === project.Bills.getSourceType()){
                query.billID = node.data.ID;
                this.deleteByBills([{type:'delete',data:node.data}]);
            }else if(node.sourceType === project.Ration.getSourceType()){
                this.deleteByRation(node.data);
                query.rationID = node.data.ID;
            }
            if(needSave===true){
                query.refreshQuantity=false;
                CommonAjax.post("/quantity_detail/save",query);
            }
            gljOprObj.detailData=[];
            sheetCommonObj.showData(gljOprObj.detailSheet,gljOprObj.detailSetting,[]);

        };
        quantity_detail.prototype.quantityEditChecking = function(value,node,fieldName){
            var validate = true;
            if(fieldName=='quantity'){
               if(node.data.hasOwnProperty('isFromDetail')&&node.data.isFromDetail==1){
                   var c = confirm('已有工程量明细，是否清空明细表，采用手工输入的表达式？')
                    if(c){
                        validate = true;
                    }else {
                        validate = false;
                    }
               }
            }
            return validate;
        };
        quantity_detail.prototype.autoTransformQuantity = function(value,node){//根据单位转换定额工程量
            let data = node.data;
            let option = optionsOprObj.getOption(optionsOprObj.optionsTypes.GENERALOPTS,'rationQuanACToRationUnit');
            let quantityEXP =  gljUtil.isDef(node.updateData.quantityEXP)? node.updateData.quantityEXP:node.data.quantityEXP
            if((quantityEXP&&(quantityEXP=='GCLMXHJ'||quantityEXP.indexOf('QDL')!=-1))||(option==true&&node.sourceType === project.Ration.getSourceType()&&data.unit)) {
                //还需加入判读是否转换,如果是来自工程量明细或者包含了表达式中包含了清单量的话，默认都进行转换
                let unit =  gljUtil.isDef(node.updateData.unit)?node.updateData.unit:data.unit;
                let times = parseInt(unit);
                if (isNaN(times)) {
                    times = 1
                }
                value = value / times;
            }
      /*      let EXPString=node.data.quantityEXP+""; 这里现在都没用到了
            if(option==false&&node.sourceType === project.Ration.getSourceType()&&EXPString!='GCLMXHJ'&&EXPString.indexOf("QDL")==-1&&data.unit){//勾选不根据单位转换工程量，且定额是手输的,
                let times = parseInt(data.unit);
                if(!isNaN(times)){///如果定额单位可以做转换
                    if(node.data.quantityEXP){
                        if(isNum(EXPString)){//如果表达式中只是数字
                            node.data.quantityEXP = EXPString+" * "+times;
                        }else {//如果表达式是一个计算式，则要加一个括号
                            node.data.quantityEXP = "("+EXPString+") * "+times;
                        }
                    }
                    if(node.data.contain!=0){
                       let billQuantity = scMathUtil.roundForObj(node.parent.data.quantity,getDecimal("quantity",node.parent));
                       let temValue = scMathUtil.roundForObj(value*times,getDecimal("quantity",node));
                       billQuantity!=0?node.data.contain = scMathUtil.roundForObj(temValue/billQuantity,getDecimal("process")):'';
                    }
                }
            }*/
            return value;
        };
        quantity_detail.prototype.reverseQuantity = function (value,node) {//根据单位反向运算出工程量
            let data = node.data;
            if(node.sourceType === project.Ration.getSourceType()&&data.unit){
                let times = parseInt(data.unit);
                if (isNaN(times)) {
                    times = 1;
                }
                value = value * times;
            }
            return value
        };
        quantity_detail.prototype.editMainTreeNodeQuantity=function (value,node,fieldName,editingText) {
            var me = this;
            if(isNaN(value)){
                alert("当前输入的数据类型不正确，请重新输入。");
                projectObj.mainController.refreshTreeNode([node]);
            }else {
                value=value?value:0;
                if(node.data.hasOwnProperty('isFromDetail')&&node.data.isFromDetail==1){
                    hintBox.infoBox('操作确认', '已有工程量明细，是否清空明细表，采用手工输入的表达式？', 2, function () {
                        node.data.isFromDetail=0;
                        me.updateMainTreeNodeQuantity(value,node,editingText);
                    }, function () {
                        projectObj.mainController.refreshTreeNode([node]);
                    },['确定','取消'],false);
                    return;
                }
                me.updateMainTreeNodeQuantity(value,node,editingText);
            }
        };
        quantity_detail.prototype.updateMainTreeNodeQuantity = function(value,node,editingText){
            let me = this;
            project.quantity_detail.cleanQuantityDetail(node,true);
            if(node.sourceType === project.Bills.getSourceType()){
                me.updateBillQuantity(value,node,null,editingText);
            }else {
                me.updateRationQuantity(value,node,null,editingText);
            }
        };
        quantity_detail.prototype.updateBillQuantity=function (value,node,quantityEXP,editingText,batchGLGL = false) {//batchGLLC是否批量更新公路公里为单位的所有清单
            let oldQuantityEXP =  node.data.quantityEXP;
            node.updateData.quantityEXP = quantityEXP?quantityEXP:editingText;
            value = scMathUtil.roundForObj(value,getDecimal("quantity",node));
            let newQuantity =  value+"";
            if(quantityEXP!="GCLMXHJ"&& oldQuantityEXP == node.data.quantityEXP && node.data.quantity == newQuantity){ //除了修改工程量明细表达式进来的操作，相当于什么都没改，不用做提交操作
                projectObj.mainController.refreshTreeNode([node]);//这里要再刷新一下，因为工程量要把手工输入的值刷新为转换后的值再显示
                return;
            }
            node.updateData.quantity = newQuantity;
            let needUpdateChildren = [];//需更新的子定额
            let gljNodes=[];//当定额工程量改变时需刷新的子工料机
            let batchBillNodes = [];
            if(batchGLGL==true){//批量更新公路公里的时候不考虑清单下的子定额工程量的更新
                this.batchUpdateGLGLNodes(batchBillNodes,node);
            }else if(node.children.length>0){//如果有子项
                for(let rationNode of node.children){
                    let EXPString = rationNode.data.quantityEXP+"";
                    if(EXPString.indexOf("QDL")!=-1){//包含了清单量的定额才要再重新计算
                        let ration_value = quantityEditObj.evalQuantityExp(EXPString,rationNode);
                        if(ration_value !== 'evalError'){
                            let times = parseInt(rationNode.data.unit);
                            if(isNaN(times)){
                                times = 1;
                            }
                            let unitTimes = 1;//清单单位转定额单位的倍数，如 kg 转 t 时是1000
                            if(gljUtil.isKGtoT(node.data.unit,rationNode.data.unit)) unitTimes = 1000;

                            rationNode.updateData.quantity = scMathUtil.roundForObj(ration_value / (times * unitTimes),getDecimal("quantity",rationNode));
                            rationNode.updateData.contain = value?scMathUtil.roundForObj(rationNode.updateData.quantity/value,getDecimal("process")):0;
                            rationNode.changed = true;
                            needUpdateChildren.push(rationNode);
                            if (rationNode.children.length>0){//如果有子工料机
                                gljNodes = gljNodes.concat(rationNode.children);
                            }
                        }
                    }else {//如果不是通过清单量计算得来的定额工程量，则重新计算含量
                        let tem_contain=0;
                        if(value&&value!=0){
                           let children_quantity = scMathUtil.roundForObj(rationNode.data.quantity,getDecimal("quantity",rationNode));
                            // children_quantity = scMathUtil.roundForObj(this.reverseQuantity(children_quantity,rationNode),getDecimal("quantity",rationNode));  原先是要反算的，现在改成不用反算了
                            tem_contain =scMathUtil.roundForObj(children_quantity/value,getDecimal("process"));
                        }
                        rationNode.updateData.contain = tem_contain;
                        rationNode.changed = true;
                        needUpdateChildren.push(rationNode);
                    }
                }
            }
            if(needUpdateChildren.length>0){//清单下的定额工程量发生了改变
                node.changed = true;//本身发生了改变，需要存储。
                needUpdateChildren.push(node);
                project.calcProgram.calcNodesAndSave(needUpdateChildren, function () {
                    project.projectGLJ.calcQuantity();
                    if(project.Bills.isFBFX(node)) { //判断是否属于分部分项工程 ，是的话才需要做计取安装费计算
                        project.installation_fee.calcInstallationFee(function (isChange,rations) {
                            if(isChange){
                                project.calcProgram.calcNodesAndSave(rations,function () {
                                    project.projectGLJ.calcQuantity();
                                });
                            }
                        });
                    }
                });
            }else {
                node.changed = true;
                batchBillNodes.push(node);
                project.calcProgram.calcNodesAndSave(batchBillNodes, function () {
                    project.projectGLJ.calcQuantity();
                });
            }
            if(gljNodes.length>0){
                projectObj.mainController.refreshTreeNode(gljNodes);
            }
            gljOprObj.refreshView();
        };

        quantity_detail.prototype.batchUpdateGLGLNodes = function (batchUpdateGLGLNodes,node) {
            for(let b of projectObj.project.Bills.datas){
                if(b.ID == node.data.ID) continue;
                let bNode =  projectObj.project.mainTree.getNodeByID(b.ID);
                if(bNode && b.unit == "公路公里"){
                    bNode.updateData.quantityEXP = node.updateData.quantityEXP;
                    bNode.updateData.quantity = node.updateData.quantity;
                    bNode.changed = true;
                    batchUpdateGLGLNodes.push(bNode);
                }
            }
        };
        quantity_detail.prototype.updateRationQuantity=function(value,node,quantityEXP,editingText){
            let oldQuantityEXP =  node.data.quantityEXP;
            node.updateData.quantityEXP = quantityEXP?quantityEXP:editingText;
            //value = scMathUtil.roundForObj(value,getDecimal("ration.quantity"));
            value = project.quantity_detail.autoTransformQuantity(value,node);//先转换再4舍5入
            value = scMathUtil.roundForObj(value,decimalObj.decimal("quantity",node));
            if( quantityEXP!="GCLMXHJ" && oldQuantityEXP == node.data.quantityEXP && node.data.quantity == value){ //除了修改工程量明细表达式进来的操作，相当于什么都没改，不用做提交操作
                projectObj.mainController.refreshTreeNode([node]);//这里要再刷新一下，因为工程量要把手工输入的值刷新为转换后的值再显示
                return;
            }
            node.updateData.quantity=value;
            if(node.parent.data.quantity&&node.parent.data.quantity!=0&&node.parent.data.quantity!=""){
                var billQuantity = scMathUtil.roundForObj(node.parent.data.quantity,getDecimal("quantity",node.parent));
                node.updateData.contain = scMathUtil.roundForObj(value/billQuantity,getDecimal("process"));
            }else {
                node.updateData.contain=0;
            }
            node.changed = true;
            project.calcProgram.calcAndSave(node, function () {
                project.projectGLJ.calcQuantity();
                if(project.Bills.isFBFX(node)) { //判断是否属于分部分项工程 ，是的话才需要做计取安装费计算
                    project.installation_fee.calcInstallationFee(function (isChange,rations) {
                        if(isChange){
                            project.calcProgram.calcNodesAndSave(rations);
                        }
                    });
                }
            });
            projectObj.mainController.refreshTreeNode(node.children);//刷新子工料机总消耗量
            gljOprObj.refreshView();
        };
        quantity_detail.prototype.getDecimal=function (node) {
            var decimal = 3;
            if(node.sourceType === project.Bills.getSourceType()){
                decimal = billsQuanDecimal.decimal(node.data.unit);
            }else {
                decimal = decimalObj.ration.quantity
            }
            return decimal;
        };
        return new quantity_detail(project);
    }

};