/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-07-06
 * 描述            ：材料成本统计
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseCostItemMapper;
import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.CmCostDstResultMapper;
import market.Cm.mapper.CmReportCostMiddleMapper;
import market.Cm.mapper.CmReportProdDetailMapper;
import market.Cm.mapper.CmReportProdMatMapper;
import market.Cm.mapper.CmReportProdMiddleMapper;
import market.Cm.mapper.CostAcmProdMapper;
import market.Cm.service.CmReportProdMatService;
import market.Cm.vo.BaseCostItem;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.CmCostDstResult;
import market.Cm.vo.CmReportCostMiddle;
import market.Cm.vo.CmReportProdDetail;
import market.Cm.vo.CmReportProdMat;
import market.Cm.vo.CmReportProdMiddle;
import market.Cm.vo.CostAcmProd;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Mat.mapper.PurMatDMapper;
import market.Pms.Mat.vo.PurMatD;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="CmReportProdMatService")
public class CmReportProdMatServiceImpl extends BaseServiceImpl<CmReportProdMat,Object> implements CmReportProdMatService {
	
	/**
	 * 材料成本统计：查询功能
	 * @param cp object[选传 item_code,prd_num,org_code,org_name,valid_flg,audit_flg等]
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCmReportProdMat(CommonPage<CmReportProdMat> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmReportProdMat rpm = cp.getObject();		
		try {
			List<CmReportProdMat> list = this.getMapper(CmReportProdMatMapper.class).doQueryCmReportProdMat(rpm);
			//处理牌号聚合成【原料卷，自制卷，委托卷】数据
			List<CmReportProdMat> steelList = this.getMapper(CmReportProdMatMapper.class).doQueryCmReportProdSteelMat(rpm);
			if (steelList!=null && steelList.size()>0) {
				for (CmReportProdMat crp : steelList) {
					list.add(crp);
				}
			}
			rm.setState("200");
			rm.setData(list);
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}

	/**
	 * 材料成本统计：审核及反审
	 * @param cp object[org_code成本组织 prd_num成本期间] memo1[1审核 0反审]
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeCmReportProdMatAuditFlg(CommonPage<CmReportProdMat> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();
		CmReportProdMat rpm = cp.getObject();
		if (rpm.getOrg_code()==null || "".equals(rpm.getOrg_code())) {
			throw new Exception("请传入成本组织");
		}
		if (rpm.getPrd_num()==null || "".equals(rpm.getPrd_num())) {
			throw new Exception("请传入成本期间");
		}
		Date now = new Date();
		//通过成本期间和成本组织进行【审核】和【反审】
		CmReportProdMat RPM = new CmReportProdMat();
		RPM.setOrg_code(rpm.getOrg_code());
		RPM.setPrd_num(rpm.getPrd_num());
		RPM.setAudit_flg("1".equals(opr)?"1":"0");//
		List<CmReportProdMat> rpmList = this.getMapper(CmReportProdMatMapper.class).find(RPM, 0, 0);
		if (rpmList!=null && rpmList.size()>0) {
			throw new Exception("成本组织【"+rpm.getOrg_name()+"】成本期间【"+rpm.getPrd_num()+"】中存在"+("1".equals(opr)?"已审核":"未审核")+"的数据");
		}
		rpm.setAudit_flg(opr);
		if ("1".equals(opr)) {//审核操作，传递审核人和审核时间
			rpm.setAudit_man(userName);
			rpm.setAudit_time(now);
		}
		this.getMapper(CmReportProdMatMapper.class).doUpdateCmReportProdMat(rpm);	
		rm.setState("200");
		rm.setMsgInfo("成本组织【"+rpm.getOrg_name()+"】成本期间【"+rpm.getPrd_num()+"】"+("0".equals(cp.getMemo1())?"反审":"审核") + "操作成功");
		return rm;
	}
	
	/**
	 * 材料成本统计：撤销核算
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCmReportProdMat(CommonPage<CmReportProdMat> cp) throws Exception{
		ResultModel rm = new ResultModel();
		CmReportProdMat rpm = cp.getObject();
		if (rpm.getPrd_num()==null || "".equals(rpm.getPrd_num())) {
			throw new Exception("请传入成本期间");
		}
		CmReportProdMat crpm = new CmReportProdMat();
		crpm.setPrd_num(rpm.getPrd_num());
		this.getMapper(CmReportProdMatMapper.class).doDeleteCmReportProdMat(crpm);		
		rm.setState("200");
		rm.setMsgInfo("删除材料成本统计成功");
		return rm;		
	}
	
	/**
	 * 反写投入产出的产出成本，单位成本，初始单价，初始金额
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doWriteBackCmCostAcmProd(CommonPage<CostAcmProd> cp) throws Exception{
		ResultModel rm = new ResultModel();
		CostAcmProd cap = cp.getObject();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String condition = " and prd_num = '"+cap.getPrd_num()+"'";
		List<CostAcmProd> capList = this.getMapper(CostAcmProdMapper.class).findWithCondition(null, condition, "prd_num desc,mat_coil_no,to_char(prod_time,'yyyyMMdd'),factweight desc", 0, 0);
		if (capList!=null && capList.size()>0) {
			//获取税率 
			Double rate = 1d;
			ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById("950901");
			if (cbi!=null) {
				rate = Double.parseDouble(cbi.getBase_name());
			}
			//获取边丝金额
			Double xzj_amount = 0d;Double dzj_amount = 0d;Double zj_amount = 0d;
			Double pz_amount = 0d;Double sx_amount = 0d;
			String swhere = " and t.prd_num = '"+cap.getPrd_num()+"' and t.item_name = '边丝'";
			List<CmCostDstResult> bsList = this.getMapper(CmCostDstResultMapper.class).doQueryCmCostDstResult(swhere);
			if (CollectionUtils.isNotEmpty(bsList)) {
				for (CmCostDstResult cdr : bsList) {
					if ("C015".equals(cdr.getOrg_code())) {//小纵剪
						xzj_amount = cdr.getAmount_value();
					}else if ("C014".equals(cdr.getOrg_code())) {//大纵剪
						dzj_amount = cdr.getAmount_value();
					}else if ("C013".equals(cdr.getOrg_code())) {//轧机
						zj_amount = cdr.getAmount_value();
					}else if ("C012".equals(cdr.getOrg_code())) {//平整
						pz_amount = cdr.getAmount_value();
					}else if ("C010".equals(cdr.getOrg_code())) {//酸洗
						sx_amount = cdr.getAmount_value();
					}
				}
			}
			
			//获取自制卷的重量差异
			Double xzj_wgt = 0d;Double dzj_wgt = 0d;Double zj_wgt = 0d;
			Double pz_wgt = 0d;Double sx_wgt = 0d;
			List<CostAcmProd> sumList = this.getMapper(CostAcmProdMapper.class).doQuaryCostAcmProdForWriteBack(cap.getPrd_num());
			if (CollectionUtils.isNotEmpty(sumList)) {
				for (CostAcmProd difCap : sumList) {
					if ("酸洗".equals(difCap.getOrg_name())) {							
						sx_wgt = difCap.getInput_wgt_value();
					}else if ("小纵剪".equals(difCap.getOrg_name())) {							
						xzj_wgt = difCap.getInput_wgt_value();
					}else if ("大纵剪".equals(difCap.getOrg_name())) {	
						// 如果都是委托卷导致重量差异为0d的话，就默认将它置为1：20230626刘侣
						dzj_wgt = difCap.getInput_wgt_value() == 0 ? 1 : difCap.getInput_wgt_value();
					}else if ("平整".equals(difCap.getOrg_name())) {
						pz_wgt = difCap.getInput_wgt_value();
					}else if ("轧机".equals(difCap.getOrg_name())) {
						zj_wgt = difCap.getInput_wgt_value();
					}
				}
			}
			
			
			for (CostAcmProd CAP : capList) {
				// ********** 如果是初始投料  **********
				if (CAP.getPrv_org_code()==null || "".equals(CAP.getPrv_org_code())) {
					//1.返写【投入产出归集表】
					CostAcmProd newCap = new CostAcmProd();
					newCap.setAcm_id(CAP.getAcm_id());
					//产出成本 = 初始投料金额(初始单价*投入量)+加工单价*产出量
					Double Original_price = CAP.getOriginal_price_value()==null?0:CAP.getOriginal_price_value();//初始单价
					Double Original_amount_value = CAP.getOriginal_amount_value()==null?0:CAP.getOriginal_amount_value();//初始金额
					if ("B".equals(CAP.getOrder_model())) {
						//委托卷上工序为null
						Original_price = 0d;
						Original_amount_value = 0d;
					}else {						
						PurMatD pmd = this.getMapper(PurMatDMapper.class).findById(CAP.getMat_coil_no());
						if (pmd!=null && pmd.getPur_price()!=null && pmd.getPur_price()!=0) {
							Original_price = pmd.getPur_price()/rate; //初始单价 = 采购单价表/税率
							//20210105 特殊处理 此卷税率是1.16
							if ("L8-600582-10".equals(CAP.getMat_coil_no())) {
								Original_price = pmd.getPur_price()/1.16;
							}
							Original_amount_value = Original_price * CAP.getInput_wgt_value();//初始金额 = 初始单价*投入量
						}
					}
					Double Process_price = CAP.getProcess_price()==null?0:CAP.getProcess_price();//加工单价
					Double Output_wgt = CAP.getOutput_wgt_value()==null?0:CAP.getOutput_wgt_value();//产出量
					//产出金额
					newCap.setOriginal_price_value(Original_price);
					newCap.setOriginal_amount_value(Original_amount_value);
					newCap.setAmount_value(Original_amount_value + (Process_price*Output_wgt));
					if ("A".equals(CAP.getOrder_model())) {							
						
						Double input_wgt = CAP.getInput_wgt_value()==null?0:CAP.getInput_wgt_value();//投入量
						if ("酸洗".equals(CAP.getOrg_name())) {							
							newCap.setAmount_value(Original_amount_value + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(sx_amount/sx_wgt));
						}else if ("小纵剪".equals(CAP.getOrg_name())) {							
							newCap.setAmount_value(Original_amount_value + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(xzj_amount/xzj_wgt));
						}else if ("大纵剪".equals(CAP.getOrg_name())) {							
							newCap.setAmount_value(Original_amount_value + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(dzj_amount/dzj_wgt));
						}else if ("平整".equals(CAP.getOrg_name())) {
							newCap.setAmount_value(Original_amount_value + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(pz_amount/pz_wgt));
						}else if ("轧机".equals(CAP.getOrg_name())) {
							newCap.setAmount_value(Original_amount_value + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(zj_amount/zj_wgt));
						}
					}
					
					//单位成本=产出成本/产出量 =初始单价+单位加工成本
					newCap.setPrice_value(Original_price + Process_price);
					if (Output_wgt!=0) {						
						newCap.setPrice_value(newCap.getAmount_value()/Output_wgt);
					}
					this.getMapper(CostAcmProdMapper.class).update(newCap);					
				}else {
					// **********   不是初始投料，投入额取上工序的产出成本。投入单价取上工序的单位成本  **********
					Double Original_price = 0d;
					CostAcmProd prvCap = new CostAcmProd();
					prvCap.setMat_coil_no(CAP.getMat_coil_no());
					prvCap.setOrg_code(CAP.getPrv_org_code());
					String prvCondition = "and prod_time < to_date('"+sf.format(CAP.getProd_time())+"','yyyy-MM-dd HH24:mi:ss')";
					List<CostAcmProd> prvList = this.getMapper(CostAcmProdMapper.class).findWithCondition(prvCap, prvCondition, "amount_value desc", 0, 0);
					if (prvList!=null && prvList.size()>0) {
						prvCap = prvList.get(0);//获取【上道工序】
						Original_price = prvCap.getPrice_value()==null?0:prvCap.getPrice_value();//初始单价	= 上工序的产出单价
						//针对委托卷
						if ("B".equals(CAP.getOrder_model())) {
							//上工序如果也是委托卷
							if ("B".equals(prvCap.getOrder_model())) {						
								Original_price = prvCap.getPrice_value()==null?0:prvCap.getPrice_value();//初始单价	= 上工序的产出单价					
							}else {
								Original_price = 0d;
							}
						}
						//本工序是自制卷，上工序是委托卷
						if ("A".equals(CAP.getOrder_model())) {
							if ("B".equals(prvCap.getOrder_model())) {
								
							}
						}
					}
					// 当前工序：小纵剪 上道工序：退火
					Double Input_wgt = CAP.getInput_wgt_value()==null?0:CAP.getInput_wgt_value();//投入量
					Double Process_price = CAP.getProcess_price()==null?0:CAP.getProcess_price();//加工单价
					Double Output_wgt = CAP.getOutput_wgt_value()==null?0:CAP.getOutput_wgt_value();//产出量
					//1.返写【投入产出归集表】
					CostAcmProd newCap = new CostAcmProd();
					newCap.setAcm_id(CAP.getAcm_id());
					newCap.setOriginal_price_value(Original_price);
					newCap.setOriginal_amount_value(Original_price*Input_wgt);
					//产出成本 = 初始投料金额(初始单价*投入量)+加工单价*产出量
					newCap.setAmount_value((Original_price*Input_wgt) + (Process_price*Output_wgt));
					if ("A".equals(CAP.getOrder_model())) {		
						// 除数为零，这个bug需要解决：20230531刘侣
						Double input_wgt = CAP.getInput_wgt_value()==null?0:CAP.getInput_wgt_value();//投入量
						if ("酸洗".equals(CAP.getOrg_name())) {							
							newCap.setAmount_value(Original_price*Input_wgt + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(sx_amount/sx_wgt));
						}else if ("小纵剪".equals(CAP.getOrg_name())) {							
							newCap.setAmount_value(Original_price*Input_wgt + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(xzj_amount/xzj_wgt));
						}else if ("大纵剪".equals(CAP.getOrg_name())) {							
							newCap.setAmount_value(Original_price*Input_wgt + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(dzj_amount/dzj_wgt));
						}else if ("平整".equals(CAP.getOrg_name())) {
							newCap.setAmount_value(Original_price*Input_wgt + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(pz_amount/pz_wgt));
						}else if ("轧机".equals(CAP.getOrg_name())) {
							newCap.setAmount_value(Original_price*Input_wgt + (Process_price*Output_wgt)-(input_wgt-Output_wgt)*(zj_amount/zj_wgt));
						}
					}
					//单位成本=产出成本/产出量 =初始单价+单位加工成本
					newCap.setPrice_value(Original_price + Process_price);
					if (Output_wgt!=0) {						
						newCap.setPrice_value(newCap.getAmount_value()/Output_wgt);//本期单位成本(实际成本/实际产量)
					}
					this.getMapper(CostAcmProdMapper.class).update(newCap);
					//20200405 委托卷且有上工序，且初始单价为0，需要清除上工序
					if ("B".equals(CAP.getOrder_model()) && CAP.getPrv_org_code()!=null && !"".equals(CAP.getPrv_org_code()) 
							&& Original_price == 0) {
						//委托卷，且来料重量为0 需要清除上工序
						this.getMapper(CostAcmProdMapper.class).doReMovePrvOrg(CAP.getAcm_id());
					}
					
				}
			}
		}
		//3.反写【产量计算中间表】(按组织归集)
		CmReportProdMiddle rpm = new CmReportProdMiddle();
		rpm.setPrd_num(cap.getPrd_num());
		List<CmReportProdMiddle> rpmList = this.getMapper(CmReportProdMiddleMapper.class).find(rpm, 0, 0);
		//获取本期成本
		CmReportProdDetail rpd = new CmReportProdDetail();
		rpd.setPrd_num(cap.getPrd_num());			
		List<CmReportProdDetail> rpdList = this.getMapper(CmReportProdDetailMapper.class).doQuaryCmReportProdDetailGbOrg(rpd);
		//获取本年累计成本
		List<CmReportProdDetail> totalRpdList = this.getMapper(CmReportProdDetailMapper.class).doQueryTotalCostAcmProdGBOrg(rpd);
		if (rpmList!=null && rpmList.size()>0) {
			for (CmReportProdMiddle crpm : rpmList) {
				//反写本期实际成本
				if (rpdList!=null && rpdList.size()>0) {
					for (CmReportProdDetail crpd : rpdList) {
						if (crpd.getOrg_code().equals(crpm.getOrg_code()) && 
								crpd.getPrd_num().equals(crpm.getPrd_num()) &&
								crpd.getOrder_model().equals(crpm.getOrder_model()) &&
								crpd.getItem_name4().equals(crpm.getInput_type()) &&
								crpd.getItem_name6().equals(crpm.getItem_type())) {							
							crpm.setAmount_value(crpd.getAmount_value());
							crpm.setConsume_amount(crpd.getConsume_amount());
							continue;
						}
					}
				}
				//反写本年累计成本
				if (totalRpdList!=null && totalRpdList.size()>0) {
					for (CmReportProdDetail totalCrpd : totalRpdList) {
						if (totalCrpd.getOrg_code().equals(crpm.getOrg_code()) && 
								totalCrpd.getOrder_model().equals(crpm.getOrder_model()) &&
								totalCrpd.getItem_name4().equals(crpm.getInput_type()) &&
								totalCrpd.getItem_name6().equals(crpm.getItem_type())) {							
							crpm.setTotal_amount(totalCrpd.getTotal_amount());
							continue;
						}
					}
				}
				this.getMapper(CmReportProdMiddleMapper.class).doWriteAmount(crpm);
			}
		}
		
		rm.setState("200");
		rm.setMsgInfo("成本价格返写成功");
		return rm;
	}
	
	/**
	 * 材料成本统计：核算功能
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doInsertCmReportProdMat(CommonPage<CmReportProdMat> cp) throws Exception{
		ResultModel rm = new ResultModel();		
		CmReportProdMat rpm = cp.getObject();
		BaseFiscalPeriodD bfpd = this.getMapper(BaseFiscalPeriodDMapper.class).findById(rpm.getPrd_num());
		if (bfpd==null) {
			throw new Exception("成本期间传递有误");
		}
		//判断当前成本期间是否核算
		CmReportProdMat RPM = new CmReportProdMat();
		RPM.setPrd_num(rpm.getPrd_num());
		int count = this.getMapper(CmReportProdMatMapper.class).count(RPM);
		if (count > 0) {
			throw new Exception("成本期间【"+rpm.getPrd_num()+"】的材料成本统计已经核算");
		}

		//I:处理【投入产出归集表】的数据
		doInsertCmReportProdMatByCcap(rpm);

		//II:处理【成本计算中间表】:资材备件、能源介质，工资，社保，变动
		doInsertCmReportProdMatByCrcm(rpm);
		
		rm.setState("200");
		rm.setMsgInfo("材料成本统计核算成功");
		return rm;
	}
	
	
	public void doInsertCmReportProdMatByCcap(CmReportProdMat rpm) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		
		//1.本期的【投入产出归集】的数据
		CostAcmProd cap = new CostAcmProd();
		cap.setPrd_num(rpm.getPrd_num());
		List<CmReportProdMat> rpmList = this.getMapper(CmReportProdMatMapper.class).doQuaryCcapForCrpMat(cap);
		if (rpmList==null || rpmList.size()<=0) {
			throw new Exception("未找到成本期间【"+rpm.getPrd_num()+"】的【投入产出归集】数据");
		}		
		//获取本年累计的产量
		List<CmReportProdMat> totalRpmList = this.getMapper(CmReportProdMatMapper.class).doQuaryTotalCcapForCrpMat(cap);
		//获取同期的材料成本统计
		CmReportProdMat sameRpm = new CmReportProdMat();
		String samePrd_num = (Long.parseLong(rpm.getPrd_num().substring(0,4))-1)+rpm.getPrd_num().substring(rpm.getPrd_num().length()-2);		
		sameRpm.setPrd_num(samePrd_num);		
		List<CmReportProdMat> sameRpmList = this.getMapper(CmReportProdMatMapper.class).find(sameRpm, 0, 0);
		
		for (CmReportProdMat RPM : rpmList) {
			CmReportProdMat crpm = new CmReportProdMat();
			crpm.setItem_code(RPM.getItem_code());
			crpm.setItem_name(RPM.getItem_name());
			crpm.setOrg_code(RPM.getOrg_code());
			crpm.setOrg_name(RPM.getOrg_name());
			crpm.setPrd_num(RPM.getPrd_num());//成本期间
			crpm.setItem_type(RPM.getItem_type());
			crpm.setItem_grade(RPM.getItem_grade());
			crpm.setItem_name2("直接材料");
			crpm.setItem_name3("原料及主料");
			crpm.setItem_name4(RPM.getItem_name4());
			crpm.setItem_name5(RPM.getItem_name5());
			crpm.setItem_name6(RPM.getItem_name6());
			crpm.setMsr_unit(RPM.getMsr_unit());
			crpm.setItem_ctrl(RPM.getItem_ctrl());//成本性态[0变动、1固定]
			crpm.setItem_prop(RPM.getItem_prop());//责任属性[0不可控、1可控]			
			crpm.setConsume_value(RPM.getConsume_value()==null?0:RPM.getConsume_value());//本期实际用量			
			crpm.setAmount_value(RPM.getAmount_value()==null?0:RPM.getAmount_value());//本期实际成本
			Double Weight_value = RPM.getWeight_value()==null?0:RPM.getWeight_value();//本期实际产量
			if (Weight_value!=0) {				
				//本期单位用量 = 本期实际用量/本期实际产量
				crpm.setConsume_per(crpm.getConsume_value()/Weight_value);
				//本期单位成本 = 本期实际成本/本期实际产量			 
				crpm.setAmount_per(crpm.getAmount_value()/Weight_value);
			}
			if (totalRpmList!=null && totalRpmList.size()>0) {
				for (CmReportProdMat totalRpm : totalRpmList) {
					if (totalRpm.getItem_code().equals(crpm.getItem_code()) &&
							totalRpm.getOrg_code().equals(crpm.getOrg_code()) &&
							totalRpm.getItem_name6().equals(crpm.getItem_name6()) &&
							totalRpm.getItem_name5().equals(crpm.getItem_name5()) &&
							totalRpm.getItem_name4().equals(crpm.getItem_name4())) {
						crpm.setTotal_consume(totalRpm.getConsume_value()==null?0:totalRpm.getConsume_value());//本年累计用量
						crpm.setTotal_amount(totalRpm.getAmount_value()==null?0:totalRpm.getAmount_value());//本年累计成本
						Double total_weight = totalRpm.getWeight_value()==null?0:totalRpm.getWeight_value();//本年累计产量
						if (total_weight!=0) {							
							//本年累计单位用量 = 本年累计用量/本年累计产量
							crpm.setTotal_consume_per(crpm.getTotal_consume()/total_weight);	
							//本年累计单位成本 = 本年累计成本/本年累计产量
							crpm.setTotal_amount_per(crpm.getTotal_amount()/total_weight);
						}
						continue;
					}
				}
			}			 
			//处理同期数据
			if (sameRpmList!=null && sameRpmList.size()>0) {
				for (CmReportProdMat srpm : sameRpmList) {
					if (srpm.getItem_code().equals(crpm.getItem_code()) &&
							srpm.getOrg_code().equals(crpm.getOrg_code()) &&
							srpm.getItem_name6().equals(crpm.getItem_name6()) &&
							srpm.getItem_name5().equals(crpm.getItem_name5()) &&
							srpm.getItem_name4().equals(crpm.getItem_name4())) {										
						//同期累计单位用量 = 同期累计用量/同期累计产量
						crpm.setSame_total_consume_per(srpm.getSame_total_consume_per());
						//同期累计单位成本 = 同期累计成本/同期累计产量
						crpm.setSame_total_amount_per(srpm.getSame_total_amount_per());			
						continue;
					}
				}
			}
			crpm.setMemo(null);
			crpm.setValid_flg("1");
			crpm.setAudit_flg("0");
			crpm.setCreate_man(userName);
			crpm.setCreate_time(now);
			this.getMapper(CmReportProdMatMapper.class).insert(crpm);
		}
	}

	/**
	 * 处理【成本计算中间表】:资材备件、能源介质，工资，社保，变动
	 * @param rpm
	 * @throws Exception
	 */
	public void doInsertCmReportProdMatByCrcm(CmReportProdMat rpm) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		//1.查询【成本计算中间表】CmReportCostMiddle的实际用量，实际成本
		CmReportCostMiddle rcm = new CmReportCostMiddle();
		rcm.setPrd_num(rpm.getPrd_num());//成本期间
		List<CmReportCostMiddle> rcmList = this.getMapper(CmReportCostMiddleMapper.class).find(rcm, 0, 0);
		if (rcmList==null || rcmList.size()<=0) {
			throw new Exception("未找到成本期间【"+rpm.getPrd_num()+"】的【成本计算中间表】数据");
		}
		//2.获取【产量计算中间表】CmReportProdDetail取产量(成本组织汇总)
		CmReportProdMiddle crmMid = new CmReportProdMiddle();
		crmMid.setPrd_num(rpm.getPrd_num());
		List<CmReportProdMiddle> crmMidList = this.getMapper(CmReportProdMiddleMapper.class).doQuaryCrpmForCrpp(crmMid);
		if (crmMidList==null || crmMidList.size()<=0) {
			throw new Exception("未找到成本期间【"+rpm.getPrd_num()+"】的【产量计算中间表】数据");
		}
		//获取本年累计的产量(成本组织汇总)
		List<CmReportProdMiddle> totalCrmMidList = this.getMapper(CmReportProdMiddleMapper.class).doQuaryTotalCrpmForCrpp(crmMid);
		//获取同期的产量明细中间表
		CmReportProdMat sameRpm2 = new CmReportProdMat();
		String samePrd_num = (Long.parseLong(rpm.getPrd_num().substring(0,4))-1)+rpm.getPrd_num().substring(rpm.getPrd_num().length()-2);
		sameRpm2.setPrd_num(samePrd_num);		
		List<CmReportProdMat> sameRpmList2 = this.getMapper(CmReportProdMatMapper.class).find(sameRpm2, 0, 0);
					
