/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-01-09
 * 描述            ：加工计划信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Slm.OrderManagement.impl;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import jxl.CellView;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import market.Com.pb.DoubleUtil;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.mapper.SlmProcessPlanMapper;
import market.Slm.OrderManagement.service.SlmProcessPlanService;
import market.Slm.OrderManagement.vo.SlmOrderInfo;
import market.Slm.OrderManagement.vo.SlmProcessPlan;

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;
//import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@RemoteService(path="SlmProcessPlanService")
public class SlmProcessPlanServiceImpl extends BaseServiceImpl<SlmProcessPlan,Object> implements SlmProcessPlanService {

	/**
	 * 查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmProcessPlan> sum){
		ResultModel rm=new ResultModel();
		SlmProcessPlan plan=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmProcessPlan> pm=new PageModel<SlmProcessPlan>(pageIndex, pageSize);
		try{
			List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).findWithCondition(plan, " valid_flag='1'", " cut_order_no", pageSize*(pageIndex-1), pageSize);
			int count=this.getMapper(SlmProcessPlanMapper.class).countWithCondition(plan, " valid_flag='1'");
			pm.setTotal(count);
			pm.setRows(list);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 查询所有的加工计划 
	 * */
	public ResultModel doQueryCensusWeb(CommonPage<SlmProcessPlan> sum){
		ResultModel rm=new ResultModel();
		SlmProcessPlan plan=sum.getObject();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		try{
			if(startTime!=null&&!"".equals(startTime)){		//页面上为开票时间
				startTime+=" 00:00:00";
			}
			if(endTime!=null&&!"".equals(endTime)){
				endTime+=" 23:59:59";
			}
			List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).doQueryCensus(plan,startTime,endTime);
			rm.setState("200");
			rm.setData(list);
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 新增
	 * */
	public ResultModel doAddWeb(CommonPage<SlmProcessPlan> sum){
		ResultModel rm=new ResultModel();
		SlmProcessPlan plan=sum.getObject();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).findWithCondition(null, " plan_no like concat('"+plan.getContract_line_no()+"','%')"," plan_no desc",0,0);
			int count=1;
			if(list.size()>0){
				String planNo=list.get(0).getPlan_no();
				planNo=planNo.substring(planNo.length()-3);
				count=Integer.parseInt(planNo);
			}	
			String plan_no=plan.getContract_line_no()+String.format("%03d", (count+1));
			plan.setPlan_no(plan_no);
			plan.setCreate_man_no(userId);
			plan.setCreate_man_name(userName);
			plan.setCreate_time(new Date());
			plan.setValid_flag("1");
			plan.setPlan_flag("0");  		//待评审

			// 验证加工序号不能重复
			SlmProcessPlan cesu = new SlmProcessPlan();
			cesu.setContract_line_no(plan.getContract_line_no());
			cesu.setOrder_seq(plan.getOrder_seq());
			cesu.setCut_order_no(plan.getCut_order_no());
			cesu.setValid_flag("1");
			int app =	this.getMapper(SlmProcessPlanMapper.class).find(cesu, 0, 0).size();

			if(app>0)
			{
				rm.setState("500");
				rm.setMsgInfo("新增失败,分切序号已存在");
				return rm;
			}
			this.getMapper(SlmProcessPlanMapper.class).insert(plan);
			//反写采购合同号
			rm=doAddPurchase(plan);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("新增失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 反写采购合同号 加工计划→订单
	 * */
	public ResultModel doAddPurchase(SlmProcessPlan plan){
		ResultModel rm=new ResultModel();
		try{
			//反写订单的采购合同号
			if(plan.getPurchase_contract_no()!=null&&!"".equals(plan.getPurchase_contract_no())){
				SlmOrderInfo order=new SlmOrderInfo();
				order.setContract_no(plan.getContract_no());
				order.setContract_line_seq(plan.getContract_line_seq());
				order.setOrder_seq(plan.getOrder_seq());
				List<SlmOrderInfo> orderList=this.getMapper(SlmOrderInfoMapper.class).find(order, 0, 0);
				if(orderList.size()>0){
					orderList.get(0).setPurchase_contract_no(plan.getPurchase_contract_no());
					this.getMapper(SlmOrderInfoMapper.class).update(orderList.get(0));
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 自动新增
	 * 新增参数放memo1里
	 * @throws Exception 
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAutoAddWeb(CommonPage<SlmProcessPlan> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmProcessPlan plan=sum.getObject();
		String info=sum.getMemo1();		//分切规则
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			SlmProcessPlan paramPlan=new SlmProcessPlan();
			paramPlan.setContract_no(plan.getContract_no());
			paramPlan.setContract_line_seq(plan.getContract_line_seq());
			paramPlan.setOrder_seq(plan.getOrder_seq());
			paramPlan.setValid_flag("1");
			List<SlmProcessPlan> order_list=this.getMapper(SlmProcessPlanMapper.class).find(paramPlan,0,0);	
			long order_num=order_list.size();		//分切序号
			if(order_num>0){
				if(!order_list.get(0).getCut_type().equals(plan.getCut_type())){
					rm.setState("500");
					rm.setMsgInfo("加工计划的分切方式需保持一致");
					return rm;
				}
			}
			//采购合同号需取合同号里的一部分，需修改请使用修改功能
//			if(plan.getPurchase_contract_no()!=null&&!"".equals(plan.getPurchase_contract_no())){
//				if(plan.getContract_no()!=null&&!plan.getContract_no().contains(plan.getPurchase_contract_no())){
//					rm.setState("500");
//					rm.setMsgInfo("采购合同号需取合同号里的一部分，如需修改请使用修改功能");
//					return rm;
//				}
//			}
			List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).findWithCondition(null, " plan_no like concat('"+plan.getContract_line_no()+"','%')"," plan_no desc",0,0);
			long count=0; 			//流水号
			if(list.size()>0){
				String planNo=list.get(0).getPlan_no();
				planNo=planNo.substring(planNo.length()-3);
				count=Integer.parseInt(planNo);		//流水号取最大值
			}
			//分切规则验证
			if("2".equals(plan.getCut_type())){			//分条
				if(info==null){		
					rm.setState("500");
					rm.setMsgInfo("请填写分切规则");
					return rm;
				}
				String[] paramList=info.contains("+")?info.split("[+]"):new String[]{info};
				for(String params:paramList){
					if(!params.contains("*")){			//不含*号，自动*1
						params+="*1";
					}
				}
				//通过验证，新增
				for(String params:paramList){
					String width=params.split("\\*")[0];			//宽度
					String cut_num=params.split("\\*")[1];		//条数
					Double d_width=Double.parseDouble(width);
					plan.setWidth(DoubleUtil.round(d_width, DoubleUtil.DEF_DIV_SCALE));
					plan.setCut_num((long) Double.parseDouble(cut_num));
					plan.setCut_order_no(order_num+1);
					String plan_no=plan.getContract_line_no()+String.format("%03d", (count+1));
					plan.setPlan_no(plan_no);
					plan.setCreate_man_no(userId);
					plan.setCreate_man_name(userName);
					plan.setCreate_time(new Date());
					plan.setValid_flag("1");
					plan.setPlan_flag("0");  		//待评审
					this.getMapper(SlmProcessPlanMapper.class).insert(plan);
					count++;
					order_num++;
				}
			}else{
				plan.setCut_order_no(order_num+1);
				String plan_no=plan.getContract_line_no()+String.format("%03d", (count+1));
				plan.setPlan_no(plan_no);
				plan.setCreate_man_no(userId);
				plan.setCreate_man_name(userName);
				plan.setCreate_time(new Date());
				plan.setValid_flag("1");
				plan.setPlan_flag("0");  		//待评审
				this.getMapper(SlmProcessPlanMapper.class).insert(plan);
			}
			//反写采购合同号
			rm=doAddPurchase(plan);
			rm=doUpdatePurchase(plan);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("新增失败"+e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 编辑
	 * plan_no
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmProcessPlan> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmProcessPlan plan=sum.getObject();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			// 验证加工序号不能重复
			SlmProcessPlan check=new SlmProcessPlan();
			check.setContract_no(plan.getContract_no());
			check.setContract_line_no(plan.getContract_line_seq());
			check.setOrder_seq(plan.getOrder_seq());
			check.setCut_order_no(plan.getCut_order_no());
			check.setValid_flag("1");
			List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).find(check, 0, 0);
			for(SlmProcessPlan plans:list){
				if(plans.getCut_order_no().equals(plan.getCut_order_no())&&!plans.getPlan_no().equals(plan.getPlan_no())){
					rm.setState("500");
					rm.setMsgInfo("编辑失败,分切序号已存在");
					return rm;
				}
			}
			check=this.getMapper(SlmProcessPlanMapper.class).findById(plan.getPlan_no());
			if("103413".equals(check.getPlan_flag())){
				rm.setState("500");
				rm.setMsgInfo("该加工计划处于质量评审中，请等待评审完毕再进行修改");
				return rm;
			}
			plan.setUpdate_man_no(userId);
			plan.setUpdate_man_name(userName);
			plan.setUpdate_time(new Date());
			this.getMapper(SlmProcessPlanMapper.class).update(plan);
			//反写采购合同号
			rm=doAddPurchase(plan);
			rm=doUpdatePurchase(plan);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("编辑失败"+e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	//修改其他加工计划的采购合同号
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdatePurchase(SlmProcessPlan plan) 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);
		try{
			SlmProcessPlan check=new SlmProcessPlan();
			check.setContract_no(plan.getContract_no());
			check.setContract_line_seq(plan.getContract_line_seq());
			check.setOrder_seq(plan.getOrder_seq());
			List<SlmProcessPlan> plan_list=this.getMapper(SlmProcessPlanMapper.class).find(check, 0, 0);
			for(SlmProcessPlan plans:plan_list){		//其余的加工计划连带修改
				if(!plans.getPlan_no().equals(plan.getPlan_no())){
					plans.setPurchase_contract_no(plan.getPurchase_contract_no());
					plans.setUpdate_man_no(userId);
					plans.setUpdate_man_name(userName);
					plans.setUpdate_time(new Date());
					this.getMapper(SlmProcessPlanMapper.class).update(plans);
				}
			}
		}catch(Exception e){
			//--19-10-15添加异常回滚
			throw new Exception();
		}
		return rm;
	}

	/**
	 * 启用停用  
	 * */
	public ResultModel doSwitchWeb(CommonPage<SlmProcessPlan> 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);
		SlmProcessPlan line=sum.getObject();
		String state="1".equals(line.getValid_flag())?"启用":"停用";
		try{
			SlmProcessPlan check=this.getMapper(SlmProcessPlanMapper.class).findById(line.getPlan_no());
			SlmProcessPlan newPlan=new SlmProcessPlan();
			newPlan.setValid_flag("1");
			newPlan.setContract_line_no(check.getContract_line_no());
			newPlan.setOrder_seq(check.getOrder_seq());
			if("0".equals(line.getValid_flag())){		//停用
				if("103413".equals(check.getPlan_flag())){
					rm.setState("500");
					rm.setMsgInfo("该加工计划处于质量评审中，请等待评审完毕再进行删除");
					return rm;
				}
				line.setDelete_man_no(userId);
				line.setDelete_man_name(userName);
				line.setDelete_time(new Date());
				List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).findWithCondition(newPlan, " valid_flag='1'", " cut_order_no", 0, 0);
				long cut_order_no=0;
				boolean in=false;
				for(SlmProcessPlan plans:list){
					if(plans.getPlan_no().equals(line.getPlan_no())){
						cut_order_no=plans.getCut_order_no();
						in=true;
					}
					if(cut_order_no<plans.getCut_order_no()&&in){
						plans.setCut_order_no(plans.getCut_order_no()-1);
						this.getMapper(SlmProcessPlanMapper.class).update(plans);
					}
				}
			}else{			//启用
				newPlan.setCut_order_no(check.getCut_order_no());
				int count=this.getMapper(SlmProcessPlanMapper.class).count(newPlan);
				if(count>0){
					rm.setState("500");
					rm.setMsgInfo("启用失败,分切序号已存在");
					return rm;
				}
				line.setUpdate_man_no(userId);
				line.setUpdate_man_name(userName);
				line.setUpdate_time(new Date());
			}
			this.getMapper(SlmProcessPlanMapper.class).update(line);
			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;
	}

	/**
	 * 加工计划 - 质量评审，修改plan_flag及订单状态 1、质量设计评审中；2、质量设计评审通过；3、质量设计评审失败
	 * 该订单下所有的加工计划都评审通过，该订单为评审通过，
	 * 只有一条加工计划通过，该订单为交期评审中
	 * 若有不通过的，则直接评审失败
	 * order_flag_no  2交期评审中、3评审通过（3、正常通过，4、强制通过）、5评审不通过
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReviewWeb(CommonPage<SlmProcessPlan> 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);
		SlmProcessPlan plan=sum.getObject();
		try{
			if(plan==null||plan.getPlan_flag()==null||plan.getPlan_no()==null){
				rm.setState("500");
				rm.setMsgInfo("请选择一条数据评审");
				return rm;
			}
			SlmProcessPlan check=this.getMapper(SlmProcessPlanMapper.class).findById(plan.getPlan_no());
			if(check==null){
				rm.setState("500");
				rm.setMsgInfo("加工计划数据不存在");
				return rm;
			}
			if("2".equals(check.getPlan_flag())||"3".equals(check.getPlan_flag())){
				rm.setState("500");
				rm.setMsgInfo("该数据已经进行评审");
				return rm;
			}
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_no(check.getContract_no());
			order.setContract_line_seq(check.getContract_line_seq());
			order.setOrder_seq(check.getOrder_seq());
			order.setValid_flag("1");
			List<SlmOrderInfo> orderList=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order,null," create_time desc", 0, 0);
			if(orderList.size()<1){
				rm.setState("500");
				rm.setMsgInfo("对应的订单不存在或已停用");
				return rm;
			}
			//更新加工计划状态
			plan.setUpdate_man_no(userId);
			plan.setUpdate_man_name(userName);
			plan.setUpdate_time(new Date());
			this.getMapper(SlmProcessPlanMapper.class).update(plan);

			order=orderList.get(0);
			if(!"103401".equals(order.getOrder_flag_no())||!"103402".equals(order.getOrder_flag_no())){
				rm.setState("500");
				rm.setMsgInfo("对应的订单已评审完毕");
				return rm;
			}
			//如果评审不通过
			if("3".equals(plan.getPlan_flag())){		
				order.setP_order_flag_no(order.getOrder_flag_no());
				order.setP_order_flag_name(order.getOrder_flag_name());
				order.setOrder_flag_no("103405");
				order.setOrder_flag_name("评审不通过");
			}

			if("2".equals(plan.getPlan_flag())){		//评审通过
				SlmProcessPlan paramPlan=new SlmProcessPlan();
				paramPlan.setContract_no(check.getContract_no());
				paramPlan.setContract_line_seq(check.getContract_line_seq());
				paramPlan.setOrder_seq(check.getOrder_seq());
				paramPlan.setValid_flag("1");
				List<SlmProcessPlan> planList=this.getMapper(SlmProcessPlanMapper.class).find(paramPlan, 0, 0);
				int size=0;
				for(SlmProcessPlan plans:planList){
					if("2".equals(plans.getPlan_flag())){
						size++;
					}
				}
				//修改订单状态
				if(size>0){
					if(size==planList.size()){		//所有的加工计划都评审通过
						order.setP_order_flag_no(order.getOrder_flag_no());
						order.setP_order_flag_name(order.getOrder_flag_name());
						order.setOrder_flag_no("103403");
						order.setOrder_flag_name("评审通过(正常)");
					}else{
						order.setOrder_flag_no("103402");
						order.setOrder_flag_name("交期评审中");
					}
				}
			}
			this.getMapper(SlmOrderInfoMapper.class).update(order);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * for质量 修改加工计划的状态为 质量设计评审中 103413
	 * 参数 ，主键 plan_no
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReviewing(SlmProcessPlan plan) throws Exception{
		ResultModel rm=new ResultModel();
		if(plan==null){
			rm.setState("500");
			rm.setMsgInfo("请传入加工计划");
			return rm;
		}
		String man_no=plan.getReview_man_no();
		String man_name=plan.getReview_man_name();
		Date man_time=plan.getReview_time();
		try{
			plan=this.getMapper(SlmProcessPlanMapper.class).findById(plan.getPlan_no());
			if(plan==null){
				rm.setState("500");
				rm.setMsgInfo("未找到对应的加工计划，请传入正确的加工计划号[plan_no]");
				return rm;
			}
			//找到对应的订单
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_no(plan.getContract_no());
			order.setContract_line_seq(plan.getContract_line_seq());
			order.setOrder_seq(plan.getOrder_seq());
			order.setValid_flag("1");
			List<SlmOrderInfo> orderList=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order,null," create_time desc", 0, 0);
			if(orderList.size()<1){
				rm.setState("500");
				rm.setMsgInfo("对应的订单不存在或已停用");
				return rm;
			}
			plan.setPlan_flag("103413"); 			//评审中
			plan.setReview_man_no(man_no);
			plan.setReview_man_name(man_name);
			plan.setReview_time(man_time);
			this.getMapper(SlmProcessPlanMapper.class).update(plan);
			//修改订单的状态
			order=orderList.get(0);
			order.setP_order_flag_no(order.getOrder_flag_no());
			order.setP_order_flag_name(order.getOrder_flag_name());
			order.setOrder_flag_no("103413");
			order.setOrder_flag_name("质量设计评审中");
			this.getMapper(SlmOrderInfoMapper.class).update(order);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setErrorInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * for质量 修改加工计划的状态为 质量设计评审通过 103414
	 * 参数 ，主键 plan_no
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReviewPass(SlmProcessPlan plan) throws Exception{
		ResultModel rm=new ResultModel();
		if(plan==null){
			rm.setState("500");
			rm.setMsgInfo("请传入加工计划");
			return rm;
		}
		String man_no=plan.getReview_man_no();
		String man_name=plan.getReview_man_name();
		Date man_time=plan.getReview_time();
		try{
			plan=this.getMapper(SlmProcessPlanMapper.class).findById(plan.getPlan_no());
			if(plan==null){
				rm.setState("500");
				rm.setMsgInfo("未找到对应的加工计划，请传入正确的加工计划号[plan_no]");
				return rm;
			}
			//找到对应的订单
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_no(plan.getContract_no());
			order.setContract_line_seq(plan.getContract_line_seq());
			order.setOrder_seq(plan.getOrder_seq());
			order.setValid_flag("1");
			List<SlmOrderInfo> orderList=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order,null," create_time desc", 0, 0);
			if(orderList.size()<1){
				rm.setState("500");
				rm.setMsgInfo("对应的订单不存在或已停用");
				return rm;
			}
			//限制状态
			//			if(!"103413".equals(plan.getPlan_flag())){
			//				rm.setState("500");
			//				rm.setMsgInfo("只有状态为评审中的加工计划才能设置为评审通过");
			//				return rm;
			//			}
			plan.setPlan_flag("103414"); 			//评审通过
			plan.setReview_man_no(man_no);
			plan.setReview_man_name(man_name);
			plan.setReview_time(man_time);
			this.getMapper(SlmProcessPlanMapper.class).update(plan);

			//判断是否所有的加工计划都为评审通过
			SlmProcessPlan paramPlan=new SlmProcessPlan();
			paramPlan.setContract_no(plan.getContract_no());
			paramPlan.setContract_line_seq(plan.getContract_line_seq());
			paramPlan.setOrder_seq(plan.getOrder_seq());
			paramPlan.setValid_flag("1");
			List<SlmProcessPlan> planList=this.getMapper(SlmProcessPlanMapper.class).find(paramPlan, 0, 0);
			int size=0;
			for(SlmProcessPlan plans:planList){
				if("103414".equals(plans.getPlan_flag())){
					size++;
				}
			}
			if(size>0&&size==planList.size()){			//修改订单的状态
				order=orderList.get(0);
				order.setP_order_flag_no(order.getOrder_flag_no());
				order.setP_order_flag_name(order.getOrder_flag_name());
				order.setOrder_flag_no("103414");
				order.setOrder_flag_name("质量设计评审通过");
				this.getMapper(SlmOrderInfoMapper.class).update(order);
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setErrorInfo(ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * for质量 修改加工计划的状态为 质量设计评审失败 103415
	 * 参数 ，主键 plan_no
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doReviewNotPass(SlmProcessPlan plan) throws Exception{
		ResultModel rm=new ResultModel();
		if(plan==null){
			rm.setState("500");
			rm.setMsgInfo("请传入加工计划");
			return rm;
		}
		String man_no=plan.getReview_man_no();
		String man_name=plan.getReview_man_name();
		Date man_time=plan.getReview_time();
		try{
			plan=this.getMapper(SlmProcessPlanMapper.class).findById(plan.getPlan_no());
			if(plan==null){
				rm.setState("500");
				rm.setMsgInfo("未找到对应的加工计划，请传入正确的加工计划号[plan_no]");
				return rm;
			}
			//找到对应的订单
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_no(plan.getContract_no());
			order.setContract_line_seq(plan.getContract_line_seq());
			order.setOrder_seq(plan.getOrder_seq());
			order.setValid_flag("1");
			List<SlmOrderInfo> orderList=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order,null," create_time desc", 0, 0);
			if(orderList.size()<1){
				rm.setState("500");
				rm.setMsgInfo("对应的订单不存在或已停用");
				return rm;
			}
			//限制状态
			//			if(!"103413".equals(plan.getPlan_flag())){
			//				rm.setState("500");
			//				rm.setMsgInfo("只有状态为评审中的加工计划才能设置为评审失败");
			//				return rm;
			//			}
			plan.setPlan_flag("103415"); 			//评审失败
			plan.setReview_man_no(man_no);
			plan.setReview_man_name(man_name);
			plan.setReview_time(man_time);
			this.getMapper(SlmProcessPlanMapper.class).update(plan);

			//暂时不修改订单状态
			order=orderList.get(0);
			order.setP_order_flag_no(order.getOrder_flag_no());
			order.setP_order_flag_name(order.getOrder_flag_name());
			order.setOrder_flag_no("103415");
			order.setOrder_flag_name("质量设计评审失败");
			this.getMapper(SlmOrderInfoMapper.class).update(order);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setErrorInfo(ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 导出加工计划 
	 * */
	public ResultModel doExportCensusWeb(CommonPage<SlmProcessPlan> sum){
		ResultModel rm=new ResultModel();
		SlmProcessPlan plan=sum.getObject();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		try{
			if(startTime!=null&&!"".equals(startTime)){		//页面上为开票时间
				startTime+=" 00:00:00";
			}
			if(endTime!=null&&!"".equals(endTime)){
				endTime+=" 23:59:59";
			}
			List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).doQueryCensus(plan,startTime,endTime);

			// 2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator; // 临时保存路径
			File dir = new File(path);
			if (!dir.exists()) {
				new File(path).mkdir();
			}
			generateExcel(rm, list, path,startTime,endTime);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 导出
	 * **/
	private void generateExcel(ResultModel rm, List<SlmProcessPlan> list, String path,String startTime,String endTime)
			throws IOException, WriteException, RowsExceededException {
		String filename ="";
		if(startTime != null && !"".equals(startTime)&&endTime != null && !"".equals(endTime)){
			startTime=startTime.substring(0, 10);
			endTime=endTime.substring(0, 10);
			filename = startTime +"至"+ endTime + "加工计划明细";
		}else{
			filename =  "加工计划明细";
		}
		WritableWorkbook workbook;
		String file=filename+".xls";  //文件名
		//3. 操作EXCEL文件
		workbook = Workbook.createWorkbook(new File(path+file));
		WritableSheet sheet = workbook.createSheet("加工计划明细", 1);
		//行高
		sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.LEFT);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		
		CellView cellview=new CellView();
		cellview.setAutosize(true);
		//表头
		sheet.mergeCells(0, 0, 0, 0);
		sheet.addCell(new Label(0,0,"序号",cellFormat1));

		sheet.mergeCells(1, 0, 1, 0);
		sheet.addCell(new Label(1,0,"客户名称",cellFormat1));
		

		sheet.mergeCells(2, 0, 2, 0);
		sheet.addCell(new Label(2,0,"合同号",cellFormat1));

		sheet.mergeCells(3, 0, 3, 0);
		sheet.addCell(new Label(3,0,"采购合同号",cellFormat1));

		sheet.mergeCells(4, 0, 4, 0);
		sheet.addCell(new Label(4,0,"订单序号",cellFormat1));

		sheet.mergeCells(5, 0, 5, 0);
		sheet.addCell(new Label(5,0,"钢级(牌号)",cellFormat1));

		sheet.mergeCells(6, 0, 6, 0);
		sheet.addCell(new Label(6,0,"备注",cellFormat1));

		sheet.mergeCells(7, 0, 7, 0);
		sheet.addCell(new Label(7,0,"分切公式",cellFormat1));

		sheet.mergeCells(8, 0, 8, 0);
		sheet.addCell(new Label(8,0,"规格",cellFormat1));

		sheet.mergeCells(9, 0, 9, 0);
		sheet.addCell(new Label(9,0,"重量",cellFormat1));

		sheet.mergeCells(10, 0, 10, 0);
		sheet.addCell(new Label(10,0,"计量单位",cellFormat1));

		sheet.mergeCells(11, 0, 11, 0);
		sheet.addCell(new Label(11,0,"分切方式",cellFormat1));

		sheet.mergeCells(12, 0, 12, 0);
		sheet.addCell(new Label(12,0,"横切方式",cellFormat1));

		sheet.mergeCells(13, 0, 13, 0);
		sheet.addCell(new Label(13,0,"评审状态",cellFormat1));
		
		sheet.mergeCells(14, 0, 14, 0);
		sheet.addCell(new Label(14,0,"创建人",cellFormat1));
		
		sheet.mergeCells(15, 0, 15, 0);
		sheet.addCell(new Label(15,0,"创建时间",cellFormat1));
		
		sheet.mergeCells(16, 0, 16, 0);
		sheet.addCell(new Label(16,0,"修改人",cellFormat1));
		
		sheet.mergeCells(17, 0, 17, 0);
		sheet.addCell(new Label(17,0,"修改时间",cellFormat1));

		WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat = new WritableCellFormat(font); 
		cellFormat.setAlignment(Alignment.LEFT);
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		//时间转字符串的格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(int i = 0; i < list.size(); i++) {
			//序号
			sheet.addCell(new Label(0,i+1,""+(i+1),cellFormat));
			//客户名称
			if(list.get(i).getCustomer_name() != null ) {
				sheet.addCell(new Label(1,i+1,list.get(i).getCustomer_name(),cellFormat));
			}
			//合同号
			if(list.get(i).getContract_no()!= null ) {
				sheet.addCell(new Label(2,i+1,list.get(i).getContract_no(),cellFormat));
			}
			//采购合同号
			if(list.get(i).getPurchase_contract_no()!= null ) {
				sheet.addCell(new Label(3,i+1,list.get(i).getPurchase_contract_no(),cellFormat));
			}
			//订单序号
			if(list.get(i).getOrder_seq()!= null ) {
				sheet.addCell(new Label(4,i+1,list.get(i).getOrder_seq(),cellFormat));
			}
			//钢级
			if(list.get(i).getSteel_name()!= null ) {
				sheet.addCell(new Label(5,i+1,list.get(i).getSteel_name(),cellFormat));
			}
			//备注
			if(list.get(i).getMemo()!= null ) {
				sheet.addCell(new Label(6,i+1,list.get(i).getMemo(),cellFormat));
			}
			//分切公式
			if(list.get(i).getAdd_ask_desc()!= null ) {
				sheet.addCell(new Label(7,i+1,list.get(i).getAdd_ask_desc(),cellFormat));
			}
			//规格
			if(list.get(i).getSpec()!= null ) {
				sheet.addCell(new Label(8,i+1,list.get(i).getSpec(),cellFormat));
			}
			//重量
			if(list.get(i).getEstimate_weight()!= null ) {
				sheet.addCell(new Label(9,i+1,String.valueOf(list.get(i).getEstimate_weight()),cellFormat));
			}
			//计量单位
			if(list.get(i).getEstimate_weight_unit_name()!= null ) {
				sheet.addCell(new Label(10,i+1,list.get(i).getEstimate_weight_unit_name(),cellFormat));
			}
			//分切方式 0：不切；1：横切(开平)；2：纵切(分条)；3：纵切并横切
			if(list.get(i).getCut_type()!= null ) {
				sheet.addCell(new Label(11,i+1,turnsCutType(list.get(i).getCut_type()),cellFormat));
			}
			//横切方式  横切方式 1：不横切；2：一切二；3：一切三 4：一切四
			if(list.get(i).getCrosscut_stype()!= null ) {
				sheet.addCell(new Label(12,i+1,turnsCrossType(list.get(i).getMemo()),cellFormat));
			}
			//评审状态
			if(list.get(i).getPlan_flag()!= null ) {
				sheet.addCell(new Label(13,i+1,turnsPlanFlag(list.get(i).getPlan_flag()),cellFormat));
			}
			//创建人
			if(list.get(i).getCreate_man_name()!= null ) {
				sheet.addCell(new Label(14,i+1, list.get(i).getCreate_man_name(),cellFormat));
			}
			//创建时间
			if(list.get(i).getCreate_time()!= null ) {
				sheet.addCell(new Label(15,i+1,sdf.format(list.get(i).getCreate_time()),cellFormat));
			}
			//修改人
			if(list.get(i).getUpdate_man_name()!= null ) {
				sheet.addCell(new Label(16,i+1,list.get(i).getUpdate_man_name(),cellFormat));
			}
			//修改时间
			if(list.get(i).getUpdate_time()!= null ) {
				sheet.addCell(new Label(17,i+1,sdf.format(list.get(i).getUpdate_time()),cellFormat));
			}
		}
		sheet.setColumnView(0, cellview);
		sheet.setColumnView(1, cellview);
		sheet.setColumnView(2, cellview);
		sheet.setColumnView(3, cellview);
		sheet.setColumnView(4, cellview);
		sheet.setColumnView(5, cellview);
		sheet.setColumnView(6, cellview);
		sheet.setColumnView(7, cellview);
		sheet.setColumnView(8, cellview);
		sheet.setColumnView(9, cellview);
		sheet.setColumnView(10, cellview);
		sheet.setColumnView(11, cellview);
		sheet.setColumnView(12, cellview);
		sheet.setColumnView(13, cellview);
		sheet.setColumnView(14, cellview);
		sheet.setColumnView(15, cellview);
		sheet.setColumnView(16, cellview);
		sheet.setColumnView(17, cellview);
		
		
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		//关闭
		workbook.write();
		workbook.close();

		rm.setData("/download?filename="+file);
	}
	

	//分切方式 0：不切；1：横切(开平)；2：纵切(分条)；3：纵切并横切
	public String transCutType(String param){
		String re="0";
		if(param==null||"".equals(param)){
			return re;
		}
		if(param.contains("横切")||param.contains("开平")){
			re="1";
		}else if(param.contains("纵切")||param.contains("分条")){
			re="2";
		}else if(param.contains("并")){
			re="3";
		}
		return re;
	}
	//横切方式 横切方式 1：不横切；2：一切二；3：一切三 4：一切四
	public String transCrossType(String param){
		String re="1";
		if(param==null||"".equals(param)){
			return re;
		}
		if(param.contains("二")){
			re="2";
		}else if(param.contains("三")){
			re="3";
		}else if(param.contains("四")){
			re="4";
		}else if(param.contains("五")){
			re="5";
		}
		return re;
	}
	
	//分切方式 0：不切；1：横切(开平)；2：纵切(分条)；3：纵切并横切
	public String turnsCutType(String param){
		String re="不切";
		if(param==null||"".equals(param)){
			return re;
		}
		if("1".equals(param)){
			re="开平";
		}else if("2".equals(param)){
			re="分条";
		}else if("3".equals(param)){
			re="开平并分条";
		}
		return re;
	}
	
	//评审状态  103413、质量设计评审中；103414、质量设计评审通过；103415、质量设计评审失败
	public String turnsPlanFlag(String param){
			String re="评审中";
			if(param==null||"".equals(param)){
				return re;
			}
			if("103413".equals(param)){
				re="质量设计评审中";
			}else if("103414".equals(param)){
				re="质量设计评审通过";
			}else if("103415".equals(param)){
				re="质量设计评审失败";
			}
			return re;
		}
		//横切方式 横切方式 1：不横切；2：一切二；3：一切三 4：一切四
		public String turnsCrossType(String param){
			String re="不横切";
			if(param==null||"".equals(param)){
				return re;
			}
			if("2".equals(param)){
				re="一切二";
			}else if("3".equals(param)){
				re="一切三";
			}else if("4".equals(param)){
				re="一切四";
			}
			return re;
		}
		
		/**
		 * for 订单导入接口
		 *	加工计划参数构建
		 * 然后新增
		 * */
		public ResultModel setPlanParam(SlmProcessPlan plan,SlmOrderInfo order) {
			ResultModel rm=new ResultModel();
			CommonPage<SlmProcessPlan> sum=new CommonPage<SlmProcessPlan>();
			try{
				plan.setContract_no(order.getContract_no());
				plan.setContract_line_seq(order.getContract_line_seq());
				plan.setContract_line_no(order.getContract_line_no());
				plan.setOrder_seq(order.getOrder_seq());
				plan.setPurchase_contract_no(order.getPurchase_contract_no());
				plan.setSteel_code(order.getSteel_code());
				plan.setSteel_name(order.getSteel_name());
				plan.setSpec(order.getThick()+"*"+order.getWidth());
				plan.setThick(order.getThick());
				plan.setWidth(order.getWidth());
				plan.setLen(order.getLength());
				plan.setEstimate_weight(order.getEstimate_weight());
				plan.setEstimate_weight_unit_no(order.getEstimate_weight_unit_no());
				plan.setEstimate_weight_unit_name(order.getEstimate_weight_unit_name());
				plan.setCut_type(transCutType(plan.getCut_type()));			//分切方式
				sum.setMemo1(plan.getCustomer_alpha_desc()); 		//分切公式
				plan.setCustomer_alpha_desc(null);
				sum.setObject(plan);
				rm=doAutoAddWeb(sum);
			}catch(Exception e){
				rm.setState("500");
				rm.setMsgInfo(e.getMessage());
			}
			return rm;
		}

		public ResultModel analysisFormula(String cross) {
			ResultModel rm=new ResultModel();
			String crosstype="1";
			String crossformula="";
			if(cross==null||"".equals(cross)){
				rm.setState("500");
				return rm;
			}
			if(!cross.contains("*")){
				rm.setState("500");
				return rm;
			}
			//含分号的情况  含中文和公式
			String type="";String formula="";
			if(cross.contains(";")||cross.contains("；")){
				if(cross.contains(";")){
					type=cross.split(";")[0];
					formula=cross.split(";")[1];
				}else if(cross.contains("；")){
					type=cross.split("；")[0];
					formula=cross.split("；")[1];	
				}
				if(type.contains("*")){				//反了 ，交换下值
					String temp=type; type=formula;formula=temp;
				}
				crosstype=transCrossType(type);
			}else{		//不含分隔符
				formula=cross;
			}
			if(formula.contains("=")){
				String left=formula.split("=")[0];
				String right=formula.split("=")[1];
				if(left.contains("*")) crossformula=left;
				else if(right.contains("*")) crossformula=right;
			}else{
				crossformula=formula;
			}
			rm.setMsgInfo(crosstype);
			rm.setData(crossformula);
			return rm;
		}
		
	//==================App eason add 2019-07-15===============
	/**
	 * 查询
	 * */
	public ResultModel doQueryApp(CommonPage<SlmProcessPlan> sum){
		ResultModel rm=new ResultModel();
		SlmProcessPlan plan=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmProcessPlan> pm=new PageModel<SlmProcessPlan>(pageIndex, pageSize);
		try{
			List<SlmProcessPlan> list=this.getMapper(SlmProcessPlanMapper.class).findWithCondition(plan, " valid_flag='1'", " cut_order_no", pageSize*(pageIndex-1), pageSize);
			int count=this.getMapper(SlmProcessPlanMapper.class).countWithCondition(plan, " valid_flag='1'");
			pm.setTotal(count);
			pm.setRows(list);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}
}

