/**
 * 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.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){
            console.log(data);
            var me = this;
            if(data.hasOwnProperty('resort')){
                this.resortData(data.doc,1);
                _.forEach(data.update_task,function (item) {
                    me.refreshEachItme(item.query,item.doc);
                })
                gljOprObj.detailData.push(data.doc);
                this.datas.push(data.doc);
            }else {
                this.datas.push(data);
                gljOprObj.detailData.push(data);
            }
            gljOprObj.detailData=_.sortBy(gljOprObj.detailData,'seq');
            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){
            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');
            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});
            _.remove(gljOprObj.detailData,{ID:data.doc.ID});
            this.refreshSheetData();
        };
        quantity_detail.prototype.refreshSheetData=function () {
            sheetCommonObj.showData(gljOprObj.detailSheet,gljOprObj.detailSetting,gljOprObj.detailData);
        };
        quantity_detail.prototype.getUpdateData=function(type,query,doc,callfunction){
            var updateData = [];
            var newobj = {
                'updateType': type,
                'query': query,
            }
            if(doc){
                newobj['doc']=doc;
            }
            if(callfunction){
                newobj['updateFunction']=callfunction;
            }
            updateData.push(newobj);
            return updateData;
        };
        quantity_detail.prototype.saveQuantityDetail=function (args,dataCode) {
            var doc={};
            var 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.regexChecking(args.editingText)||!this.referenceChecking(args.editingText,args.row,doc)){
                    return;
                }
                doc.refreshQuantity=true;
                if(!selected.data.hasOwnProperty('isFromDetail')||selected.data.isFromDetail==0){
                    var c = confirm("确定要使用工程量明细替换原工程量吗？");
                    if(!c){
                        doc.refreshQuantity=false;
                    }
                }

            }
            var updateData
            if(args.hasOwnProperty("insertRecode")){
                updateData = this.getUpdateData('ut_update',null,doc,'insertRecode');
            }else{
                updateData = this.getUpdateData('ut_create',null,doc);
            }
            project.pushNow('saveQuantityDetail',[this.getSourceType()],updateData);
        };
        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 deleteable = this.checkReference(row);
           if(deleteable){
               var recode = gljOprObj.detailData[row];
               var updateData = this.getUpdateData('ut_delete',null,recode);
               project.pushNow('deleteQuantityDetail',[this.getSourceType()],updateData);
           }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) {
            this.swapRow(row);
        };
        quantity_detail.prototype.moveUp = function (row) {
            this.swapRow(row-1);
        };
        quantity_detail.prototype.swapRow = function (preRow) {
            var me = this;
            var update_task = [];
            var a_row = gljOprObj.detailData[preRow];//
            var b_row = gljOprObj.detailData[preRow +1];//
            var temA = a_row.seq;
            var 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}});
                }
            })

            var updateData=[];
            update_task.forEach(function (task) {
                updateData.push({'updateType': 'ut_update', 'query': task.query,'doc':task.doc});
            })
            project.pushNow('updateQuantityDetail',[this.getSourceType()],[updateData]);

        };
        quantity_detail.prototype.replaceAll=function(FindText, RepText,str) {
            let regExp = new RegExp(FindText, "g");
            return str.replace(regExp, RepText);
        };
        quantity_detail.prototype.updateQuantityDetail=function (args,dataCode,recode) {
            var doc ={};
            var query={
                ID:recode.ID,
                projectID:recode.projectID
            };
            var selected = projectObj.project.mainTree.selected;
            doc[dataCode]=args.editingText;
            if (dataCode == 'regex') {
                if(recode.hasOwnProperty('rationID')){
                    query.rationID=recode.rationID;
                }else {
                    query.billID = recode.billID
                }
                query.refreshQuantity=true;
                if(!selected.data.hasOwnProperty('isFromDetail')||selected.data.isFromDetail==0){
                    var c = confirm("确定要使用工程量明细替换原工程量吗？");
                    if(!c){
                        query.refreshQuantity=false;
                    }
                }
                query.index = args.row;
                this.updateQuantityRegex(query,doc,args)
            }else {
                this.normalUpdate(query,doc);
            }
        };
        quantity_detail.prototype.updateQuantityRegex=function(query,doc,args){
            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){
                var updateData = this.getUpdateData('ut_update',query,doc,'updateQuantityRegex');
                project.pushNow('updateQuantityDetail',[this.getSourceType()],updateData);
            }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){
                var c = confirm("确定要使用工程量明细替换原工程量吗？");
                if(!c){
                    query.refreshQuantity=false;
                }
            }
            if(detailList[args.row].hasOwnProperty('rationID')){
                query.rationID=detailList[args.row].rationID;
            }else {
                query.billID = detailList[args.row].billID
            }
            var doc={
                isSummation:newval
            };
            this.normalUpdate(query,doc);
        };
        quantity_detail.prototype.normalUpdate=function(query,doc){
            var updateData = this.getUpdateData('ut_update',query,doc);
            project.pushNow('updateQuantityDetail',[this.getSourceType()],updateData);
        };
        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.deleteByRation = function(ration){
            var detail_list = this.datas;
            var newList =_.filter(detail_list,(d)=>{
                return d.rationID!=ration.ID;
            });
            if(newList!=undefined){
                this.datas = newList;
            }
        };
        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.quantityEditChecking = function(value,node,fieldName){
            var validate = true;
            if (value && value != calcFees.getFee(node.data, fieldName)){
                if(fieldName=='quantity'){
                   if(node.data.hasOwnProperty('isFromDetail')&&node.data.isFromDetail==1){
                       var c = confirm('已有工程量明细，是否清空明细表，采用手工输入的表达式？')
                        if(c){
                            node.data.isFromDetail=0;
                            if(node.sourceType === project.Bills.getSourceType()){
                                this.deleteByBills([{type:'delete',data:node.data}]);
                            }else if(node.sourceType === project.Ration.getSourceType()){
                                this.deleteByRation(node.data);
                            }
                            gljOprObj.detailData=[];
                            sheetCommonObj.showData(gljOprObj.detailSheet,gljOprObj.detailSetting,[]);

                            validate = true;
                        }else {
                            validate = false;
                        }
                   }
                }
            }
            return validate;

        }
        return new quantity_detail(project);
    }

};