/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：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.CmCostAcmOutMapper;
import market.Cm.service.CmCostAcmOutService;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.BaseOrgCmp;
import market.Cm.vo.CmCostAcmOut;
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="CmCostAcmOutService")
public class CmCostAcmOutServiceImpl extends BaseServiceImpl<CmCostAcmOut,Object> implements CmCostAcmOutService {

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