package market.Slm.DeliveryManagement.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.DeliveryManagement.mapper.SlmDeliveryPlanHeatMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.service.SlmDeliveryPlanHeatService;
import market.Slm.DeliveryManagement.vo.SlmDeliveryPlanHeat;
import market.Slm.DeliveryManagement.vo.SlmDeliveryPlanLine;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;

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="SlmDeliveryPlanHeatService")
public class SlmDeliveryPlanHeatServiceImpl extends BaseServiceImpl<SlmDeliveryPlanHeat,Object> implements SlmDeliveryPlanHeatService {
	
	/**
	 * 列表查询
	 * 1审核页面  2关闭页面 3给提单的查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmDeliveryPlanHeat> sum){
		ResultModel rm=new ResultModel();
		SlmDeliveryPlanHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String sType=sum.getMemo6()==null?"":sum.getMemo6(); // 为1则是火运
		PageModel<SlmDeliveryPlanHeat> pm=new PageModel<SlmDeliveryPlanHeat>(pageIndex, pageSize);
		try{
			String sWhere="";
			if("1".equals(sum.getMemo1()))		//审核页面
				sWhere=" plan_status in ('2','3')";
			if("2".equals(sum.getMemo1()))		//关闭页面
				sWhere=" plan_status in ('3','4','5')";
			if("3".equals(sum.getMemo1()))		//提单页面
				sWhere=" plan_status in ('3','4')";
			if("1".equals(sType)){
				sWhere += "and PLAN_NO in (SELECT t.plan_no from SLM_DELIVERY_PLAN_HEAT t join SLM_DELIVERY_PLAN_LINE t2 on t.plan_no=t2.plan_no)";
			}
			List<SlmDeliveryPlanHeat> list=this.getMapper(SlmDeliveryPlanHeatMapper.class).findWithCondition(heat,sWhere, " valid_flag desc,create_time desc", (pageIndex-1)*pageSize,pageSize);
			int count=this.getMapper(SlmDeliveryPlanHeatMapper.class).countWithCondition(heat, sWhere);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 审核页面查询
	 * */
	public ResultModel doQueryApproverWeb(CommonPage<SlmDeliveryPlanHeat> sum){
		ResultModel rm=new ResultModel();
		SlmDeliveryPlanHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmDeliveryPlanHeat> pm=new PageModel<SlmDeliveryPlanHeat>(pageIndex, pageSize);
		String contract_no="".equals(sum.getMemo1())?null:sum.getMemo1();
		String order_no="".equals(sum.getMemo2())?null:sum.getMemo2();
		try{
			List<SlmDeliveryPlanHeat> list=this.getMapper(SlmDeliveryPlanHeatMapper.class).doQueryApprover(heat,contract_no, order_no, (pageIndex-1)*pageSize,pageIndex*pageSize);
			int count=this.getMapper(SlmDeliveryPlanHeatMapper.class).doQueryApproverCount(heat,contract_no, order_no);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 发运计划新增
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		SlmDeliveryPlanHeat heat=sum.getObject();
		try{
			String date=new SimpleDateFormat("yyyyMMdd").format(new Date());
			int count=this.getMapper(SlmDeliveryPlanHeatMapper.class).countWithCondition(null," PLAN_NO like concat('"+date+"','%')")+1;
			heat.setPlan_no(date+String.format("%06d",count));
			heat.setCreate_man_no(userId);
			heat.setCreate_man_name(userName);
			heat.setCreate_time(new Date());
			heat.setPlan_status("1");		//编辑
			heat.setValid_flag("1");
			this.getMapper(SlmDeliveryPlanHeatMapper.class).insert(heat);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("新增失败"+ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 发运单编辑
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		SlmDeliveryPlanHeat heat=sum.getObject();
		try{
			//判断何种状态可以进行编辑
			SlmDeliveryPlanHeat newheat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
			if(!"1".equals(newheat.getPlan_status())){		//只有编辑状态才可修改
				rm.setMsgInfo("当前状态无法编辑");
				rm.setState("500");
				return rm;
			}
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmDeliveryPlanHeatMapper.class).update(heat);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("编辑失败"+ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 发运单启用停用
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSwitchWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		SlmDeliveryPlanHeat heat=sum.getObject();
		String state="1".equals(heat.getValid_flag())?"启用":"停用";
		try{
			//判断何种状态可以进行启用停用
			SlmDeliveryPlanHeat newheat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
			if(!"1".equals(newheat.getPlan_status())){		//编辑状态才可 启用停用
				rm.setMsgInfo("当前状态无法"+state);
				rm.setState("500");
				return rm;
			}
			if("0".equals(heat.getValid_flag())){		//停用
				//若发运头下存在有效提单，则需先将有效提单作废，方可将发运头停用
				SlmLadingBillHeat billHeat=new SlmLadingBillHeat();
				billHeat.setPlan_no(heat.getPlan_no());
				billHeat.setValid_flag("1");
				int count=this.getMapper(SlmLadingBillHeatMapper.class).count(billHeat);
				if(count>0){
					rm.setState("500");
					rm.setMsgInfo("该发运计划下存在有效提单，如需作废该计划请先将该计划下的提单作废");
					return rm;
				}
				heat.setDelete_man_no(userId);
				heat.setDelete_man_name(userName);
				heat.setDelete_time(new Date());
				//连带行一起停用
				SlmDeliveryPlanLine line=new SlmDeliveryPlanLine();
				line.setPlan_no(heat.getPlan_no());
				List<SlmDeliveryPlanLine> lineList=this.getBean(SlmDeliveryPlanLineServiceImpl.class).doQuery(line);
				for(SlmDeliveryPlanLine lines:lineList){
					lines.setValid_flag("0");
					this.getBean(SlmDeliveryPlanLineServiceImpl.class).doUpdate(lines);
				}
			}else{			//启用
				heat.setUpdate_man_no(userId);
				heat.setUpdate_man_name(userName);
				heat.setUpdate_time(new Date());
			}
			this.getMapper(SlmDeliveryPlanHeatMapper.class).update(heat);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(state+"失败"+ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 批量提交
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSubmitWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmDeliveryPlanHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmDeliveryPlanHeat heat:heatList){
				heat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
				//新增判断，有计划行才可提交
				SlmDeliveryPlanLine line=new SlmDeliveryPlanLine();
				line.setPlan_no(heat.getPlan_no());
				line.setValid_flag("1");
				List<SlmDeliveryPlanLine> lineList=this.getBean(SlmDeliveryPlanLineServiceImpl.class).doQuery(line);
				if("1".equals(heat.getValid_flag())&&"1".equals(heat.getPlan_status())&&lineList.size()>0){		//有效的 编辑状态才能提交
					heat.setPlan_status("2");		//待审核
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmDeliveryPlanHeatMapper.class).update(heat);
				}else{
					msg+=heat.getPlan_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("发运计划["+msg.substring(0, msg.length()-1)+"]无法提交，原因：非编辑状态或无有效计划行");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 批量撤回
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRollbackWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmDeliveryPlanHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmDeliveryPlanHeat heat:heatList){
				heat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
				if("1".equals(heat.getValid_flag())&&"2".equals(heat.getPlan_status())){		//有效的 待审核状态才能撤回
					heat.setPlan_status("1");		//编辑
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmDeliveryPlanHeatMapper.class).update(heat);
				}else{
					msg+=heat.getPlan_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("发运计划["+msg.substring(0, msg.length()-1)+"]无法撤回，原因：非待审核状态");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 批量审核
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doPassWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmDeliveryPlanHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmDeliveryPlanHeat heat:heatList){
				heat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
				if("1".equals(heat.getValid_flag())&&"2".equals(heat.getPlan_status())){		//有效的 待审核状态才能审核
					heat.setPlan_status("3");		//待执行
					heat.setCheck_man_no(userId);
					heat.setCheck_man_name(userName);
					heat.setCheck_time(new Date());
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmDeliveryPlanHeatMapper.class).update(heat);
				}else{
					msg+=heat.getPlan_no()+"，";
				}
			}
			if(!"".equals(msg)){
				rm.setMsgInfo("发运计划["+msg.substring(0, msg.length()-1)+"]无法审核通过，原因：非待审核状态");
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 批量反审
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doNotPassWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmDeliveryPlanHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmDeliveryPlanHeat heat:heatList){
				heat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
				if("1".equals(heat.getValid_flag())&&("3".equals(heat.getPlan_status())||"6".equals(heat.getPlan_status()))){		//有效的 执行状态才能反审
					heat.setPlan_status("2");		//待审核
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmDeliveryPlanHeatMapper.class).doNotPass(heat);
				}else{
					msg+=heat.getPlan_no()+"，";
				}
			}
			if(!"".equals(msg)){
				rm.setMsgInfo("发运计划["+msg.substring(0, msg.length()-1)+"]无法反审，原因：非执行或审核不通过状态");
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 批量关闭
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCloseWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmDeliveryPlanHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmDeliveryPlanHeat heat:heatList){
				heat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
				if("1".equals(heat.getValid_flag())&&("3".equals(heat.getPlan_status())||"4".equals(heat.getPlan_status()))){		//有效的 执行状态才能关闭
					//查询计划下的提单状态
//					SlmLadingBillHeat bill=new SlmLadingBillHeat();
//					bill.setPlan_no(heat.getPlan_no());
//					bill.setValid_flag("1");
//					int count=this.getMapper(SlmLadingBillHeatMapper.class).countWithCondition(bill, " valid_status not in('8','9','10','11')");
//					if(count>0){
//						rm.setState("500");
//						rm.setMsgInfo("该计划下存在有效的未发运的提单，请先将其关闭或废除");
//						return rm;
//					}
					heat.setP_plan_status(heat.getPlan_status());
					heat.setPlan_status("5");		//关闭
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmDeliveryPlanHeatMapper.class).update(heat);
				}else{
					msg+=heat.getPlan_no()+"，";
				}
			}
			if(!"".equals(msg)){
				rm.setMsgInfo("发运计划["+msg.substring(0, msg.length()-1)+"]无法关闭，原因：非执行状态");
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 批量取消关闭
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelCloseWeb(CommonPage<SlmDeliveryPlanHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmDeliveryPlanHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmDeliveryPlanHeat heat:heatList){
				heat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
				if("1".equals(heat.getValid_flag())&&"5".equals(heat.getPlan_status())){		//有效的 关闭状态才能取消关闭
					heat.setPlan_status(heat.getP_plan_status());		//执行或待执行 
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmDeliveryPlanHeatMapper.class).update(heat);
				}else{
					msg+=heat.getPlan_no()+"，";
				}
			}
			if(!"".equals(msg)){
				rm.setMsgInfo("发运计划["+msg.substring(0, msg.length()-1)+"]无法开启，原因：非关闭状态");
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 详情
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<SlmDeliveryPlanHeat> sum){
		ResultModel rm=new ResultModel();
		SlmDeliveryPlanHeat heat=sum.getObject();
		try{
			heat=this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(heat.getPlan_no());
			rm.setData(heat);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	public SlmDeliveryPlanHeat doQueryOne(String planNo) {
		return this.getMapper(SlmDeliveryPlanHeatMapper.class).findById(planNo);
	}
}