		//查询所有的有效的成本项目
		BaseCostItem bci = new BaseCostItem();
		bci.setValid_flg("1");
		List<BaseCostItem> bciList = this.getMapper(BaseCostItemMapper.class).find(bci, 0, 0);
		if (bciList==null || bciList.size()<=0) {
			throw new Exception("未找到有效的成本组织");
		}
	
		for (CmReportCostMiddle rcmi : rcmList) {
			CmReportProdMat crpm = new CmReportProdMat();
			crpm.setItem_code(rcmi.getItem_code());
			crpm.setItem_name(rcmi.getItem_name());
			crpm.setOrg_code(rcmi.getOrg_code());
			crpm.setOrg_name(rcmi.getOrg_name());
			crpm.setPrd_num(rcmi.getPrd_num());//成本期间
			crpm.setItem_type(rcmi.getItem_type());//项目类型
			crpm.setItem_grade(rcmi.getItem_grade());//项目等级
			//父级成本项目
			for (BaseCostItem BCI : bciList) {
				if (BCI.getItem_code().equals(rcmi.getParent_item_code())) {					
					if (BCI.getItem_grade().longValue()==2) {
						crpm.setItem_name2(rcmi.getParent_item_name());
					}
					if (BCI.getItem_grade().longValue()==3) {
						crpm.setItem_name3(rcmi.getParent_item_name());
					}					
					continue;
				}
			}
			crpm.setMsr_unit(rcmi.getMsr_unit());
			//成本项目
			for (BaseCostItem BCI : bciList) {
				if (BCI.getItem_code().equals(rcmi.getItem_code())) {
					crpm.setItem_ctrl(BCI.getItem_ctrl());//成本性态[0变动、1固定]
					crpm.setItem_prop(BCI.getItem_prop());//责任属性[0不可控、1可控]
					continue;
				}
			}
			//处理本期用量，本期成本，本期产量
			crpm.setConsume_value(rcmi.getConsume_value()==null?0:rcmi.getConsume_value());//本期实际用量
			crpm.setAmount_value(rcmi.getAmount_value()==null?0:rcmi.getAmount_value());//本期实际成本
			if (crmMidList!=null && crmMidList.size()>0) {
				for (CmReportProdMiddle ccrmMid : crmMidList) {
					if (ccrmMid.getOrg_code().equals(rcmi.getOrg_code())) {
						//本期实际产量
						Double weight_value = ccrmMid.getWeight_value()==null?0:ccrmMid.getWeight_value();
						if (weight_value!=0) {							
							//本期单位用量 = 本期实际用量/本期实际产量
							crpm.setConsume_per(crpm.getConsume_value()/weight_value);
							//本期单位成本 = 本期实际成本/本期实际产量
							crpm.setAmount_per(crpm.getAmount_value()/weight_value);
						}
						continue;
					}
				}
			}
			//处理累计用量，累计成本，累计产量			
			crpm.setTotal_consume(rcmi.getTotal_consume()==null?0:rcmi.getTotal_consume());//本年累计用量
			crpm.setTotal_amount(rcmi.getTotal_amount()==null?0:rcmi.getTotal_amount());//本年累计成本
			if (totalCrmMidList!=null && totalCrmMidList.size()>0) {
				for (CmReportProdMiddle totalCrmMid : totalCrmMidList) {
					if (totalCrmMid.getOrg_code().equals(rcmi.getOrg_code())) {
						//本年累计产量
						Double total_weight = totalCrmMid.getTotal_weight()==null?0:totalCrmMid.getTotal_weight();
						if (total_weight!=0) {							
							//本年累计单位用量 = 本年累计用量/本年累计产量
							crpm.setTotal_consume_per(crpm.getTotal_consume()/total_weight);	
							//本年累计单位成本 = 本年累计成本/本年累计产量
							crpm.setTotal_amount_per(crpm.getTotal_amount()/total_weight);
						}
						continue;
					}
				}
			}
			//处理同期数据
			if (sameRpmList2!=null && sameRpmList2.size()>0) {
				for (CmReportProdMat srpm : sameRpmList2) {
					if (srpm.getItem_code().equals(rcmi.getItem_code()) &&
							srpm.getOrg_code().equals(rcmi.getOrg_code())) {										
						//同期累计单位用量 = 同期累计用量/同期累计产量
						crpm.setSame_total_consume_per(srpm.getSame_total_consume_per());
						//同期累计单位成本 = 同期累计成本/同期累计产量
						crpm.setSame_total_amount_per(srpm.getSame_total_amount_per());			
						continue;
					}
				}
			}						
			crpm.setMemo(null);
			crpm.setValid_flg("1");
			crpm.setAudit_flg("0");
			crpm.setCreate_man(userName);
			crpm.setCreate_time(now);
			this.getMapper(CmReportProdMatMapper.class).insert(crpm);
		}
	}
}
