/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-08-31
 * 描述            ：入库信息归集表
 * 注意事项     ：
 * 遗留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.CmCostAcmInnMapper;
import market.Cm.service.CmCostAcmInnService;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.BaseOrgCmp;
import market.Cm.vo.CmCostAcmInn;
import market.Cm.vo.CostAcmProd;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;

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="CmCostAcmInnService")
public class CmCostAcmInnServiceImpl extends BaseServiceImpl<CmCostAcmInn,Object> implements CmCostAcmInnService {

	/**
	 * 入库信息归集查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCmCostAcmInn(CommonPage<CmCostAcmInn> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmCostAcmInn cai = cp.getObject();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<CmCostAcmInn> pm = new PageModel<CmCostAcmInn>(pageIndex,pageSize);
		try {
			String swhere = "";			
			if (cai.getOrder_id()!=null && !"".equals(cai.getOrder_id())) {
				swhere+=" and order_id like '%"+cai.getOrder_id()+"%'";//订单号
			}
			if (cai.getMat_coil_no()!=null && !"".equals(cai.getMat_coil_no())) {
				swhere+=" and mat_coil_no like '%"+cai.getMat_coil_no()+"%'";//原料卷号
			}
			if (cai.getOrg_name()!=null && !"".equals(cai.getOrg_name())) {
				swhere+=" and org_name like '%"+cai.getOrg_name()+"%'";//成本组织
			}
			if (cai.getOrg_code()!=null && !"".equals(cai.getOrg_code())) {
				swhere+=" and org_code = '"+cai.getOrg_code()+"'";//成本组织
			}
			if (cai.getPrd_num()!=null && !"".equals(cai.getPrd_num())) {
				swhere+=" and prd_num like '%"+cai.getPrd_num()+"%'";//成本期间
			}
			if (startTime!=null && !"".equals(startTime)) {
				swhere += " and to_char(in_time, 'yyyy-mm-dd hh24:mi:ss') >='"
						+ startTime +" 00:00:00"+ "'";//生产时间起
			}
			if (endTime!=null && !"".equals(endTime)) {
				swhere += " and to_char(in_time, 'yyyy-mm-dd hh24:mi:ss') <='"
						+ endTime +" 23:59:59"+ "'";//生产时间止
			}
			if (cai.getOrder_model()!=null && !"".equals(cai.getOrder_model())) {
				swhere+=" and order_model = '"+cai.getOrder_model()+"'";//是否有效
			}
			if (cai.getInput_type()!=null && !"".equals(cai.getInput_type())) {
				swhere+=" and input_type = '"+cai.getInput_type()+"'";//是否有效
			}
			if (cai.getAudit_flg()!=null && !"".equals(cai.getAudit_flg())) {
				swhere += " and audit_flg = '"+cai.getAudit_flg()+"'";//是否审核
			}
			pm.setRows(this.getMapper(CmCostAcmInnMapper.class).findWithCondition(null, swhere, "prd_num desc,mat_coil_no,in_time", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(CmCostAcmInnMapper.class).countWithCondition(null, swhere));			
			rm.setData(pm);
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 入库信息归集
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertCmCostAcmInn(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("请传入成本期间");
		}
		//判断成本期间内是否已经进行了归集
		CmCostAcmInn CCAI = new CmCostAcmInn();
		CCAI.setPrd_num(bfpd.getPrd_num());//成本期间
		int count = this.getMapper(CmCostAcmInnMapper.class).count(CCAI);
		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.查找归集期间的所在投料时间内的的入库数据
		List<CmCostAcmInn> caiList = this.getMapper(CmCostAcmInnMapper.class).doQuaryYdmProductInlistForCcai(startTime,endTime);
		if (caiList==null || caiList.size()<=0) {
			throw new Exception("未找到数据");
		}
		
		Long ser_num = Long.parseLong(bfpd.getPrd_num()+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+"0000");
		for (CmCostAcmInn CAI : caiList) {			
			CmCostAcmInn cai = new CmCostAcmInn();			
			//设置主键
			ser_num++;
			cai.setIn_id("IN"+ser_num);
			//获取上工序机台代码及名称：通过原料卷号，机台，仓库
			cai.setMat_coil_no(CAI.getMat_coil_no());//原料卷号
			//cap.setMachine_code(CAP.getMachine_code());//机台代码
			//cap.setMachine_name(CAP.getMachine_name());
			cai.setOrder_id(CAI.getOrder_id());//订单号
			//订单属性(1原料卷  2需加工  3非计划)
			cai.setOrder_nature(CAI.getOrder_nature());
			//计重方式(102302毛重   102301净重)
			cai.setWeight_type_no(CAI.getWeight_type_no());
			cai.setWeight_type_name(CAI.getWeight_type_name());
			//订单号为null,默认是净重交货
			if (CAI.getOrder_id()==null || "".equals(CAI.getOrder_id())) {
				cai.setWeight_type_no("102301");
				cai.setWeight_type_name("净重");
			}			
			//投料类型(A原料卷、B自制卷 C委托卷)
			//C:委托卷：毛重交货 
			if ("102302".equals(cai.getWeight_type_no())) {
				cai.setInput_type("C");
			}
			CostAcmProd cap = new CostAcmProd();
			cap.setMat_coil_no(CAI.getMat_coil_no());
			cap.setMachine_code(CAI.getMachine_code());
			cap.setStorageattr(CAI.getStock_code());
			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());									
				}
			}
			//B:自制卷：(冷轧，酸洗订单 && 上工序不为null) || (净重交货，上工序不为null) || 
			if ((("4".equals(cai.getOrder_nature())|| "5".equals(cai.getOrder_nature())) && cai.getPrv_org_code()!=null) || 
					("102301".equals(cap.getWeight_type_no()) && cai.getPrv_org_code()!=null)) {
				cai.setInput_type("B");
			}
			//A:原料卷：(冷轧，酸洗订单 && 上工序为null) || (净重交货，上工序为null)
			if ((("4".equals(cai.getOrder_nature())|| "5".equals(cai.getOrder_nature())) && cai.getPrv_org_code()==null) || 
					("102301".equals(cai.getWeight_type_no()) && cai.getPrv_org_code()==null)) {
				cai.setInput_type("A");
			}
			//业务类型(A自制加工 B委托加工)
			if ("C".equals(cai.getInput_type())) { //投料类型是委托卷，业务类型也是委托卷。其它都是自制卷
				cai.setOrder_model("B");
			}else {
				cai.setOrder_model("A");
			}
			//交货状态代码 
			cai.setDelivery_state_code(CAI.getDelivery_state_code()==null?" ":CAI.getDelivery_state_code());
			cai.setDelivery_state_desc(CAI.getDelivery_state_desc()==null?" ":CAI.getDelivery_state_desc());			
			//牌号代码
			cai.setSteel_code(CAI.getSteel_code());
			cai.setSteel_name(CAI.getSteel_name());
			//仓库
			cai.setStock_code(CAI.getStock_code());
			cai.setStock_name(CAI.getStock_name());
			//产品状态(A成品 B中间品 C在制品)
			if ("500202".equals(CAI.getStock_code())) {
				cai.setProd_state("B");
			}else if ("500203".equals(CAI.getStock_code())) {
				cai.setProd_state("A");
			}
			//项目代码
			cai.setItem_code(CAI.getItem_code());
			cai.setItem_name(CAI.getItem_name());
			//父级项目代码
			cai.setParent_item_code(CAI.getParent_item_code());
			cai.setParent_item_name(CAI.getParent_item_name());
			//成本组织
			cai.setOrg_code(CAI.getOrg_code());
			cai.setOrg_name(CAI.getOrg_name());
			//成本期间 
			cai.setPrd_num(bfpd.getPrd_num());
			//入库时间
			cai.setIn_time(CAI.getIn_time());
			//是否头尾卷
			cai.setIs_tw(CAI.getIs_tw());
			//理重和实重
			cai.setFact_wgt(CAI.getFact_wgt());
			cai.setTheory_wgt(CAI.getTheory_wgt());
			//创建人和创建时间
			cai.setValid_flg("1");//默认有效
			cai.setAudit_flg("0");//默认未审核
			cai.setCreate_man(userName);
			cai.setCreate_time(now);			
			this.getMapper(CmCostAcmInnMapper.class).insert(cai);			
		}		
		rm.setState("200");
		rm.setMsgInfo("入库信息归集成功");
		return rm;
	}
	
	/**
	 * 入库信息归集的删除方法
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCmCostAcmInn(CommonPage<CmCostAcmInn> cp) throws Exception{
		ResultModel rm = new ResultModel();
		CmCostAcmInn cai = cp.getObject();		
		if (cai.getPrd_num()==null || "".equals(cai.getPrd_num())) {
			throw new Exception("请传入成本期间");
		}		
		//判断成本期间内是否已经进行了归集		
		CmCostAcmInn CAI = new CmCostAcmInn();
		CAI.setPrd_num(cai.getPrd_num());	//成本期间
		CAI.setAudit_flg("1");		//已经审核
		int count = this.getMapper(CmCostAcmInnMapper.class).count(CAI);
		if (count>0) {
			throw new Exception("当前成本期间【"+cai.getPrd_num()+"】已经存在已经审核的入库归集信息,无法删除");
		}
		//删除成本期间内的信息
		this.getMapper(CmCostAcmInnMapper.class).doDeleteCmCostAcmInn(cai);		
		
		rm.setState("200");
		rm.setMsgInfo("入库归集信息删除成功");
		return rm;		
	}
	
	/**
	 * 入库归集信息：审核及反审
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeCmCostAcmInnAuditFlg(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();
		
		//通过成本期间进行【审核】和【反审】
		CmCostAcmInn CAI = new CmCostAcmInn();
		CAI.setPrd_num(cap.getPrd_num());
		CAI.setAudit_flg("1".equals(opr)?"1":"0");//
		int count = this.getMapper(CmCostAcmInnMapper.class).count(CAI);
		if (count > 0) {
			throw new Exception("成本期间【"+cap.getPrd_num()+"】中存在"+("1".equals(opr)?"已审核":"未审核")+"的数据");
		}
		
		CmCostAcmInn cai = new CmCostAcmInn();
		cai.setPrd_num(cap.getPrd_num());
		cai.setAudit_flg(opr);
		if ("1".equals(opr)) {//审核操作，传递审核人和审核时间			
			cai.setAudit_man(userName);
			cai.setAudit_time(now);
		}
		this.getMapper(CmCostAcmInnMapper.class).doChangeCmCostAcmInnAuditFlg(cai);	
		rm.setMsgInfo("成本期间【"+cap.getPrd_num()+"】"+("0".equals(cp.getMemo1())?"反审":"审核") + "操作成功");
		rm.setState("200");		
		return rm;
	}
	
}
