/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2020-03-17
 * 描述            ：投入产出归集表
 * 注意事项     ：
 * 遗留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.BaseOrgCmpMapper;
import market.Cm.mapper.CmCostAcmProdHMapper;
import market.Cm.mapper.CostAcmProdMapper;
import market.Cm.service.CmCostAcmProdHService;
import market.Cm.vo.BaseOrgCmp;
import market.Cm.vo.CmCostAcmProdH;
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.Pms.Mat.mapper.PurMatDMapper;
import market.Pms.Mat.vo.PurMatD;

import org.apache.commons.beanutils.BeanUtils;
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="CmCostAcmProdHService")
public class CmCostAcmProdHServiceImpl extends BaseServiceImpl<CmCostAcmProdH,Object> implements CmCostAcmProdHService {
	
	/**
	 * 查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCostAcmProd(CommonPage<CmCostAcmProdH> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmCostAcmProdH cap = cp.getObject();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<CmCostAcmProdH> pm = new PageModel<CmCostAcmProdH>(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())) {
				swhere+=" and mat_coil_no like '%"+cap.getMat_coil_no()+"%'";//原料卷号
			}
			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 (startTime!=null && !"".equals(startTime)) {
				swhere += " and prd_num >= '"+startTime+"'";//查询归集开始时间
			}
			if (endTime!=null && !"".equals(endTime)) {
				swhere += " and prd_num <= '"+endTime+"'";//查询归集结束时间
			}
			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(CmCostAcmProdHMapper.class).findWithCondition(null, swhere, "prd_num desc,mat_coil_no,prod_time", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(CmCostAcmProdHMapper.class).countWithCondition(null, swhere));			
			rm.setState("200");
			rm.setData(pm);
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 投入产出归集（日归集）
	 * @param cp [{"startTime":"2020-03-22","endTime":"2020-03-24"}]
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertCostAcmProd(CommonPage<CmCostAcmProdH> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		CmCostAcmProdH bfpd = cp.getObject();
		String startTime = cp.getStartTime() + " 00:00:00";
		String endTime = cp.getEndTime() + " 23:59:59";		
		//判断成本期间内是否已经进行了归集
		String swhere = "prod_time >= to_date('"+startTime+"', 'yyyy-MM-dd HH24:mi:ss') "
				+ "and prod_time <= to_date('"+endTime+"','yyyy-MM-dd HH24:mi:ss')";
		int count = this.getMapper(CmCostAcmProdHMapper.class).countWithCondition(null, swhere);		
		if (count > 0) {
			throw new Exception("当前成本区间【"+cp.getStartTime()+"--"+cp.getEndTime()+"】中存在已经归集的日期");
		}

		Date now = new Date();	
		//1.查找归集期间的所在投料时间内的的入库数据
		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(cp.getEndTime().replace("-", "")+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();
			String prd_num =new SimpleDateFormat("yyyyMMdd").format(CAP.getIndate());
			cap.setPrd_num(prd_num);//成本期间 
			//设置主键
			ser_num++;
			cap.setAcm_id("GG"+ser_num);
			//获取上工序机台代码及名称：通过原料卷号，机台，仓库
			cap.setMat_coil_no(CAP.getMat_coil_no());//原料卷号
			//cap.setCoilno(CAP.getCoilno());//钢卷号(子卷号)
			cap.setMachine_code(CAP.getMachine_code());//机台代码
			cap.setMachine_name(CAP.getMachine_name());	
			
			// 取最后一次入库的仓库：20230726刘侣
//			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
			// end
			
			cap.setIs_tw(CAP.getIs_tw());
			List<BaseOrgCmp> BOCList = this.getMapper(BaseOrgCmpMapper.class).doQuaryPrvOrgInfo(cap);		
			if (BOCList!=null && BOCList.size()>0) {
				BaseOrgCmp BOC = BOCList.get(0);
				if (BOC!=null && BOC.getOrg_code()!=null && !"".equals(BOC.getOrg_code())) {
					cap.setPrv_org_code(BOC.getOrg_code());
					cap.setPrv_org_name(BOC.getOrg_name());									
				}
			}
			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("净重");
			}
			//没有订单的头尾卷不进行归集
			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());										
				}
			}			
			
			//投料类型(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");
			}				
			//业务类型(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);
			cap.setPk_ask_desc(CAP.getPk_ask_desc());
			cap.setOrder_memo(CAP.getOrder_memo());
			CmCostAcmProdH capH = new CmCostAcmProdH();
			//1.除序号外全部复制
			BeanUtils.copyProperties(capH, cap);
			this.getMapper(CmCostAcmProdHMapper.class).insert(capH);			
		}	
		
		rm.setState("200");
		rm.setMsgInfo("投入产出归集成功");
		return rm;
	}
	
	/**
	 * 删除投入产出归集信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteCostAcmProd(CommonPage<CmCostAcmProdH> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String startTime = cp.getStartTime() + " 00:00:00";
		String endTime = cp.getEndTime() + " 23:59:59";
		
		//判断成本期间内是否已经进行了归集
		String swhere = "prod_time >= to_date('"+startTime+"', 'yyyy-MM-dd HH24:mi:ss') "
				+ "and prod_time <= to_date('"+endTime+"','yyyy-MM-dd HH24:mi:ss')"
						+ " and audit_flg = '1'";
		int count = this.getMapper(CmCostAcmProdHMapper.class).countWithCondition(null, swhere);
		if (count > 0) {
			throw new Exception("当前成本区间已经存在已经审核归集信息,无法删除");
		}
		
		//删除成本期间内的信息
		this.getMapper(CmCostAcmProdHMapper.class).deleteCmCostAcmProdHByPrdnum(startTime,endTime);
		
		rm.setState("200");
		rm.setMsgInfo("投入产出日归集信息删除成功");
		return rm;		
	}
}
