/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-10-30
 * 描述            ：原材料贸易卷收发存报表的期末数据
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.CmReportMatIosMapper;
import market.Cm.service.CmReportMatIosService;
import market.Cm.vo.CmReportMatIos;
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.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="CmReportMatIosService")
public class CmReportMatIosServiceImpl extends BaseServiceImpl<CmReportMatIos,Object> implements CmReportMatIosService {

	/**
	 * 查询收发存明细
	 * @param cp 【mat_flg:0原材料  1贸易卷】
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQauryCmReportFinalResult(CommonPage<CmReportMatIos> cp) throws Exception {
		ResultModel rm = new ResultModel();
		CmReportMatIos crm = cp.getObject();
		String condition = "";
		if (crm.getPrd_num()!=null && !"".equals(crm.getPrd_num())) {
			condition += " and prd_num = '"+crm.getPrd_num()+"'";
		}
		if (crm.getMat_flg()!=null && !"".equals(crm.getMat_flg())) {
			condition += " and mat_flg = '"+crm.getMat_flg()+"'";
		}
		String orderBy = "mat_flg,is_yg,mat_type,parent_object_code";//排序
		List<CmReportMatIos> bciList = this.getMapper(CmReportMatIosMapper.class).findWithCondition(null, condition, orderBy, 0, 0);
		rm.setData(bciList);
		rm.setState("200");
		rm.setMsgInfo("查询收发存明细成功");
		return rm;
	}
	
	/**
	 * 撤销核算
	 * @param cp prd_num[成本期间]  mat_flg[0原材料 1贸易卷]
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCmReportMatIos(CommonPage<CmReportMatIos> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmReportMatIos crm = cp.getObject();
		if (crm.getPrd_num()==null || "".equals(crm.getPrd_num())) {
			throw new Exception("请传入成本期间");
		}
		if (!"0".equals(crm.getMat_flg()) && !"1".equals(crm.getMat_flg())) {
			throw new Exception("界面分类传入错误");
		}		
		//判断当前成本期间是否已经进行核算
		String condition = " and prd_num = '"+crm.getPrd_num()+"' and mat_flg = '"+crm.getMat_flg()+"'";
		int count = this.getMapper(CmReportMatIosMapper.class).countWithCondition(null, condition);
		if (count<=0) {
			throw new Exception("成本期间【"+crm.getPrd_num()+"】还未进行核算");
		}
		//判断当前成本期间是否已经审核
		condition = " and prd_num = '"+crm.getPrd_num()+"' and mat_flg = '"+crm.getMat_flg()+"' and is_audit = '1'";
		count = this.getMapper(CmReportMatIosMapper.class).countWithCondition(null, condition);
		if (count > 0) {
			throw new Exception("成本期间【"+crm.getPrd_num()+"】已经进行审核，请先撤销审核");
		}
		//根据成本期间进行撤销核算
		this.getMapper(CmReportMatIosMapper.class).doDeleteCmReportMatIos(crm);		
		rm.setState("200");
		rm.setMsgInfo("撤销核算成功");
		return rm;
	}
	
	/**
	 * 调整功能
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doUpdateCmReportMatIos(CommonPage<CmReportMatIos> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmReportMatIos crm = cp.getObject();
		if (crm.getObject_id()==null) {
			//执行新增
			this.getMapper(CmReportMatIosMapper.class).insert(crm);
		}else {		
			//判断数据是否存在
			CmReportMatIos CRM = this.getMapper(CmReportMatIosMapper.class).findById(crm.getObject_id());
			if (CRM==null) {
				throw new Exception("未找到当前数据");
			}
			if ("1".equals(CRM.getIs_audit())) {
				throw new Exception("当前数据已经审核，如需调整，请先撤销核算");
			}
			//根据成本期间进行修改			
			this.getMapper(CmReportMatIosMapper.class).update(crm);		
		}
		rm.setState("200");
		rm.setMsgInfo("调整收发存明细成功");
		return rm;
	}
	
	/**
	 * 审核及反审
	 * @param cp memo1[0取消审核  1审核] prd_num[成本期间]
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeCmReportMatIosValidflg(CommonPage<CmReportMatIos> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm  = new ResultModel();
		CmReportMatIos crm = cp.getObject();
		String opr = cp.getMemo1();//0:反审  1审核
		if ("1".equals(opr)) {
			//审核操作
			//1.判断数据是否已经审核
			String condition = " and is_audit = '1' and prd_num = '"+crm.getPrd_num()+"' and mat_flg = '"+crm.getMat_flg()+"'";
			int count = this.getMapper(CmReportMatIosMapper.class).countWithCondition(null, condition);
			if (count > 0) {
				throw new Exception("成本期间【"+crm.getPrd_num()+"】已经审核，无需继续审核");
			}
			//2.执行审核
			crm.setAudit_man(userName);
			crm.setAudit_time(new Date());
			crm.setIs_audit("1");
			this.getMapper(CmReportMatIosMapper.class).doChangeCmReportMatIosValidflg(crm);
		}else if ("0".equals(opr)) {
			//反审操作
			//1.判断数据是否还未审核
			String condition = " and is_audit = '0' and prd_num = '"+crm.getPrd_num()+"' and mat_flg = '"+crm.getMat_flg()+"'";
			int count = this.getMapper(CmReportMatIosMapper.class).countWithCondition(null, condition);
			if (count > 0) {
				throw new Exception("成本期间【"+crm.getPrd_num()+"】还未审核，无法取消审核");
			}
			//2.执行反审
			crm.setIs_audit("0");
			crm.setAudit_man(null);
			crm.setAudit_time(null);
			this.getMapper(CmReportMatIosMapper.class).doChangeCmReportMatIosValidflg(crm);
		}
		rm.setState("200");
		rm.setMsgInfo(("0".equals(opr)?"取消审核":"审核")+"操作成功");
		return rm;
	}
	
	/**
	 * 核算
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertCmReportMatIos(CommonPage<CmReportMatIos> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmReportMatIos crm = cp.getObject();
		if (crm.getPrd_num()==null || "".equals(crm.getPrd_num())) {
			throw new Exception("请传入成本期间");
		}
		//判断是否已经核算
		String condition = " and prd_num = '"+crm.getPrd_num()+"' and mat_flg = '"+crm.getMat_flg()+"'";
		int count = this.getMapper(CmReportMatIosMapper.class).countWithCondition(null, condition);
		if (count > 0) {
			throw new Exception("成本期间【"+crm.getPrd_num()+"】已经核算");
		}
		if ("0".equals(crm.getMat_flg())) {
			//原材料的核算
			doInsertMaterialForReport(crm);			
		}else if ("1".equals(crm.getMat_flg())) {
			//贸易卷的核算
			doInsertTradeForReport(crm);
		}
		rm.setState("200");
		rm.setMsgInfo("核算成功");
		return rm;
	}
	
	/**
	 * 原材料的核算
	 * @param prd_num
	 * @throws Exception
	 */
	public void doInsertMaterialForReport(CmReportMatIos crm) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		try {
			//成本期间+界面分类+原料卷类别+牌号(确定唯一的一条数据)		
			List<CmReportMatIos> crmList = new ArrayList<CmReportMatIos>();
			//1.获取原材料的本月期初
			SimpleDateFormat sd = new SimpleDateFormat("yyyyMM");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(sd.parse(crm.getPrd_num()));
			calendar.add(Calendar.MONTH, -1);
			String lastPrd_num = sd.format(calendar.getTime());//上月的成本期间
			String condition = " and prd_num = '"+lastPrd_num+"' and mat_flg = '0'";
			List<CmReportMatIos> lastList = this.getMapper(CmReportMatIosMapper.class).findWithCondition(null, condition, null, 0, 0);
			if (lastList!=null && lastList.size()>0) {
				for (CmReportMatIos lastCrm : lastList) {
					CmReportMatIos CRM = new CmReportMatIos();
					CRM.setPrd_num(crm.getPrd_num());
					CRM.setMat_flg(crm.getMat_flg());
					CRM.setMat_type(lastCrm.getMat_type());
					CRM.setParent_object_code(lastCrm.getParent_object_code());
					CRM.setParent_object_name(lastCrm.getParent_object_name());
					CRM.setStr_wgt(lastCrm.getEnd_wgt()==null?0:lastCrm.getEnd_wgt());
					CRM.setStr_amount(lastCrm.getEnd_amount()==null?0:lastCrm.getEnd_amount());
					crmList.add(CRM);
				}
			}		
			//2.获取原材料的本月增加
			List<CmReportMatIos> inList = this.getMapper(CmReportMatIosMapper.class).doQauryAddMaterialForReport(crm);
			if (inList!=null && inList.size()>0) {
				for (CmReportMatIos inCrm : inList) {
					boolean ismatch = false;
					for (CmReportMatIos CRM : crmList) {
						//原料卷类型相同，牌号类别相同
						if (CRM.getMat_type().equals(inCrm.getMat_type()) 
								&& CRM.getParent_object_code().equals(inCrm.getParent_object_code())) {
							CRM.setIn_wgt(inCrm.getIn_wgt()==null?0:inCrm.getIn_wgt());
							CRM.setIn_amount(inCrm.getIn_amount()==null?0:inCrm.getIn_amount());
							ismatch = true;
							continue;
						}
					}
					if (!ismatch) {
						//如果没有匹配上，则新增本月增加数据
						CmReportMatIos CRM = new CmReportMatIos();
						CRM.setPrd_num(crm.getPrd_num());
						CRM.setMat_flg(crm.getMat_flg());
						CRM.setMat_type(inCrm.getMat_type());
						CRM.setParent_object_code(inCrm.getParent_object_code());
						CRM.setParent_object_name(inCrm.getParent_object_name());
						CRM.setIn_wgt(inCrm.getIn_wgt()==null?0:inCrm.getIn_wgt());
						CRM.setIn_amount(inCrm.getIn_amount()==null?0:inCrm.getIn_amount());
						crmList.add(CRM);
					}
				}
			}		
			//3.获取原材料的本月减少
			List<CmReportMatIos> outList = this.getMapper(CmReportMatIosMapper.class).doQauryReduceMaterialForReport(crm);
			if (outList!=null && outList.size()>0) {
				for (CmReportMatIos outCrm : outList) {
					boolean ismatch = false;
					for (CmReportMatIos CRM : crmList) {
						//原料卷类型相同，牌号类别相同
						if (CRM.getMat_type().equals(outCrm.getMat_type()) 
								&& CRM.getParent_object_code().equals(outCrm.getParent_object_code())) {
							CRM.setOut_wgt(outCrm.getOut_wgt()==null?0:outCrm.getOut_wgt());
							CRM.setOut_amount(outCrm.getOut_amount()==null?0:outCrm.getOut_amount());
							ismatch = true;
							continue;
						}
					}
					if (!ismatch) {
						//如果没有匹配上，则新增本月增加数据
						CmReportMatIos CRM = new CmReportMatIos();
						CRM.setPrd_num(crm.getPrd_num());
						CRM.setMat_flg(crm.getMat_flg());
						CRM.setMat_type(outCrm.getMat_type());
						CRM.setParent_object_code(outCrm.getParent_object_code());
						CRM.setParent_object_name(outCrm.getParent_object_name());
						CRM.setOut_wgt(outCrm.getOut_wgt()==null?0:outCrm.getOut_wgt());
						CRM.setOut_amount(outCrm.getOut_amount()==null?0:outCrm.getOut_amount());
						crmList.add(CRM);
					}
				}
			}
			//4.计算期末数据 
			Long ser_num = Long.parseLong(crm.getPrd_num()+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+"0000");
			for (CmReportMatIos CRM : crmList) {
				if ("1".equals(CRM.getMat_type())
						||"2".equals(CRM.getMat_type())
						||"5".equals(CRM.getMat_type())) {
					Double str_wgt = CRM.getStr_wgt()==null?0:CRM.getStr_wgt();
					Double in_wgt = CRM.getIn_wgt()==null?0:CRM.getIn_wgt();
					Double out_wgt = CRM.getOut_wgt()==null?0:CRM.getOut_wgt();
					CRM.setEnd_wgt(str_wgt+in_wgt-out_wgt);
					Double str_amount = CRM.getStr_amount()==null?0:CRM.getStr_amount();
					Double in_amount = CRM.getIn_amount()==null?0:CRM.getIn_amount();
					Double out_amount = CRM.getOut_amount()==null?0:CRM.getOut_amount();
					CRM.setEnd_amount(str_amount+in_amount-out_amount);
					CRM.setPrd_num(crm.getPrd_num());
					CRM.setCreate_man(userName);
					CRM.setCreate_time(now);
					CRM.setValid_flg("1");
					CRM.setIs_audit("0");
					//设置主键ID
					ser_num++;
					CRM.setObject_id("QM"+ser_num);
					this.getMapper(CmReportMatIosMapper.class).insert(CRM);
				}
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}	
	}
	
