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

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

            var sourceType = ModuleNames.ration_coe;
            this.getSourceType = function () {
                return sourceType;
            }
            proj.registerModule(ModuleNames.ration_coe, this);
        };

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

        // 提交数据后返回数据处理
        ration_coe.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);
                }
            }
        };
        ration_coe.prototype.refreshAfterSave=function(data){
            projectObj.project.ration_coe.addDatasToList(data);
            zmhs_obj.showDatas();
        };

        ration_coe.prototype.addDatasToList = function (datas) {
            let  me = projectObj.project.ration_coe;
            if(datas&&datas.length>0){
                if (me.datas && Array.isArray(me.datas)) {
                    me.datas = me.datas.concat(datas);
                } else {
                    me.datas = datas;
                }
            }
        };
        ration_coe.prototype.getCoeByRationID = function (rationID) {
           let coeList = _.filter(this.datas, {'rationID': rationID});
           return coeList;
        };
        ration_coe.prototype.refreshAfterUpdate=function(data){
            var coe_list = projectObj.project.ration_coe.datas;
            var coe_index= _.findIndex(coe_list,function(coe){
                return coe.ID==data.query.ID&&coe.projectID==data.query.projectID;
            })
            _.forEach(data.doc, function(n, key) {
                coe_list[coe_index][key] = n;
            });
            $('#coeSpread').is(':visible'),
            zmhs_obj.showDatas();
        };
        ration_coe.prototype.refreshAfterDelete=function(data){
            var glj_list = projectObj.project.ration_coe.datas;
            _.remove(glj_list,data.query);
            _.remove(gljOprObj.sheetData,data.query);
            zmhs_obj.showDatas();
        };

        ration_coe.prototype.getRationCoedata=function(newRation,data){
            var criteria= {};
            criteria.ration_coe_list = [];
            var dataLength = 0;
            if(data.hasOwnProperty('rationCoeList')&&data.rationCoeList.length>0){
                dataLength = data.rationCoeList.length
            }
            for(var i=0;i<=dataLength;i++){;
                var newCoe = {
                    libID :data.rationRepId,
                    rationID:newRation.ID,
                    projectID :  newRation.projectID
                }
                if(i==dataLength){
                    newCoe.coeID=-1;
                    newCoe.name = '自定义系数';
                    newCoe.content='人工×1，材料×1，机械×1，主材×1，设备×1';
                    newCoe.isAdjust=0;
                    newCoe.coes = this.getCustomerCoeData();
                }else {
                    newCoe.coeID= data.rationCoeList[i].ID;
                }
                criteria.ration_coe_list.push(newCoe);
            }
            criteria.updateType = 'ut_create';
            return criteria;
        };
        ration_coe.prototype.getCustomerCoeData = function () {
            var coeList = [];
            coeList.push({ amount:1, operator:'*', gljCode:null, coeType:'定额'});
            coeList.push({ amount:1, operator:'*', gljCode:null, coeType:'人工'});
            coeList.push({ amount:1, operator:'*', gljCode:null, coeType:'材料'});
            coeList.push({ amount:1, operator:'*', gljCode:null, coeType:'机械'});
            coeList.push({ amount:1, operator:'*', gljCode:null, coeType:'主材'});
            coeList.push({ amount:1, operator:'*', gljCode:null, coeType:'设备'});
            return coeList;
        };

        ration_coe.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;
        };
        ration_coe.prototype.adjustCoeClick = function(record,newval,ext){
            let me=this,codesList = [],add=[],replace=[];
            let doc = ext?ext:{};
            doc['isAdjust'] = newval;
            var updateData = {
                'ID':record.ID,
                'projectID': record.projectID,
                'rationID':record.rationID,
                'doc':doc,
                add:[],
                delete:[],
                replace:[]
            };
            let gljList = project.ration_glj.getGLJListByRationID(record.rationID);
            if(gljUtil.isDef(record.option_codes)&&record.option_codes!=""){ //说明编辑的是下拉选择编号的类型
                //勾选而不是下拉的情况下，默认选择下拉框中的第一个
                if(newval == 1 && (!gljUtil.isDef(doc.select_code)||doc.select_code == '')){
                    if(record.option_list&&record.option_list.length > 0) doc.select_code = record.option_list[0].value;
                }
                this.prepareDataForOptionType(record,newval,gljList,updateData,replace,codesList,doc);
            }
            for(let coe of record.coes){//做单个、替换等检查
                if(coe.coeType == "单个工料机"){ //单个工料机的情况
                    let glj = _.find(gljList,{"code":coe.gljCode});
                    if(newval == 1){ //单个工料机，选中时，如果能找到则不管，如果没找到，则需自动插入
                        if(glj) continue;
                        add.push(coe.gljCode);
                        codesList.push(coe.gljCode);
                    }else {//取消勾选时，要删除添加的工料机记录
                       if(glj && glj.createType == "add") updateData.delete.push(glj.ID);
                    }
                }
                //替换工料机的情况
                if(coe.coeType ==  "替换人材机"){
                    let glj = _.find(gljList,{"rcode":coe.gljCode,'code':coe.replaceCode});//两个条件都满足，则表示已找到对应的记录
                    if(newval == 1){
                        if(glj) continue;
                        let r_glj = _.find(gljList,function (g) {
                            return (g.code == coe.gljCode && (g.createType===undefined || g.createType == 'normal')) || g.rcode == coe.gljCode //这两个满足一个说明要替换
                        });
                        if(r_glj){
                            replace.push({code:coe.replaceCode,oldData:r_glj});
                            codesList.push(coe.replaceCode);
                        }
                    }
                    if(newval == 0 && glj){//取消勾选并找到的情况，要恢复成原来的
                        replace.push({code:coe.gljCode,oldData:glj});
                        codesList.push(coe.gljCode);
                    }
                }
            }
            project.ration_glj.getGLJDataByCodes(codesList,function (gljList) {//统一从后端按编号查找标准工料机信息
                let gljMap = _.indexBy(gljList, 'code');
                for(let a of add){
                    if(gljMap[a]){
                        let tem = project.ration_glj.getAddDataByStd(gljMap[a],record.rationID,project.mainTree.selected.data.billsItemID,record.projectID);
                        updateData.add.push(tem);
                    }
                }
                for(let r of replace){
                    if(gljMap[r.code]){
                        let r_tem = project.ration_glj.getReplaceDataByStd(r.oldData,gljMap[r.code]);
                        updateData.replace.push(r_tem);
                    }
                }
                $.bootstrapLoading.start();
                CommonAjax.post("/ration/updateCoeAdjust",updateData,function (result) {
                    $.bootstrapLoading.end();
                    me.refreshAfterUpdate(result.coe);
                    zmhs_obj.refreshAfterUpdate(result);
                })
            });

        };
        ration_coe.prototype.prepareDataForOptionType = function (record,newval,gljList,updateData,replace,codesList,ext) {
            let select_code = record.select_code;
            if(ext && gljUtil.isDef(ext.select_code)&&ext.select_code!=""){//是下拉框选择了人材机编号进来的
                select_code = ext.select_code;
            }
            if(gljUtil.isDef(select_code) && select_code!=""){//有选中编号的情况下，才会做这些操作
                let glj = _.find(gljList,{"rcode":record.original_code,'code':select_code});//两个条件都满足，则表示已找到对应的记录
                if(newval == 1){
                    if(!glj){//在没找到的情况下，要替换
                        let r_glj = _.find(gljList,function (g) {
                            return (g.code == record.original_code && (g.createType===undefined || g.createType == 'normal')) || g.rcode == record.original_code //这两个满足一个说明要替换
                        });
                        if(r_glj){
                            replace.push({code:select_code,oldData:r_glj});
                            codesList.push(select_code);
                        }
                    }
                }else {
                    updateData.doc['select_code'] = ""; //取消勾选，选中值要恢复为空
                    if(glj){//如果找到工料机，还需要恢复成原来的
                        replace.push({code:record.original_code,oldData:glj});
                        codesList.push(record.original_code);
                    }
                }
            }
        };




        ration_coe.prototype.updateCustomerCoe = function (data) {
            var updateData = this.getUpdateData('ut_update',data.query,data.doc,'updateCustomerCoe');
            project.pushNow('updateCustomerCoe',[this.getSourceType()],updateData);
        };
        ration_coe.prototype.deleteByRation = function(ration){
            var coe_list = projectObj.project.ration_coe.datas;
            _.remove(coe_list,{'rationID':ration.ID});
        };
        return new ration_coe(project);
    }



};