/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-06-03
 * 描述            ：投入产出归集表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.BaseOrgCmpMapper;
import market.Cm.mapper.CostAcmProdMapper;
import market.Cm.service.CostAcmProdService;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.BaseOrgCmp;
import market.Cm.vo.CmCostAcmInn;
import market.Cm.vo.CmCostAcmOut;
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.Mes.Pickle.Performance.mapper.MesPlmMMapper;
import market.Mes.Pickle.Performance.vo.MesPlmM;
import market.Mes.Rolling.Performance.vo.MesRcmM;
import market.Mes.Tpm.vo.MesTpmM;
import market.Pms.Mat.mapper.PurMatDMapper;
import market.Pms.Mat.vo.PurMatD;

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

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

@RemoteService(path="CostAcmProdService")
public class CostAcmProdServiceImpl extends BaseServiceImpl<CostAcmProd,Object> implements CostAcmProdService {

	/**
	 * 产量归集查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCostAcmProd(CommonPage<CostAcmProd> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CostAcmProd cap = cp.getObject();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<CostAcmProd> pm = new PageModel<CostAcmProd>(pageIndex,pageSize);
		try {
			String swhere = "";			
			if (cap.getOrder_id()!=null && !"".equals(cap.getOrder_id())) {
				swhere+=" and order_id like '%"+cap.getOrder_id()+"%'";//订单号
			}
			if (cap.getMat_coil_no()!=null && !"".equals(cap.getMat_coil_no().trim())) {
				swhere+=" and mat_coil_no like '%"+cap.getMat_coil_no().trim()+"%'";//原料卷号
			}
			if (cap.getOrg_name()!=null && !"".equals(cap.getOrg_name())) {
				swhere+=" and org_name like '%"+cap.getOrg_name()+"%'";//成本组织
			}
			if (cap.getOrg_code()!=null && !"".equals(cap.getOrg_code())) {
				swhere+=" and org_code = '"+cap.getOrg_code()+"'";//成本组织
			}
			if (cap.getPrd_num()!=null && !"".equals(cap.getPrd_num())) {
				swhere+=" and prd_num like '%"+cap.getPrd_num()+"%'";//成本期间
			}
			if (startTime!=null && !"".equals(startTime)) {
				swhere += " and to_char(prod_time, 'yyyy-mm-dd hh24:mi:ss') >='"
						+ startTime +" 00:00:00"+ "'";//生产时间起
			}
			if (endTime!=null && !"".equals(endTime)) {
				swhere += " and to_char(prod_time, 'yyyy-mm-dd hh24:mi:ss') <='"
						+ endTime +" 23:59:59"+ "'";//生产时间止
			}
			if (cap.getOrder_model()!=null && !"".equals(cap.getOrder_model())) {
				swhere+=" and order_model = '"+cap.getOrder_model()+"'";//是否有效
			}
			if (cap.getInput_type()!=null && !"".equals(cap.getInput_type())) {
				swhere+=" and input_type = '"+cap.getInput_type()+"'";//是否有效
			}
			if (cap.getValid_flg()!=null && !"".equals(cap.getValid_flg())) {
				swhere+=" and valid_flg = '"+cap.getValid_flg()+"'";//是否有效
			}
			if (cap.getAudit_flg()!=null && !"".equals(cap.getAudit_flg())) {
				swhere += " and audit_flg = '"+cap.getAudit_flg()+"'";//是否审核
			}
			pm.setRows(this.getMapper(CostAcmProdMapper.class).findWithCondition(null, swhere, "prd_num desc,mat_coil_no,prod_time", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(CostAcmProdMapper.class).countWithCondition(null, swhere));			
			rm.setState("200");
			rm.setData(pm);
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 产量归集：审核及反审
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doChangeCostAcmProdAuditFlg(CommonPage<CostAcmProd> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();
		CostAcmProd cap = cp.getObject();
		
		//通过成本期间和成本组织进行【审核】和【反审】
		CostAcmProd CAP = new CostAcmProd();
		CAP.setPrd_num(cap.getPrd_num());
		CAP.setAudit_flg("1".equals(opr)?"1":"0");//
		int count = this.getMapper(CostAcmProdMapper.class).count(CAP);
		if (count > 0) {
			throw new Exception("成本期间【"+cap.getPrd_num()+"】中存在"+("1".equals(opr)?"已审核":"未审核")+"的数据");
		}
		cap.setAudit_flg(opr);
		if ("1".equals(opr)) {//审核操作，传递审核人和审核时间			
			cap.setAudit_man(userName);
			cap.setAudit_time(now);
		}
		//反审操作：需要验证是否进行了合法性核算
		if ("0".equals(opr)) {
			
		}
		this.getMapper(CostAcmProdMapper.class).doChangeCostAcmProdAuditFlg(cap);
		this.getBean(CmCostAcmInnServiceImpl.class).doChangeCmCostAcmInnAuditFlg(cp);
		this.getBean(CmCostAcmOutServiceImpl.class).doChangeCmCostAcmOutAuditFlg(cp);
		rm.setMsgInfo("成本期间【"+cap.getPrd_num()+"】"+("0".equals(cp.getMemo1())?"反审":"审核") + "操作成功");
		rm.setState("200");		
		return rm;
	}

	/**
	 * 删除投入产出归集信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteCostAcmProd(CommonPage<BaseFiscalPeriodD> cp) throws Exception{
		ResultModel rm = new ResultModel();
		BaseFiscalPeriodD bfpd = cp.getObject();
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
		if (b==null) {
			throw new Exception("请传入成本期间");
		}		
		//判断成本期间内是否已经进行了归集
		String prd_num = bfpd.getPrd_num();//成本期间
		CostAcmProd CAP = new CostAcmProd();
		CAP.setPrd_num(prd_num);	//成本期间
		CAP.setAudit_flg("1");		//已经审核
		List<CostAcmProd> CAMList = this.getMapper(CostAcmProdMapper.class).find(CAP, 0, 0);
		if (CAMList!=null && CAMList.size()>0) {
			throw new Exception("当前成本期间【"+prd_num+"】已经存在已经审核归集信息,无法删除");
		}
		//删除成本期间内的信息
		this.getMapper(CostAcmProdMapper.class).deleteCostAcmProdByPrdnum(prd_num);
		
		CommonPage<CmCostAcmInn> cpInn = new CommonPage<CmCostAcmInn>();
		CmCostAcmInn inn = new CmCostAcmInn();
		inn.setPrd_num(prd_num);
		cpInn.setObject(inn);
		this.getBean(CmCostAcmInnServiceImpl.class).doDeleteCmCostAcmInn(cpInn);
		
		CommonPage<CmCostAcmOut> cpOut = new CommonPage<CmCostAcmOut>();
		CmCostAcmOut out = new CmCostAcmOut();
		out.setPrd_num(prd_num);
		cpOut.setObject(out);
		this.getBean(CmCostAcmOutServiceImpl.class).doDeleteCmCostAcmOut(cpOut);
		rm.setState("200");
		rm.setMsgInfo("投入产出归集信息删除成功");
		return rm;		
	}

	/**
	 * 投入产出归集
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertCostAcmProd(CommonPage<BaseFiscalPeriodD> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		BaseFiscalPeriodD bfpd = cp.getObject();
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
		if (b==null) {
			throw new Exception("请传入成本期间");
		}
		//判断成本期间内是否已经进行了归集
		CostAcmProd CCAP = new CostAcmProd();
		CCAP.setPrd_num(bfpd.getPrd_num());//成本期间
		int count = this.getMapper(CostAcmProdMapper.class).count(CCAP);
		if (count > 0) {
			throw new Exception("当前成本期间【"+bfpd.getPrd_num()+"】已经进行投入产出归集");
		}

		Date now = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String startTime = df.format(b.getStr_date());
		String endTime = df.format(b.getEnd_date());
		
		//1.查找归集期间的所在投料时间内的的入库数据：需要增加 is_bs 来将成品卷和边丝分开 (20220403 treals)
		List<CostAcmProd> capList = this.getMapper(CostAcmProdMapper.class).doQuaryYdmProductInlistForCap(startTime,endTime);
		if (capList==null || capList.size()<=0) {
			throw new Exception("未找到数据");
		}
		//获取税率 
		Double rate = 1d;
		ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById("950901");
		if (cbi!=null) {
			rate = Double.parseDouble(cbi.getBase_name());
		}
		Long ser_num = Long.parseLong(bfpd.getPrd_num()+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+"0000");
		for (CostAcmProd CAP : capList) {	
			if (StringUtils.isEmpty(CAP.getItem_code())) {
				rm.setState("500");
				rm.setMsgInfo("未维护牌号【"+CAP.getSteel_name()+"】对应的成本项目");
				return rm;
			}
			CostAcmProd cap = new CostAcmProd();
			cap.setPrd_num(bfpd.getPrd_num());//成本期间 
			//设置主键
			ser_num++;
			cap.setAcm_id("GG"+ser_num);
			//获取上工序机台代码及名称：通过原料卷号，机台，仓库
			cap.setMat_coil_no(CAP.getMat_coil_no());//原料卷号
			cap.setMachine_code(CAP.getMachine_code());//机台代码
			cap.setMachine_name(CAP.getMachine_name());	
			
			cap.setStorageattr(CAP.getStorageattr());
			
			// storageattr是取的该卷所有入库记录的最后一条：如果是500201说明是成品库再入原料库，应定为500202；如果是500205说明是成品库转到贸易外库，应定为500203 20230525刘侣
//			cap.setStorageattr("500201".equals(CAP.getStorageattr()) ? "500202" : "500205".equals(CAP.getStorageattr()) ? "500203" : CAP.getStorageattr());//仓库			
//			// 同时对卷进行是贸易外库卷还是挂单回原料库卷进行标记：
//			cap.setMemo("500201".equals(CAP.getStorageattr()) ? "成品重进原料库" : "500205".equals(CAP.getStorageattr()) ? "贸易卷" : "无");
			// end
			
			cap.setPrv_org_code(CAP.getPrv_org_code());
			cap.setPrv_org_name(CAP.getPrv_org_name());
			cap.setIs_tw(CAP.getIs_tw());//是否头尾卷
			cap.setIs_bs(CAP.getIs_bs());// 是否边丝
			cap.setProd_time(CAP.getIndate());//最大的入库时间
			//产品状态(A成品 B中间品 C在制品)
			if ("500202".equals(CAP.getStorageattr())) {
				cap.setProd_state("B");
			}else if ("500203".equals(CAP.getStorageattr())) {
				cap.setProd_state("A");
			}
			//牌号代码
			cap.setSteel_code(CAP.getSteel_code());
			cap.setSteel_name(CAP.getSteel_name());
			//项目代码
			cap.setItem_code(CAP.getItem_code());
			cap.setItem_name(CAP.getItem_name());
			//父级项目代码
			cap.setParent_item_code(CAP.getParent_item_code());
			cap.setParent_item_name(CAP.getParent_item_name());
			//成本组织
			cap.setOrg_code(CAP.getOrg_code());
			cap.setOrg_name(CAP.getOrg_name());
			cap.setOrder_id(CAP.getOrder_id());//订单号			
			//交货状态代码 
			cap.setDelivery_state_code(CAP.getDelivery_state_code()==null?" ":CAP.getDelivery_state_code());
			cap.setDelivery_state_desc(CAP.getDelivery_state_desc()==null?" ":CAP.getDelivery_state_desc());			
			//订单属性(1原料卷  2需加工  3非计划)
			cap.setOrder_nature(CAP.getOrder_nature());
			//计重方式(102302毛重   102301净重)
			cap.setWeight_type_no(CAP.getWeight_type_no());
			cap.setWeight_type_name(CAP.getWeight_type_name());
			//订单号为null,默认是净重交货
			if (CAP.getOrder_id()==null || "".equals(CAP.getOrder_id())) {
				cap.setWeight_type_no("102301");
				cap.setWeight_type_name("净重");
			}
			//没有订单的头尾卷不进行归集，将边丝卷也加进去：20230525刘侣废掉
			if ((CAP.getOrder_id()==null || "".equals(CAP.getOrder_id())) && ("1".equals(CAP.getIs_tw()))) {
				continue;
			}
			
			//实重和理重
			cap.setFactweight(CAP.getFactweight()==null?0:CAP.getFactweight());
			cap.setTheoryweight(CAP.getTheoryweight()==null?0:CAP.getTheoryweight());
			//毛重交货：投入量和产出量默认 = 理重
			if ("102302".equals(cap.getWeight_type_no())) {
				cap.setInput_wgt_value(CAP.getTheoryweight()==null?0:CAP.getTheoryweight());
				cap.setOutput_wgt_value(CAP.getTheoryweight()==null?0:CAP.getTheoryweight());
				if ("M0004".equals(cap.getMachine_code()) || "M0005".equals(cap.getMachine_code()) 
						|| "M0006".equals(cap.getMachine_code()) || "M0009".equals(cap.getMachine_code())) {
					//退火 (投入量=产出量=实重)
					cap.setInput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());
					cap.setOutput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());
				}else if ("M0010".equals(cap.getMachine_code())) {
					//酸洗的特色处理
					//投入量:取产线的上料量
					String condition = " material_no_src = '"+cap.getMat_coil_no()+"'";
					List<MesPlmM> mpmList = this.getMapper(MesPlmMMapper.class).findWithCondition(null, condition, null, 0, 1);
					if (mpmList!=null && mpmList.size()>0) {						
						cap.setInput_wgt_value(mpmList.get(0).getMtr_thr_wgt()==null?0d:mpmList.get(0).getMtr_thr_wgt()/1000);
					}
				}
			} else if ("102301".equals(cap.getWeight_type_no())) {
				//净重交货：分机组进行处理				
				if ("M0001".equals(cap.getMachine_code()) || "M0002".equals(cap.getMachine_code())) {
					//大纵剪和小纵剪 (投入量=理重	产出量=实重)
					cap.setInput_wgt_value(CAP.getTheoryweight()==null?0:CAP.getTheoryweight());
					cap.setOutput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());										
				}else if ("M0003".equals(cap.getMachine_code())) {
					//3mm横剪(投入量=汇总	 产出量=实重)
					cap.setOutput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());
					Double inweight = this.getMapper(CostAcmProdMapper.class).doQuary3mmInweight(cap.getMat_coil_no(),bfpd.getPrd_num());
					cap.setInput_wgt_value(inweight==null?0:inweight);
				}else if ("M0004".equals(cap.getMachine_code()) || "M0005".equals(cap.getMachine_code()) 
						|| "M0006".equals(cap.getMachine_code()) || "M0009".equals(cap.getMachine_code())) {
					//退火 (投入量=产出量=实重)
					cap.setInput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());
					cap.setOutput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());
				}else if ("M0007".equals(cap.getMachine_code()) || "M0008".equals(cap.getMachine_code())) {
					//轧机 和 平整(投入量=产出量=实重)
					cap.setInput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());
					cap.setOutput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());
				}if ("M0010".equals(cap.getMachine_code())) {							
					//投入量:取产线的上料量
					String condition = " material_no_src = '"+cap.getMat_coil_no()+"'";
					List<MesPlmM> mpmList = this.getMapper(MesPlmMMapper.class).findWithCondition(null, condition, null, 0, 1);
					if (mpmList!=null && mpmList.size()>0) {						
						cap.setInput_wgt_value(mpmList.get(0).getMtr_thr_wgt()==null?0d:mpmList.get(0).getMtr_thr_wgt()/1000);
					}
					//产出 = 实际量
					cap.setOutput_wgt_value(CAP.getFactweight()==null?0:CAP.getFactweight());										
				}
			}			
			
			// 暂时注销：20230621刘侣
			// 重写逻辑：区分委托加工和自制；20230525刘侣
			// 依据合同类型来判断是否是委托加工，只有来料加工合同是委托加工，其他的都是原料或者自制卷：
			// 投料类型(A原料卷、B自制卷 C委托卷)
			// C:委托卷：合同类型一定是来料加工合同
//			if ("101606".equals(CAP.getOrder_memo())) {
//				cap.setInput_type("C");
//			} else if (cap.getPrv_org_code()!=null) {
//				// B:自制卷：上工序不为null
//				cap.setInput_type("B");
//			} else if (cap.getPrv_org_code()==null) {
//				// A:原料卷：上工序为null
//				cap.setInput_type("A");
//			}
			
			// end 20230621
			
			
			// 恢复：20230621刘侣
			// 这些旧逻辑先注释：
			//投料类型(A原料卷、B自制卷 C委托卷)
			//C:委托卷：毛重交货 
			if ("102302".equals(cap.getWeight_type_no())) {
				cap.setInput_type("C");
			}
			//B:自制卷：(冷轧，酸洗订单 && 上工序不为null) || (净重交货，上工序不为null) || 
			if ((("4".equals(cap.getOrder_nature())|| "5".equals(cap.getOrder_nature())) && cap.getPrv_org_code()!=null) || 
					("102301".equals(cap.getWeight_type_no()) && cap.getPrv_org_code()!=null)) {
				cap.setInput_type("B");
			}
			//A:原料卷：(冷轧，酸洗订单 && 上工序为null) || (净重交货，上工序为null)
			if ((("4".equals(cap.getOrder_nature())|| "5".equals(cap.getOrder_nature())) && cap.getPrv_org_code()==null) || 
					("102301".equals(cap.getWeight_type_no()) && cap.getPrv_org_code()==null)) {
				cap.setInput_type("A");
			}	
			// end 
			// end 20230621
			
			
			//业务类型(A自制加工 B委托加工)
			if ("C".equals(cap.getInput_type())) { //投料类型是委托卷，业务类型也是委托卷。其它都是自制卷
				cap.setOrder_model("B");
			}else {
				cap.setOrder_model("A");
			}
			
			//设置初始投料单价和初始投料金额
			if (cap.getPrv_org_code()==null || "".equals(cap.getPrv_org_code())) {
				if ("B".equals(cap.getOrder_model())) {
					//委托加工的初始单价和初始金额，默认为0
					//单位原料成本 = 初始投料金额/产出量
					cap.setOriginal_price_value(0d);
					cap.setOriginal_amount_value(0d);
					cap.setMat_price(0d);			
				}else {
					//获取原料单价和初始金额
					PurMatD pmd = this.getMapper(PurMatDMapper.class).findById(CAP.getMat_coil_no());
					if (pmd!=null) {				
						//原始单价 == 采购单价
						if (rate.doubleValue()!=0) {
							Double Original_price_value = pmd.getPur_price()==null?0:pmd.getPur_price()/rate;
							cap.setOriginal_price_value(Original_price_value);
							//原始投料金额
							cap.setOriginal_amount_value(Original_price_value * (cap.getInput_wgt_value()==null?0:cap.getInput_wgt_value()));
						}
						//单位原料成本 = 初始投料金额/产出量
						if (cap.getOutput_wgt_value()!=null && cap.getOutput_wgt_value().doubleValue()!=0) {
							cap.setMat_price(cap.getOriginal_amount_value()/cap.getOutput_wgt_value());					
						}
					}					
				}
			}			
			cap.setValid_flg("1");//默认有效
			cap.setAudit_flg("0");//默认未审核
			cap.setCreate_man(userName);
			cap.setCreate_time(now);			
			this.getMapper(CostAcmProdMapper.class).insert(cap);			
		}
		
		//2.处理大小纵剪的头尾卷 and (平整和轧机)
		CostAcmProd cap = new CostAcmProd();
		cap.setPrd_num(bfpd.getPrd_num());
		cap.setIs_tw("1");
		List<CostAcmProd> capTwList = this.getMapper(CostAcmProdMapper.class).find(cap, 0, 0);
		if (capTwList!=null && capTwList.size()>0) {
			for (CostAcmProd capTw : capTwList) {
				//获取相同组织，相同原料卷号，不是头尾卷的归集信息
				CostAcmProd notTw = new CostAcmProd();
				notTw.setPrd_num(bfpd.getPrd_num());
				notTw.setMat_coil_no(capTw.getMat_coil_no());
				notTw.setOrg_code(capTw.getOrg_code());
				notTw.setIs_tw("0");
				notTw.setIs_bs("0");
				String condition = " and machine_code in ('M0001','M0002') ";
				List<CostAcmProd> notTwList = this.getMapper(CostAcmProdMapper.class).findWithCondition(notTw, condition, null, 0, 0);
				if (notTwList!=null && notTwList.size()>0) {
					for (CostAcmProd finalTw : notTwList) {
						//System.out.println("不是头尾卷的重量"+(finalTw.getInput_wgt_value()==null?0:finalTw.getInput_wgt_value()));
						//System.out.println("头尾卷的重量"+(capTw.getInput_wgt_value()==null?0:capTw.getInput_wgt_value()));
						//(非头尾卷)投入量 =不是头尾卷的投入量-头尾卷的投入量：查询不能再包含边丝卷（20220406 treals）
						finalTw.setInput_wgt_value((finalTw.getInput_wgt_value()==null?0:finalTw.getInput_wgt_value())-
								(capTw.getInput_wgt_value()==null?0:capTw.getInput_wgt_value()));
						this.getMapper(CostAcmProdMapper.class).update(finalTw);
					}
				}
			}
		}
		
		//3.处理平整和轧机的不是头尾卷的数据
		String condition = " and machine_code in ('M0007','M0008') and is_tw = '0' and prd_num = '"+bfpd.getPrd_num()+"'";
		List<CostAcmProd> zpCapList = this.getMapper(CostAcmProdMapper.class).findWithCondition(null, condition, "org_code", 0, 0);
		if (zpCapList!=null && zpCapList.size()>0) {	
			for (CostAcmProd zpCap : zpCapList) {				
				//判断同组织，同原料卷号的归集数据是否存在多条
				String sameCondition = " and org_code = '"+zpCap.getOrg_code()+"' and mat_coil_no = '"+ zpCap.getMat_coil_no()+"' and prd_num = '"+bfpd.getPrd_num()+"' and order_id = '"+zpCap.getOrder_id()+"'";
				int sameCount = this.getMapper(CostAcmProdMapper.class).countWithCondition(null, sameCondition);
				if (sameCount==0) {
					continue;
				}else if (sameCount >= 1) {
					Double prvOutWeight = 0d;
					//多条数据：根据产量的占比，去分配投入量
					if ("C013".equals(zpCap.getOrg_code())) {	//轧机	
						List<MesRcmM> srcList = this.getMapper(CostAcmProdMapper.class).doQuaryMrmForCmCostAcmProd(zpCap.getMat_coil_no(),zpCap.getOrder_id(), zpCap.getPrd_num());
						if (srcList!=null && srcList.size()>0) {							
							for (MesRcmM mrm : srcList) {
								prvOutWeight += mrm.getMtr_act_wgt()/1000;
							}
						}
					}else if ("C012".equals(zpCap.getOrg_code())) { //平整
						List<MesTpmM> srcList = this.getMapper(CostAcmProdMapper.class).doQuaryMtmForCmCostAcmProd(zpCap.getMat_coil_no(),zpCap.getOrder_id(), zpCap.getPrd_num());
						if (srcList!=null && srcList.size()>0) {
							for (MesTpmM mtm : srcList) {
								prvOutWeight += mtm.getMtr_act_wgt()/1000;
							}
						}
					}

					System.out.println(zpCap.getMat_coil_no() + ": " + prvOutWeight);
					if (prvOutWeight==0) {
						//未找到上工序，则重量不变
						continue;
					}
					//获取同组织总的产量
					List<CostAcmProd> sameCapList = this.getMapper(CostAcmProdMapper.class).findWithCondition(null, sameCondition, null, 0, 0);
					Double sameOutWeight = 0d;
					if (sameCapList!=null && sameCapList.size()>0) {
						for (CostAcmProd sameCap : sameCapList) {
							sameOutWeight += sameCap.getOutput_wgt_value();
						}

						for (CostAcmProd sCap : sameCapList) {
							//单条数据反写投入量
							CostAcmProd finalZpCap = new CostAcmProd();
							finalZpCap.setAcm_id(sCap.getAcm_id());
							finalZpCap.setInput_wgt_value(prvOutWeight*(sCap.getOutput_wgt_value()/sameOutWeight));
							// 轧机没必要根据投入量去返写：20220701 刘侣 要不限制同订单
							// 之前是因为分卷的时候每个产出卷的理重都是投料卷的总理重，而不是现在这种和产出卷一样的值；
							this.getMapper(CostAcmProdMapper.class).update(finalZpCap);
						}
					}									
				}	
			}
		}
		
		//4.处理大小纵剪的同组织，不同仓库(产品状态)的数据：
		List<CostAcmProd> capList4 = this.getMapper(CostAcmProdMapper.class).doQuary12mmAnd4mm(bfpd.getPrd_num());
		if (capList4!=null && capList4.size()>0) {
			for (CostAcmProd cap4 : capList4) {
				//相同组织，相同成本期间，相同原料卷号
				List<CostAcmProd> list = this.getMapper(CostAcmProdMapper.class).find(cap4, 0, 0);
				if (list!=null && list.size()>0) {
					for (CostAcmProd costAcmProd : list) {
						CostAcmProd finalCap = new CostAcmProd();
						finalCap.setAcm_id(costAcmProd.getAcm_id());
						if ("B".equals(costAcmProd.getProd_state())) {
							//中间品的产出量= 实重
							finalCap.setOutput_wgt_value(costAcmProd.getFactweight());
						}else if ("A".equals(costAcmProd.getProd_state())) {
							//产成品的产出量 = 实重
							finalCap.setOutput_wgt_value(costAcmProd.getFactweight());
						}else {
							continue;
						}
						this.getMapper(CostAcmProdMapper.class).update(finalCap);
					}
				}
			}
		}
		
		//5.处理横剪的业务类型
		doCostAcmProd3mm(bfpd.getPrd_num());
		
		//20200103 归集数量过多，先不进行入库和出库量的归集
		//this.getBean(CmCostAcmInnServiceImpl.class).doInsertCmCostAcmInn(cp);
		//this.getBean(CmCostAcmOutServiceImpl.class).doInsertCmCostAcmOut(cp);
		rm.setState("200");
		rm.setMsgInfo("投入产出归集成功");
		return rm;
	}
	
	
	/**
	 * 投入产出汇总统计
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryGbSumCostAcmProd(CommonPage<CostAcmProd> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CostAcmProd cap = cp.getObject();
		try {
			List<CostAcmProd> list = this.getMapper(CostAcmProdMapper.class).doQueryGbSumCostAcmProd(cap.getPrd_num());
			rm.setData(list);
			rm.setState("200");
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 处理横剪的数据
	 * @param prd_num
	 */
	public void doCostAcmProd3mm(String prd_num){
		String condition = "and prd_num = '"+prd_num+"' and machine_code = 'M0003'";
		List<CostAcmProd> capList = this.getMapper(CostAcmProdMapper.class).findWithCondition(null, condition, null, 0, 0);
		if (CollectionUtils.isNotEmpty(capList)) {
			for (CostAcmProd cap : capList) {
				String sql = "select count(1) from mes_cr_cross_cutting_m t left join ydm_product_inlist ypi on t.material_no = ypi.coilno "
						+ " where t.material_no_src = '"+cap.getMat_coil_no()+"' and ypi.storageattr = '500210'";
				int count = this.getMapper(CostAcmProdMapper.class).doQuary3mm(sql);
				if (count > 0) {
					cap.setOrder_model("B");//委托加工
					cap.setInput_type("C");//委托卷
					cap.setOriginal_price_value(0d);
					cap.setOriginal_amount_value(0d);
					this.getMapper(CostAcmProdMapper.class).update(cap);
				}
			}
		}
	}
}
