/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-07-23
 * 描述            ：在制品盘点表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.BaseOrgCmpMapper;
import market.Cm.mapper.CmCostAcmIprodMapper;
import market.Cm.service.CmCostAcmIprodService;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.BaseOrgCmp;
import market.Cm.vo.CmCostAcmIprod;
import market.Cm.vo.CostAcmProd;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Mat.mapper.PurMatDMapper;
import market.Pms.Mat.vo.PurMatD;

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="CmCostAcmIprodService")
public class CmCostAcmIprodServiceImpl extends BaseServiceImpl<CmCostAcmIprod,Object> implements CmCostAcmIprodService {
	
	/**
	 * 在制品盘点：查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCmCostAcmIprod(CommonPage<CmCostAcmIprod> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmCostAcmIprod cap = cp.getObject();		 
		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 (cap.getPrd_num()!=null && !"".equals(cap.getPrd_num())) {
				swhere+=" and prd_num like '%"+cap.getPrd_num()+"%'";//成本期间
			}			
			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()+"'";//是否审核
			}
			List<CmCostAcmIprod> list = this.getMapper(CmCostAcmIprodMapper.class).findWithCondition(null, swhere, "prd_num desc,order_model,mat_coil_no", 0, 0);
			rm.setState("200");
			rm.setData(list);
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 在制品盘点：新增
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doInsertCmCostAcmIprod(CommonPage<CmCostAcmIprod> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		CmCostAcmIprod ccai = cp.getObject();
		if (ccai.getMat_coil_no()==null || "".equals(ccai.getMat_coil_no())) {
			throw new Exception("原料卷号不能为空");
		}
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(ccai.getPrd_num());
		if (b==null) {
			throw new Exception("请传入成本期间");
		}
		//判断成本期间内的原料卷号是否重复
		CmCostAcmIprod CCAI = new CmCostAcmIprod();
		CCAI.setPrd_num(ccai.getPrd_num());
		CCAI.setMat_coil_no(ccai.getMat_coil_no());
		int count = this.getMapper(CmCostAcmIprodMapper.class).count(CCAI);
		if (count>0) {
			throw new Exception("成本期间【"+ccai.getPrd_num()+"】内存在原料卷号【"+ccai.getMat_coil_no()+"】的在制品盘点数据");
		}
		ccai.setValid_flg("1");//有效
		ccai.setAudit_flg("0");//未审核
		ccai.setCreate_man(userName);
		ccai.setCreate_time(new Date());
		this.getMapper(CmCostAcmIprodMapper.class).insert(ccai);
		rm.setState("200");
		rm.setMsgInfo("新增成功");
		return rm;
	}
	
	/**
	 * 在制品盘点：修改
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doUpdateCmCostAcmIprod(CommonPage<CmCostAcmIprod> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		CmCostAcmIprod ccai = cp.getObject();
		if (ccai.getMat_coil_no()==null || "".equals(ccai.getMat_coil_no())) {
			throw new Exception("原料卷号不能为空");
		}
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(ccai.getPrd_num());
		if (b==null) {
			throw new Exception("请传入成本期间");
		}
		//判断成本期间内的原料卷号是否重复
		CmCostAcmIprod CCAI = new CmCostAcmIprod();
		CCAI.setPrd_num(ccai.getPrd_num());
		CCAI.setMat_coil_no(ccai.getMat_coil_no());
		int count = this.getMapper(CmCostAcmIprodMapper.class).count(CCAI);
		if (count<=0) {
			throw new Exception("成本期间【"+ccai.getPrd_num()+"】原料卷号【"+ccai.getMat_coil_no()+"】的在制品盘点数据不存在");
		}
		ccai.setUpdate_man(userName);		 		 
		ccai.setUpdate_time(new Date());
		this.getMapper(CmCostAcmIprodMapper.class).update(ccai);
		rm.setState("200");
		rm.setMsgInfo("修改成功");
		return rm;
	}

	/**
	 * 在制品盘点：归集
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doGroupCmCostAcmIprod(CommonPage<CmCostAcmIprod> cp) throws Exception{
		ResultModel rm = new ResultModel();
		Date now = new Date();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		CmCostAcmIprod cai = cp.getObject();
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(cai.getPrd_num());
		if (b==null) {
			throw new Exception("请传入成本期间");
		}
		//0.判断当前成本期间是否进行归集
		int count = this.getMapper(CmCostAcmIprodMapper.class).count(cai);
		if (count > 0) {
			throw new Exception("当前成本期间【"+cai.getPrd_num()+"】已经进行在制品盘点归集");
		}
		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.查找归集期间的所在投料时间内的的入库数据		
		List<CmCostAcmIprod> caiList = this.getMapper(CmCostAcmIprodMapper.class).doQuaryMesForCmCostAcmIprod(cai,startTime,endTime);
		if (caiList==null || caiList.size()<=0) {
			throw new Exception("未找到成本期间【"+cai.getPrd_num()+"】需要进行在制品盘点的数据");
		}
		for (CmCostAcmIprod CAI : caiList) {		
			CmCostAcmIprod ccai = new CmCostAcmIprod(); 
			ccai.setPlan_id(null);//生产计划号 
			ccai.setMat_coil_no(CAI.getMat_coil_no());//原料卷号
			ccai.setOrder_id(CAI.getOrder_id());//订单号
			//订单属性(1原料卷  2需加工  3非计划)
			ccai.setOrder_nature(CAI.getOrder_nature());
			//计重方式(102302毛重   102301净重)
			ccai.setWeight_type_no(CAI.getWeight_type_no());
			ccai.setWeight_type_name(CAI.getWeight_type_name());
			
			//投料类型(A原料卷、B自制卷 C委托卷)
			//C:委托卷：毛重交货 
			if ("102302".equals(ccai.getWeight_type_no())) {
				ccai.setInput_type("C");
			}
			//B:自制卷：(冷轧，酸洗订单 && 上工序不为null) || (净重交货，上工序不为null) || 
			if ((("4".equals(ccai.getOrder_nature())|| "5".equals(ccai.getOrder_nature())) && ccai.getPrv_org_code()!=null) || 
				("102301".equals(ccai.getWeight_type_no()) && ccai.getPrv_org_code()!=null)) {
				ccai.setInput_type("B");
			}
			//A:原料卷：(冷轧，酸洗订单 && 上工序为null) || (净重交货，上工序为null)
			if ((("4".equals(ccai.getOrder_nature())|| "5".equals(ccai.getOrder_nature())) && ccai.getPrv_org_code()==null) || 
				("102301".equals(ccai.getWeight_type_no()) && ccai.getPrv_org_code()==null)) {
				ccai.setInput_type("A");
			}
			
			//业务类型(A自制加工 B委托加工)
			if ("C".equals(ccai.getInput_type())) { //投料类型是委托卷，业务类型也是委托卷。其它都是自制卷
				ccai.setOrder_model("B");
			}else {
				ccai.setOrder_model("A");
			}
			//交货状态代码 
			ccai.setDelivery_state_code(CAI.getDelivery_state_code());
			ccai.setDelivery_state_desc(CAI.getDelivery_state_desc());
			//牌号代码
			ccai.setSteel_code(CAI.getSteel_code());
			ccai.setSteel_name(CAI.getSteel_name());
			//获取上工序机台代码及名称：通过原料卷号，机台，仓库
			CostAcmProd cap = new CostAcmProd();
			cap.setMat_coil_no(CAI.getMat_coil_no());//原料卷号			
			cap.setMachine_code(CAI.getMachine_code());//机台代码
			cap.setStorageattr(CAI.getStorageattr());//仓库
			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());									
				}
			}
			
			PurMatD pmd = this.getMapper(PurMatDMapper.class).findById(CAI.getMat_coil_no());
			if (pmd!=null) {				
				//原始单价 == 采购单价
				ccai.setOriginal_price_value(pmd.getPur_price()==null?0:pmd.getPur_price());
				//原始投料金额
				ccai.setOriginal_amount_value(ccai.getOriginal_price_value() * (pmd.getPur_num()==null?0:pmd.getPur_num()));
			}
			//投入量
			if (CAI.getInput_wgt_value()!=null) {
				ccai.setInput_wgt_value(CAI.getInput_wgt_value()/1000);			
			}
			//成本项目
			ccai.setItem_code(CAI.getItem_code());
			ccai.setItem_name(CAI.getItem_name());			
			//产品类别代码:父级项目编码
			ccai.setParent_item_code(CAI.getParent_item_code());
			ccai.setParent_item_name(CAI.getParent_item_name());			
			//成本组织
			ccai.setOrg_code(CAI.getOrg_code());
			ccai.setOrg_name(CAI.getOrg_name());						
			//成本期间 和 生产时间 
			ccai.setPrd_num(cai.getPrd_num());
			ccai.setProd_time(null);		
			ccai.setValid_flg("1");//默认有效
			ccai.setAudit_flg("0");//默认未审核
			ccai.setCreate_man(userName);
			ccai.setCreate_time(now);
			this.getMapper(CmCostAcmIprodMapper.class).insert(ccai);
		}
		rm.setState("200");
		rm.setMsgInfo("在制品盘点归集成功");
		return rm;
	}
	
	/**
	 * 在制品盘点：审核和反审
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeCmCostAcmIprodAuditFlg(CommonPage<CmCostAcmIprod> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		String opr = cp.getMemo1();
		List<CmCostAcmIprod> caiList = cp.getObjectList();
		if (caiList==null || caiList.size()<=0) {
			throw new Exception("请传入参数");
		}
		for (CmCostAcmIprod cai : caiList) {			
			if (cai.getPrd_num()==null || "".equals(cai.getPrd_num())) {
				throw new Exception("请传入成本期间");
			}
			if (cai.getMat_coil_no()==null || "".equals(cai.getMat_coil_no())) {
				throw new Exception("请传入原料卷号");
			}
			//判断数据是否存在
			CmCostAcmIprod CCAI = this.getMapper(CmCostAcmIprodMapper.class).findById(cai.getMat_coil_no(),cai.getPrd_num());
			if (CCAI == null) {
				throw new Exception("成本期间【"+cai.getPrd_num()+"】内不存在原料卷号【"+cai.getMat_coil_no()+"】的在制品盘点数据");
			}
			
			if ("0".equals(opr)) {
				//反审操作判断数据是否还未审核
				if ("0".equals(CCAI.getAudit_flg())) {
					throw new Exception("成本期间【"+cai.getPrd_num()+"】的原料卷号【"+cai.getMat_coil_no()+"】还未审核，无法反审");
				}
				cai.setAudit_flg("0");
			} else if ("1".equals(opr)) {
				//审核操作判断数据是否已经审核
				if ("1".equals(CCAI.getAudit_flg())) {
					throw new Exception("成本期间【"+cai.getPrd_num()+"】的原料卷号【"+cai.getMat_coil_no()+"】已经审核，无需继续审核");
				}
				cai.setAudit_flg("1");
			}
			cai.setAudit_man(userName);//审核人
			cai.setAudit_time(now);//审核时间			
			this.getMapper(CmCostAcmIprodMapper.class).update(cai);
		}
		rm.setState("200");
		rm.setMsgInfo(("0".equals(opr)?"反审":"审核")+ "操作成功");
		return rm;
	}
	
	/**
	 * 在制品盘点：删除
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteCmCostAcmIprod(CommonPage<CmCostAcmIprod> cp) throws Exception{
		ResultModel rm = new ResultModel();
		List<CmCostAcmIprod> ccaiList = cp.getObjectList();
		if (ccaiList==null || ccaiList.size()<=0) {
			throw new Exception("请传入参数");
		}
		
		for (CmCostAcmIprod cai : ccaiList) {
			CmCostAcmIprod CCAI = this.getMapper(CmCostAcmIprodMapper.class).findById(cai.getMat_coil_no(),cai.getPrd_num());
			if (CCAI == null) {
				throw new Exception("成本期间【"+cai.getPrd_num()+"】内不存在原料卷号【"+cai.getMat_coil_no()+"】的在制品盘点数据");
			}
			if ("1".equals(CCAI.getAudit_flg())) {
				throw new Exception("成本期间【"+cai.getPrd_num()+"】的原料卷号【"+cai.getMat_coil_no()+"】已经审核，无法删除");
			}
			this.getMapper(CmCostAcmIprodMapper.class).delete(cai.getMat_coil_no(),cai.getPrd_num());
		}		
		rm.setState("200");
		rm.setMsgInfo("删除成功");
		return rm;		
	}
	
}