	/**
	 * 贸易卷的核算
	 * @param prd_num
	 * @throws Exception
	 */
	public void doInsertTradeForReport(CmReportMatIos crm) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		try {
			//成本期间+界面分类+原料卷类别+牌号(确定唯一的一条数据)		
			List<CmReportMatIos> crmList = new ArrayList<CmReportMatIos>();
			//1.获取贸易卷的本月期初
			SimpleDateFormat sd = new SimpleDateFormat("yyyyMM");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(sd.parse(crm.getPrd_num()));
			calendar.add(Calendar.MONTH, -1);
			String lastPrd_num = sd.format(calendar.getTime());//上月的成本期间
			String condition = " and prd_num = '"+lastPrd_num+"' and mat_flg = '1'";
			List<CmReportMatIos> lastList = this.getMapper(CmReportMatIosMapper.class).findWithCondition(null, condition, null, 0, 0);
			if (lastList!=null && lastList.size()>0) {
				for (CmReportMatIos lastCrm : lastList) {
					CmReportMatIos CRM = new CmReportMatIos();
					CRM.setPrd_num(crm.getPrd_num());
					CRM.setMat_flg(crm.getMat_flg());
					CRM.setMat_type(lastCrm.getMat_type());
					CRM.setParent_object_code(lastCrm.getParent_object_code());
					CRM.setParent_object_name(lastCrm.getParent_object_name());
					CRM.setStr_wgt(lastCrm.getEnd_wgt()==null?0:lastCrm.getEnd_wgt());
					CRM.setStr_amount(lastCrm.getEnd_amount()==null?0:lastCrm.getEnd_amount());
					crmList.add(CRM);
				}
			}		
			//2.获取贸易卷的本月增加
			List<CmReportMatIos> inList = this.getMapper(CmReportMatIosMapper.class).doQauryAddTradeForReport(crm);
			if (inList!=null && inList.size()>0) {
				for (CmReportMatIos inCrm : inList) {
					if (inCrm.getParent_object_code()==null) {
						continue;
					}
					boolean ismatch = false;
					for (CmReportMatIos CRM : crmList) {						
						//原料卷类型相同，牌号类别相同
						if (CRM.getMat_type().equals(inCrm.getMat_type()) 
								&& CRM.getParent_object_code().equals(inCrm.getParent_object_code())) {
							CRM.setIn_wgt(inCrm.getIn_wgt()==null?0:inCrm.getIn_wgt());
							CRM.setIn_amount(inCrm.getIn_amount()==null?0:inCrm.getIn_amount());
							ismatch = true;
							continue;
						}
					}
					if (!ismatch) {
						//如果没有匹配上，则新增本月增加数据
						CmReportMatIos CRM = new CmReportMatIos();
						CRM.setPrd_num(crm.getPrd_num());
						CRM.setMat_flg(crm.getMat_flg());
						CRM.setMat_type(inCrm.getMat_type());
						CRM.setParent_object_code(inCrm.getParent_object_code());
						CRM.setParent_object_name(inCrm.getParent_object_name());
						CRM.setIn_wgt(inCrm.getIn_wgt()==null?0:inCrm.getIn_wgt());
						CRM.setIn_amount(inCrm.getIn_amount()==null?0:inCrm.getIn_amount());
						crmList.add(CRM);
					}
				}
			}		
			//3.获取贸易卷的本月减少
			List<CmReportMatIos> outList = this.getMapper(CmReportMatIosMapper.class).doQauryReduceTradeForReport(crm);
			if (outList!=null && outList.size()>0) {
				for (CmReportMatIos outCrm : outList) {
					if (outCrm.getParent_object_code()==null) {
						continue;
					}
					boolean ismatch = false;
					for (CmReportMatIos CRM : crmList) {
						//原料卷类型相同，牌号类别相同
						if (CRM.getMat_type().equals(outCrm.getMat_type()) 
								&& CRM.getParent_object_code().equals(outCrm.getParent_object_code())) {
							CRM.setOut_wgt(outCrm.getOut_wgt()==null?0:outCrm.getOut_wgt());
							CRM.setOut_amount(outCrm.getOut_amount()==null?0:outCrm.getOut_amount());
							ismatch = true;
							continue;
						}
					}
					if (!ismatch) {
						//如果没有匹配上，则新增本月增加数据
						CmReportMatIos CRM = new CmReportMatIos();
						CRM.setPrd_num(crm.getPrd_num());
						CRM.setMat_flg(crm.getMat_flg());
						CRM.setMat_type(outCrm.getMat_type());
						CRM.setParent_object_code(outCrm.getParent_object_code());
						CRM.setParent_object_name(outCrm.getParent_object_name());
						CRM.setOut_wgt(outCrm.getOut_wgt()==null?0:outCrm.getOut_wgt());
						CRM.setOut_amount(outCrm.getOut_amount()==null?0:outCrm.getOut_amount());
						crmList.add(CRM);
					}
				}
			}
			//4.计算期末数据 
			Long ser_num = Long.parseLong(crm.getPrd_num()+Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+"0000");
			for (CmReportMatIos CRM : crmList) {
				if ("1".equals(CRM.getMat_type())
						||"2".equals(CRM.getMat_type())
						||"5".equals(CRM.getMat_type())) {				
					Double str_wgt = CRM.getStr_wgt()==null?0:CRM.getStr_wgt();
					Double in_wgt = CRM.getIn_wgt()==null?0:CRM.getIn_wgt();
					Double out_wgt = CRM.getOut_wgt()==null?0:CRM.getOut_wgt();
					CRM.setEnd_wgt(str_wgt+in_wgt-out_wgt);
					Double str_amount = CRM.getStr_amount()==null?0:CRM.getStr_amount();
					Double in_amount = CRM.getIn_amount()==null?0:CRM.getIn_amount();
					Double out_amount = CRM.getOut_amount()==null?0:CRM.getOut_amount();
					CRM.setEnd_amount(str_amount+in_amount-out_amount);
					CRM.setPrd_num(crm.getPrd_num());
					CRM.setCreate_man(userName);
					CRM.setCreate_time(now);
					CRM.setValid_flg("1");
					CRM.setIs_audit("0");
					//设置主键ID
					ser_num++;
					CRM.setObject_id("QT"+ser_num);
					this.getMapper(CmReportMatIosMapper.class).insert(CRM);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
}
