/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2017.11.21
 * 描述               :        			分条计划
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/

package market.Mes.Lengthwise.Plan.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 market.Api.Mes.impl.MesApiDesignInfoImpl;
import market.Api.Mes.impl.MesApiServiceImpl;
import market.Api.Mes.impl.Utils;
import market.Api.Mes.service.MesApiService;
import market.Com.impl.PbModelDbServiceImpl;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseMachineMapper;
import market.Com.mapper.ComDsnPltlmtMapper;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.ComBaseMachine;
import market.Com.vo.ComDsnPltlmt;
import market.Com.vo.CommonPage;
import market.Com.vo.PbModelDb;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Mes.Lengthwise.Design.mapper.PlnDsnOrderInfoMapper;
import market.Mes.Lengthwise.Design.mapper.PlnLengthwiseDsnMainMapper;
import market.Mes.Lengthwise.Design.vo.ClsRestrict;
import market.Mes.Lengthwise.Design.vo.PlnDsnOrderInfo;
import market.Mes.Lengthwise.Design.vo.PlnLengthwiseDsnMain;
import market.Mes.Lengthwise.Design.vo.PlnLengthwiseDsnMainSum;
import market.Mes.Lengthwise.Plan.mapper.PlnLengthwisePlanDetailMapper;
import market.Mes.Lengthwise.Plan.mapper.PlnLengthwisePlanMapper;
import market.Mes.Lengthwise.Plan.mapper.PlnLwPlanStatisticMapper;
import market.Mes.Lengthwise.Plan.mapper.PlnMaterielDetailMapper;
import market.Mes.Lengthwise.Plan.service.PlnLengthwisePlanService;
import market.Mes.Lengthwise.Plan.vo.PlnLengthwisePlan;
import market.Mes.Lengthwise.Plan.vo.PlnLengthwisePlanDetail;
import market.Mes.Lengthwise.Plan.vo.PlnLengthwisePlanSum;
import market.Mes.Lengthwise.Plan.vo.PlnLwPlanStatistic;
import market.Mes.Lengthwise.Plan.vo.PlnMaterielDetail;
import market.Mes.MaterielTrack.vo.PrcMaterielProcess;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Mes.OrderManager.Plan.mapper.PlnOrderStatisticMapper;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderMapper;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderStatisticMapper;
import market.Mes.OrderManager.Plan.vo.PlnOrderStatistic;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Mes.OrderManager.Plan.vo.PlnProdorderStatistic;

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="PlnLengthwisePlanService")
public class PlnLengthwisePlanServiceImpl extends BaseServiceImpl<PlnLengthwisePlan,Object> implements PlnLengthwisePlanService {
	
	/**
	 * 作业计划主数据（原料卷主信息）
	 * @param memo1 传1为自动定位
	 * */
	public ResultModel doQueryWeb(CommonPage<PlnLengthwisePlan> oci){
		ResultModel rm=new ResultModel();
		try{
			String sWhere="";
			PlnLengthwisePlan mcsm=oci.getObject();
			//如果memo1为1 则增加 条件
			if(oci.getMemo1()!=null&&"1".equals(oci.getMemo1())){
				sWhere=" and t1.plan_seq >= (select min(plan_seq) from pln_lengthwise_plan x where x.machine_code= '"+mcsm.getMachine_code()+"' and (x.status = '0PLW02' or x.status = '0PLW03')) ";
				oci.setStartTime("");
				oci.setEndTime("");
				mcsm.setLw_plan_no(null);
			}
			List<PlnLengthwisePlanSum> lplps = this.getMapper(PlnLengthwisePlanMapper.class).doQuery(mcsm,oci.getStartTime(),oci.getEndTime(),sWhere);
			if(lplps==null||lplps.size()==0){
				rm.setMsgInfo("未找到数据");
				return rm;
			}
			rm.setData(lplps);
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}


	/**
	 * 查询待编制计划钢卷
	 * memo1 1为计划时间 2为交货时间
	 * memo2 外径下限值
	 * memo3 外径上限值
	 * memo4 分条计划号
	 * */
	public ResultModel doQueryWaitPlanWeb(CommonPage<PlnLengthwiseDsnMain> sum){
		ResultModel rm=new ResultModel();
		try{
			// 工序点信息
			ComBaseInfo infoI = this.getMapper(ComBaseInfoMapper.class).findById("200201");
			String sWhere1="",sWhere2="",sWhere3="";
			//假如为1则为计划时间  为2交货时间 4交货时间
			if("2".equals(sum.getMemo1())){
				sWhere1+=" and t3.deliver_date between to_date('"+sum.getStartTime()+"','yyyy-MM-dd HH24:mi:ss') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd HH24:mi:ss') ";
			}else if ("4".equals(sum.getMemo1())) {
				sWhere1+=" and t3.create_time between to_date('"+sum.getStartTime()+"','yyyy-MM-dd HH24:mi:ss') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd HH24:mi:ss') ";
			}

			if(sum.getMemo2()!=null&&!"".equals(sum.getMemo2())){
				sWhere3+=" and t1.diameter_out>="+sum.getMemo2();
			}
			if(sum.getMemo3()!=null&&!"".equals(sum.getMemo3())){
				sWhere3+=" and t1.diameter_out<="+sum.getMemo3();
			}
			if(sum.getMemo4()!=null&&!"".equals(sum.getMemo4().trim())){
				sWhere3+=" and t1.lw_plan_no like '%"+sum.getMemo4().trim()+"%'";
			}

			PlnLengthwiseDsnMain pdm=(sum.getObject()==null?(new PlnLengthwiseDsnMain()):sum.getObject());
			if(sum.getObject()!=null){
				//条件2
				if(sum.getObject().getOrder_no()!=null
						&&!"".equals(sum.getObject().getOrder_no().trim())){
					sWhere2+=" and t2.order_no like '%"+sum.getObject().getOrder_no().trim()+"%' ";
				}
				if(sum.getObject().getProd_order_no()!=null
						&&!"".equals(sum.getObject().getProd_order_no().trim())){
					sWhere2+=" and t2.prod_order_no like '%"+sum.getObject().getProd_order_no().trim()+"%' ";
				}
			}
			
			//这里面的sql有个分条代码需要知晓***************************
			//rm.setData(this.getMapper(PlnLengthwiseDsnMainMapper.class).doQueryWaitPlan(sWhere1, sWhere2, sWhere3,pdm));
			rm.setData(this.getMapper(PlnLengthwiseDsnMainMapper.class).doQueryWaitPlan1(sWhere1, sWhere2, sWhere3,pdm,infoI.getMemo()));

			rm.setState("200");

		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询出错！");
			rm.setErrorInfo(ex.getMessage());
		}
		return rm;
	}
	
	// 调整计划序号 2018-12-18
	// 表计划旧  计划号-顺序号 
	Map<String, Integer> v_planno_old = new HashMap<String, Integer>();
	
	/**
	 * 查询已编制分条计划
	 * memo1 1为下发生产时间 2为交货时间
	 * memo2 外径下限值
	 * memo3 外径上限值
	 * memo4 分条计划号
	 * 		 修改生成时间为母卷上料时间
	 * */
	public ResultModel doQueryCompletePlanWeb(CommonPage<PlnLengthwiseDsnMain> sum){
		ResultModel rm=new ResultModel();
		v_planno_old.clear();
		try{
			StringBuffer sWhere0 = new StringBuffer();
			StringBuffer sWhere1 = new StringBuffer();
			StringBuffer sWhere2 = new StringBuffer();
			StringBuffer sWhere3 = new StringBuffer();
			//假如为1则为下发生产时间  为2交货时间  3生产时间 4订单接收时间
			if("1".equals(sum.getMemo1())){
				sWhere0.append(" and t6.send_date between to_date('"+sum.getStartTime()+"','yyyy-MM-dd HH24:mi:ss') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd HH24:mi:ss') ");
			}else if("2".equals(sum.getMemo1())){
				sWhere1.append(" and p.deliver_date between to_date('"+sum.getStartTime()+"','yyyy-MM-dd HH24:mi:ss') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd HH24:mi:ss') ");
			}else if ("3".equals(sum.getMemo1())) {
				sWhere0.append(" and ttt.feeding_time between to_date('"+sum.getStartTime()+"','yyyy-MM-dd HH24:mi:ss') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd HH24:mi:ss') ");
			}else if ("4".equals(sum.getMemo1())) {
				sWhere1.append(" and p.create_time between to_date('"+sum.getStartTime()+"','yyyy-MM-dd HH24:mi:ss') and to_date('"+sum.getEndTime()+"','yyyy-MM-dd HH24:mi:ss') ");
			}
			if(sum.getMemo2()!=null&&!"".equals(sum.getMemo2())){
				sWhere3.append(" and t1.diameter_out>="+sum.getMemo2());
			}
			if(sum.getMemo3()!=null&&!"".equals(sum.getMemo3())){
				sWhere3.append(" and t1.diameter_out<="+sum.getMemo3());
			}
			if(sum.getMemo4()!=null&&!"".equals(sum.getMemo4().trim())){
				sWhere3.append(" and t1.lw_plan_no like '%"+sum.getMemo4().trim()+"%'");
			}

			PlnLengthwiseDsnMain pdm=(sum.getObject()==null?(new PlnLengthwiseDsnMain()):sum.getObject());
			if(sum.getObject()!=null){
				//条件2
				if(sum.getObject().getOrder_no()!=null
						&&!"".equals(sum.getObject().getOrder_no().trim())){
					sWhere2.append(" and p.order_no like '%"+sum.getObject().getOrder_no().trim()+"%' ");
				}
				if(sum.getObject().getProd_order_no()!=null
						&&!"".equals(sum.getObject().getProd_order_no().trim())){
					sWhere2.append(" and p.prod_order_no like '%"+sum.getObject().getProd_order_no().trim()+"%' ");
				}
				// 增加状态筛选框默认不显示已完成的计划
				if(Utils.isEmpty(sum.getObject().getStatus())) {
					sWhere0.append(" and t6.status != '5BLW10' ");
				} else if (!sum.getObject().getStatus().equals("0")) {
					sWhere0.append(" and t6.status = '"+sum.getObject().getStatus()+"'");
				}
			}
			List<PlnLengthwiseDsnMainSum> listPSum = this.getMapper(PlnLengthwiseDsnMainMapper.class)
					.doQueryCompletePlan(sWhere0.toString(),sWhere1.toString(), sWhere2.toString(), sWhere3.toString(),pdm);
			for(PlnLengthwiseDsnMainSum orders:listPSum){
				// 在界面查询刷新后，赋值 V_PlanNo 和 V_PlanSeq_Old
				v_planno_old.put(orders.getLw_plan_no(), orders.getPlan_seq());
				//加工计划备注PlnProcessPlan
//				PlnProcessPlan pplan=new PlnProcessPlan();
//				pplan.setOrder_no(orders.getOrder_no());
//				pplan.setCut_order_no(1L);
//				// SELECT PLAN_NO,PRODUCE_NO,CUT_ORDER_NO,ORDER_NO,PURCHASE_CONTRACT_NO,STEEL_CODE,STEEL_NAME,SPEC,MAT_WIDTH,MAT_THICK,MAT_LENGTH,MAT_DIAMETER_INN,MAT_DIAMETER_OUT,MAT_ESTIMATE_WEIGHT,WIDTH,THICK,LENGTH,DIAMETER_INN,DIAMETER_OUT,ESTIMATE_WEIGHT,CUT_STYLE,CROSSCUT_STYLE,CUT_TYPE,CUT_NUM,REMARK,VALID_FLAG,CREATE_MAN_NAME,CREATE_TIME,UPDATE_MAN_NAME,UPDATE_TIME FROM PLN_PROCESS_PLAN WHERE CUT_ORDER_NO = 1 AND ORDER_NO = 'YTGD-0329010001'
//				List<PlnProcessPlan> planList=this.getMapper(PlnProcessPlanMapper.class).findWithCondition(pplan, "", null, 0, 0);
//				if(planList.size()>0){
//					//关联加工计划信息表SLM_PROCESS_PLAN查询加工计划备注
//					orders.setProcessMemo(planList.get(0).getRemark());
//				}
			}
			rm.setData(listPSum);
			rm.setState("200");

		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询出错！");
			rm.setErrorInfo(ex.getMessage());
		}
		return rm;
	}

	
	/**
	 * 动作处理_移动确认按钮
	 * 
	 * @param sum V_PlanNo--按顺序保存左表计划号 查询的时候保存 V_PlanSeq_Old--按顺序保存左表计划顺序号
	 *            V_PlanSeq_New
	 * @return
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doMove(CommonPage<PlnLengthwisePlan> sum) throws Exception {
		ResultModel rm = new ResultModel();
		// 记录计划号index用于查找对应循序号
		Integer i = 0;
		List<PlnLengthwisePlan> plns = sum.getObjectList();
		PlnLengthwisePlan p = new PlnLengthwisePlan();
		for (PlnLengthwisePlan pln : plns) {
			i = v_planno_old.get(pln.getLw_plan_no());
			if (i == 0) {
				throw new Exception("调整计划顺序失败。计划[" + pln.getLw_plan_no() + "]的顺序或状态已经改变，请刷新重试。");
			}
			p.setLw_plan_no(pln.getLw_plan_no());
			List<PlnLengthwisePlan> plrp = this.getMapper(PlnLengthwisePlanMapper.class).find(p, 0, 0);
			if (plrp == null || plrp.size() == 0) {
				throw new Exception("计划信息[" + pln.getLw_plan_no() + "]不存在！");
			}
//			if (!"0PLW01".equals(plrp.get(0).getStatus())) {
//				throw new Exception("只有已编制待下发计划允许调整循序！");
//			}
			int count = this.getMapper(PlnLengthwisePlanMapper.class).doUpdateSeq(pln, i);
			if (count == 0) {
				throw new Exception("调整计划顺序失败。计划[" + pln.getLw_plan_no() + "]的顺序或状态已经改变，请刷新重试。");
			}
		}
		// 释放旧数据
		v_planno_old.clear();
		rm.setState("200");
		rm.setMsgInfo("调整计划循序成功!");
		return rm ; 
	}

	/**
	 * 分条计划编制 虚拟物料号数组
	 * memo1 计划分条时间
	 * memo2 机台编号
	 * memo3 = 1 :母卷批量编制到同一个计划 ; 默认为空一个卷一个计划。
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddWeb(CommonPage<String[]> oci) throws Exception{
		ResultModel rm=new ResultModel();

		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);

		//虚拟物料号数组
		String[] ObjectNoVts=oci.getObject();
		List<PlnMaterielDetail> lpmd=new ArrayList<PlnMaterielDetail>();
		for(String s:ObjectNoVts){
			//查询虚拟卷
			PlnMaterielDetail pmd=new PlnMaterielDetail();
			pmd.setObject_no_vt(s);
			List<PlnMaterielDetail> lpmdq=this.getMapper(PlnMaterielDetailMapper.class).find(pmd, 0, 0);

			if(lpmdq==null||lpmdq.size()==0){
				rm.setState("500");
				rm.setMsgInfo("虚拟物料["+s+"]信息不存在!");
				return rm;
			}
			if (Utils.isNotEmpty(lpmdq.get(0).getObject_no())) {
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(lpmdq.get(0).getObject_no());
				if (Utils.isNotEmpty(ypd) && !"0".equals(ypd.getState())) {
					rm.setState("500");
					rm.setMsgInfo("请先将物料[" + lpmdq.get(0).getObject_no() + "]入库再编制计划！");
					return rm;
				}
			}
			//实际上只有一条
			for(PlnMaterielDetail pmdq:lpmdq){
				if(!"".equals(pmdq.getLw_plan_no())&&pmdq.getLw_plan_no()!=null){
					rm.setState("500");
					rm.setMsgInfo("虚拟物料["+s+"]已经在计划["+pmdq.getLw_plan_no()+"]内，无法再次编制！");
					return rm;
				}

				PlnLengthwisePlanDetail ppd=new PlnLengthwisePlanDetail();
				ppd.setObject_no_vt(pmdq.getObject_no_vt());
				int icount=this.getMapper(PlnLengthwisePlanDetailMapper.class).countWithCondition(ppd," STATUS<= '0PLW10' ");
				if(icount>0){
					rm.setState("500");
					rm.setMsgInfo("虚拟物料["+s+"]已经在计划["+pmdq.getLw_plan_no()+"]内，无法再次编制！");
					return rm;
				}

				//若虚拟物料表的 (OPT_TIMES >=1 AND NEED_EXTOPT =0) ,则报错退出
				if(pmdq.getOpt_times()!=null&&pmdq.getOpt_times()>=1
						&&"1".equals(pmdq.getNeed_extopt())){
					rm.setState("500");
					rm.setMsgInfo("虚拟物料["+s+"]已经生产完毕，不能编制计划！");
					return rm;
				}

				//单重求和
				if(pmdq.getSingle_weight()==null){
					rm.setState("500");
					rm.setMsgInfo("虚拟物料["+s+"]没有单重！");
					return rm;
				}
				lpmd.add(pmdq);
			}
		}
		PlnLengthwisePlan pp = new PlnLengthwisePlan();
		//  所选母卷统一编制到同一个计划
		if ("1".equals(oci.getMemo3())) {
			//  保存相关数据: 
		    pp=getPlanNo();
			pp.setPlan_seq(pp.getSerial_no());
			pp.setStatus("0PLW01");
			pp.setPline_code(lpmd.get(0).getPline_code());
			pp.setMachine_code(oci.getMemo2());
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(oci.getMemo1());
			pp.setStart_time(date);
			pp.setCreate_man_name(userName);
			pp.setCreate_time(new Date());
			this.getMapper(PlnLengthwisePlanMapper.class).insert(pp);
			
			//分条计划明细表：对选中的各母卷分别增加明细记录
			for (PlnMaterielDetail pmd : lpmd) {
				List<PlnLengthwisePlanDetail> lppd=this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(null, "", " serial_no desc ", 0, 1);
				long sNo=0;
				if(lppd==null||lppd.size()==0){
					sNo=1;
				}else{
					sNo=lppd.get(0).getSerial_no()+1;
				}
				int isqe=0;
				PlnLengthwisePlanDetail plpdq=new PlnLengthwisePlanDetail();
				plpdq.setLw_plan_no(pp.getLw_plan_no());
				lppd=this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(plpdq, "", " lw_seq desc ", 0, 1);
				if(lppd==null||lppd.size()==0){
					isqe=1;
				}else{
					isqe=lppd.get(0).getLw_seq()+1;
				}
				PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
				plpd.setSerial_no(sNo++);
				plpd.setLw_plan_no(pp.getLw_plan_no());
				plpd.setLw_seq(isqe++);
				plpd.setObject_no(pmd.getObject_no());
				plpd.setObject_no_vt(pmd.getObject_no_vt());
				plpd.setLw_design_no(pmd.getLw_design_no());
				plpd.setStatus("5BLW01");
				plpd.setPline_code(pmd.getPline_code());
				plpd.setMachine_code(pmd.getMachine_code());
				plpd.setSteel_code(pmd.getSteel_code());
				plpd.setMat_width(pmd.getWidth());
				plpd.setMat_thick(pmd.getThick());
				plpd.setMat_diameter_inn(pmd.getDiameter_inn());
				plpd.setMat_diameter_out(pmd.getDiameter_out());
				plpd.setMat_length(pmd.getLength());
				plpd.setMat_single_weight(pmd.getSingle_weight());
				plpd.setPlan_opt_time(pp.getStart_time());
				plpd.setCreate_man_name(userName);
				plpd.setCreate_time(new Date());
				
				PlnLengthwiseDsnMain pldm=new PlnLengthwiseDsnMain();
				pldm.setLw_design_no(pmd.getLw_design_no());
				List<PlnLengthwiseDsnMain> lpldm=this.getMapper(PlnLengthwiseDsnMainMapper.class).find(pldm, 0, 1);
				plpd.setRate(lpldm.get(0).getProd_rate());
				plpd.setSub_count(lpldm.get(0).getSub_count().intValue()*Integer.parseInt(lpldm.get(0).getCrosscut_style()));
				
				this.getMapper(PlnLengthwisePlanDetailMapper.class).insert(plpd);
				
				//虚拟物料表：修改子卷的 分条计划号[LW_PLANNO]字段
				PlnMaterielDetail pmdu=new PlnMaterielDetail();
				pmdu.setLw_plan_no(pp.getLw_plan_no());
				pmdu.setSerial_no(pmd.getSerial_no());
				this.getMapper(PlnMaterielDetailMapper.class).update(pmdu);
				
				//写虚拟物料履历，状态填:0PLW01		子卷																			
				this.getBean(MesApiServiceImpl.class).InsertMatVtProc(pmd.getObject_no_vt(), "0PLW01", userName, new Date());
			}
		}else {
			
			// 一个母卷对应一个计划号
			for (PlnMaterielDetail pmd : lpmd) {
				//保存相关数据: 
				pp=getPlanNo();
				pp.setPlan_seq(pp.getSerial_no());
				pp.setStatus("0PLW01");
				pp.setPline_code(lpmd.get(0).getPline_code());
				pp.setMachine_code(pmd.getMachine_code());
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date date = sdf.parse(oci.getMemo1());
				pp.setStart_time(date);
				pp.setCreate_man_name(userName);
				pp.setCreate_time(new Date());
				this.getMapper(PlnLengthwisePlanMapper.class).insert(pp);
				
				//分条计划明细表：对选中的各母卷分别增加明细记录
				List<PlnLengthwisePlanDetail> lppd=this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(null, "", " serial_no desc ", 0, 1);
				long sNo=0;
				if(lppd==null||lppd.size()==0){
					sNo=1;
				}else{
					sNo=lppd.get(0).getSerial_no()+1;
				}
				
				
				int isqe=0;
				PlnLengthwisePlanDetail plpdq=new PlnLengthwisePlanDetail();
				plpdq.setLw_plan_no(pp.getLw_plan_no());
				lppd=this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(plpdq, "", " lw_seq desc ", 0, 1);
				if(lppd==null||lppd.size()==0){
					isqe=1;
				}else{
					isqe=lppd.get(0).getLw_seq()+1;
				}
				
				PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
				plpd.setSerial_no(sNo++);
				plpd.setLw_plan_no(pp.getLw_plan_no());
				plpd.setLw_seq(isqe++);
				plpd.setObject_no(pmd.getObject_no());
				plpd.setObject_no_vt(pmd.getObject_no_vt());
				plpd.setLw_design_no(pmd.getLw_design_no());
				plpd.setStatus("5BLW01");
				plpd.setPline_code(pmd.getPline_code());
				plpd.setMachine_code(pmd.getMachine_code());
				plpd.setSteel_code(pmd.getSteel_code());
				plpd.setMat_width(pmd.getWidth());
				plpd.setMat_thick(pmd.getThick());
				plpd.setMat_diameter_inn(pmd.getDiameter_inn());
				plpd.setMat_diameter_out(pmd.getDiameter_out());
				plpd.setMat_length(pmd.getLength());
				plpd.setMat_single_weight(pmd.getSingle_weight());
				plpd.setPlan_opt_time(pp.getStart_time());
				plpd.setCreate_man_name(userName);
				plpd.setCreate_time(new Date());
				
				PlnLengthwiseDsnMain pldm=new PlnLengthwiseDsnMain();
				pldm.setLw_design_no(pmd.getLw_design_no());
				List<PlnLengthwiseDsnMain> lpldm=this.getMapper(PlnLengthwiseDsnMainMapper.class).find(pldm, 0, 1);
				plpd.setRate(lpldm.get(0).getProd_rate());
				plpd.setSub_count(lpldm.get(0).getSub_count().intValue()*Integer.parseInt(lpldm.get(0).getCrosscut_style()));
				this.getMapper(PlnLengthwisePlanDetailMapper.class).insert(plpd);
				
				//虚拟物料表：修改子卷的 分条计划号[LW_PLANNO]字段
				PlnMaterielDetail pmdu=new PlnMaterielDetail();
				pmdu.setLw_plan_no(pp.getLw_plan_no());
				pmdu.setSerial_no(pmd.getSerial_no());
				this.getMapper(PlnMaterielDetailMapper.class).update(pmdu);
				
				//写虚拟物料履历，状态填:0PLW01		子卷																			
				this.getBean(MesApiServiceImpl.class).InsertMatVtProc(pmd.getObject_no_vt(), "0PLW01", userName, new Date());
				
			}
		}		
		
		//虚拟物料表：修改各母卷，的分条计划号[LW_PLANNO]字段
		for(String s:ObjectNoVts){
			PlnMaterielDetail pmdu=new PlnMaterielDetail();
			pmdu.setObject_no_vt(s);
			pmdu.setLw_plan_no(pp.getLw_plan_no());
			this.getMapper(PlnMaterielDetailMapper.class).doUpdateLwPlanNo(pmdu);

			//写虚拟物料履历，状态填:0PLW01			母卷																		
			this.getBean(MesApiServiceImpl.class).InsertMatVtProc(s, "0PLW01", userName, new Date());

			doAddChildMethod(pmdu);
		}

		rm.setState("200");
		return rm;
	}

	/**
	 * doAddWeb的子方法
	 * @throws Exception 
	 * */
	private void doAddChildMethod(PlnMaterielDetail pmd) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		//判断虚拟母卷对应的实物号是否挂料,如果  object_no<>null

		pmd=this.getMapper(PlnMaterielDetailMapper.class).find(pmd, 0, 1).get(0);

		if(pmd.getObject_no()!=null){
			//调用接口 新增实物物料状态跟踪	
			//调用 新增实物物料状态跟踪:  传入（实物子卷号,5BLW10，操作时间，操作人，""）
			PrcMaterielProcess pmp=new PrcMaterielProcess();
			pmp.setObject_no(pmd.getObject_no());
			pmp.setPrc_code("5BLW01");//新增的状态
			pmp.setCreate_time(new Date());
			pmp.setCreate_man_name(userName);
			pmp.setRemark("");
			//新增物料跟踪：
			this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
		}
		double One_Weight=0;
		int One_Quantity=0;
		//根据母卷的【CREATE_DESIGN_NO】, 读取【pln_dsn_order_info】
		if (Utils.isEmpty(pmd.getLw_design_no())) {
			throw new Exception("数据错误 ! 请联系管理员![虚拟物料:"+pmd.getObject_no_vt()+" 设计号不存在!]");
		}
		PlnDsnOrderInfo pdoi=new PlnDsnOrderInfo();
		pdoi.setDesign_no(pmd.getLw_design_no());
		List<PlnDsnOrderInfo> lpoi=this.getMapper(PlnDsnOrderInfoMapper.class).find(pdoi, 0, 0);
		if(lpoi!=null&&lpoi.size()>0){
			for(PlnDsnOrderInfo s2:lpoi){
				One_Weight+=s2.getWeight_in_one()==null?0:s2.getWeight_in_one();
				One_Quantity+=s2.getQuantity_in_one()==null?0:s2.getQuantity_in_one();

				//根据S2的 生产订单号，修改对应 生产订单进程表[PLN_PRODORDER_STATISTIC]
				PlnProdorderStatistic pps=new PlnProdorderStatistic();
				pps.setProd_order_no(s2.getProd_order_no());
				pps.setLw_planed(s2.getWeight_in_one());
				pps.setLw_planed_cnt(s2.getQuantity_in_one());
				this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

				//根据S2的 订单号，修改  订单进程表[PLN_ORDER_STATISTIC]
				PlnOrderStatistic pos=new PlnOrderStatistic();
				pos.setOrder_no(s2.getOrder_no());
				pos.setLw_planed(s2.getWeight_in_one());
				pos.setLw_planed_cnt(s2.getQuantity_in_one());
				this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);
			}
		}

		PlnLwPlanStatistic plps=new PlnLwPlanStatistic();
		plps.setLw_plan_no(pmd.getLw_plan_no());
		int icount=this.getMapper(PlnLwPlanStatisticMapper.class).count(plps);
		if(icount==0){
			List<PlnLwPlanStatistic> lplps=this.getMapper(PlnLwPlanStatisticMapper.class).findWithCondition(null, null, " to_number(serial_no) desc ", 0, 1);
			if(lplps!=null&&lplps.size()>0){
				plps.setSerial_no((Long.parseLong(lplps.get(0).getSerial_no().trim())+1)+"");
			}else{
				plps.setSerial_no("1");
			}
		}
		//修改 分条计划进程表 [PLN_LW_PLAN_STATISTIC]  修改 纵剪计划进程表 [PLN_LW_PLAN_STATISTIC]
		plps.setMat_planed(pmd.getSingle_weight());
		plps.setMat_planed_cnt(1);
		plps.setPlaned(One_Weight);
		plps.setPlaned_cnt(One_Quantity);
		if(icount==0){
			this.getMapper(PlnLwPlanStatisticMapper.class).insert(plps);
		}else{
			this.getMapper(PlnLwPlanStatisticMapper.class).doUpdatePlaned(plps);
		}
		//修改分条计划表： QUANTITY 数量 += 1;   TOTALWEIGHT 总重量 += 虚拟物料号单重
		PlnLengthwisePlan plp=new PlnLengthwisePlan();
		plp.setLw_plan_no(pmd.getLw_plan_no());
		plp.setMat_quantity(1);
		plp.setMat_weight(pmd.getSingle_weight());
		this.getMapper(PlnLengthwisePlanMapper.class).doUpdatePlaned(plp);

		//调用【接口文档--公共函数SHEET--修改分条计划主表状态
		this.getBean(MesApiServiceImpl.class).doUpdatePlnLengthwisePlan(pmd.getLw_plan_no());
	}

	/**
	 * 选定物料加入分条计划
	 * PlnMaterielDetail object_no_vt 数组 lw_plan_no 数组
	 * memo1 计划分条时间
	 * machine_code 机台编码
	 * memo3 = 1 :母卷批量编制到同一个计划 ; 默认为空:一个卷一个计划。
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCheckPlanAdd(CommonPage<PlnMaterielDetail> oci) throws Exception{
		ResultModel rm=new ResultModel();
		if (Utils.isEmpty(oci)) {
			rm.setState("500");
			rm.setMsgInfo("请传入参数!");
			return rm;
		}
		List<PlnMaterielDetail> lpmd=oci.getObjectList();
		// 获取主计划计划号和序列号
		PlnLengthwisePlan ppoo = getPlanNo();
		// 记录物料对应的计划号
		String plan_no = "";
		PlnLengthwisePlan plpl = new PlnLengthwisePlan();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		for (PlnMaterielDetail plnmd : lpmd) {
			if (Utils.isEmpty(plnmd.getMachine_code())) {
				rm.setState("500");
				rm.setMsgInfo("编制计划之前,请先选择机台!");
				return rm;
			}
			// 验证设备限制信息 2018-10-26
			List<ComBaseInfo> cbf = this.getMapper(ComBaseInfoMapper.class)
					.findWithCondition(null,
							" base_code = '2008' and  validflag = '1'", null,
							0, 1);
			if (Utils.isNotEmpty(cbf)) {
				// 读取基础配置 产线机组限制表
				ComDsnPltlmt cdp = new ComDsnPltlmt();
				cdp.setPlt("Y1");// 工厂
				cdp.setPlt_line(plnmd.getMachine_code());// 产线
				List<ComDsnPltlmt> lc = this.getMapper(
						ComDsnPltlmtMapper.class).find(cdp, 0, 0);
				if (Utils.isEmpty(lc)) {
					throw new Exception("未找到机台设备信息");
				}
				
				// 获取机台代码名称
				List<ComBaseMachine> cbm = this.getMapper(ComBaseMachineMapper.class).findWithCondition(null, "machine_code = '"+plnmd.getMachine_code()+"' and validflag = '1'", null, 0, 1);
				
				ClsRestrict MachineRestrict = new ClsRestrict(lc);
				
				ResultModel thick_rm = this.getBean(PbModelDbServiceImpl.class)
						.findPlnThickRangeCmbDb();
				if (!"200".equals(thick_rm.getState())) {
					throw new Exception("获取厚度公差范围失败！");
				}
				List<PbModelDb> lpmdd = (List<PbModelDb>) thick_rm.getData();
				if (lpmdd == null || lpmdd.size() == 0) {
					throw new Exception("请先配置厚度公差范围！");
				}
				
				// 获取虚拟物料信息
				List<PlnMaterielDetail> lpmdq=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, "object_no_vt = '"+plnmd.getObject_no_vt()+"' and nvl(invalid_flg,0) =0", null, 0, 1);
				if (Utils.isEmpty(lpmdq)) {
					throw new Exception("未找到虚拟物料["+plnmd.getObject_no_vt()+"]信息！");
				}
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(lpmdq.get(0).getObject_no());
				
				for (PbModelDb pmd : lpmdd) {
					if (pmd.getId().equals("200101")) {// 范围
						if (ypd.getThick().doubleValue()
								- MachineRestrict.lim_max_height > (Double
									.parseDouble(pmd.getRegionkey()))) {
							throw new Exception("母卷[" + ypd.getCoilno()
									+ "]的厚度超出纵剪机台["+cbm.get(0).getMachine_name()+"]最大公差设备限制范围内，不能编制计划！");
						}
					}

					if (pmd.getId().equals("200102")) {
						if (ypd.getThick().doubleValue()
								- MachineRestrict.lim_min_height < (Double
									.parseDouble(pmd.getRegionkey()))) {
							throw new Exception("母卷[" + ypd.getCoilno()
									+ "]的厚度小于纵剪机台["+cbm.get(0).getMachine_name()+"]最小公差设备限制范围内，不能编制计划！当前厚度偏差为：" + (ypd.getThick().doubleValue()
								- MachineRestrict.lim_min_height));
						}
					}
				}
			}
			
			// 已传入计划号
			if (plnmd.getLw_plan_no()!=null && !"".equals(plnmd.getLw_plan_no())) {
				plpl.setLw_plan_no(plnmd.getLw_plan_no());
				plpl.setPlan_seq(plnmd.getPlan_seq());
				List<PlnLengthwisePlan> lplp=this.getMapper(PlnLengthwisePlanMapper.class).find(plpl, 0, 1);
				if(lplp==null||lplp.size()==0){
					rm.setState("500");
					rm.setMsgInfo("分条计划["+plnmd.getLw_plan_no()+"]信息不存在!");
					return rm;
				}
				if(lplp.get(0).getStatus().trim().compareTo("0PLW01")>0){
					rm.setState("500");
					rm.setMsgInfo("分条计划["+plnmd.getLw_plan_no()+"]已下发，不能加入!");
					return rm;
				}
				// 判断虚拟物料信息
				ResultModel rmValid = doPlanJudgeByObject_no_vt(plnmd.getObject_no_vt());
				if(!"200".equals(rmValid.getState())){
					throw new Exception(rmValid.getMsgInfo());
				}
				plan_no = plnmd.getLw_plan_no();
				// 新增分条计划明细表记录
				doAddDetail(plnmd, userName, plnmd.getMachine_code(),oci.getMemo6());
			} else {
				// 判断虚拟物料信息
				ResultModel rmValid = doPlanJudgeByObject_no_vt(plnmd.getObject_no_vt());
				if(!"200".equals(rmValid.getState())){
					throw new Exception(rmValid.getMsgInfo());
				}
				if ("1".equals(oci.getMemo3())) {
					PlnLengthwisePlan pp = ppoo;
					plan_no = pp.getLw_plan_no();
					List<PlnLengthwisePlan> plnleng = this.getMapper(PlnLengthwisePlanMapper.class)
							.findWithCondition(null, "lw_plan_no ='"+plan_no+"'", "", 0, 1);
					if (plnleng == null || plnleng.size()==0) {
						pp.setPlan_seq(pp.getSerial_no());
						pp.setStatus("0PLW01");
						pp.setPline_code(plnmd.getPline_code());
						pp.setMachine_code(plnmd.getMachine_code());
						
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						Date date = sdf.parse(oci.getMemo1());
						pp.setStart_time(date);
						pp.setCreate_man_name(userName);
						pp.setCreate_time(new Date());
						this.getMapper(PlnLengthwisePlanMapper.class).insert(pp);
					}
					// 新增分条计划明细表记录
					PlnMaterielDetail plnmh = new PlnMaterielDetail();
					plnmh.setLw_plan_no(pp.getLw_plan_no());
					plnmh.setObject_no_vt(plnmd.getObject_no_vt());
					plnmh.setPline_code(plnmd.getPline_code());
					doAddDetail(plnmh, userName, plnmd.getMachine_code(),oci.getMemo6());
				} else {
					// 新增分条计划主记录
					PlnLengthwisePlan pp = getPlanNo();
					plan_no = pp.getLw_plan_no();
					pp.setPlan_seq(pp.getSerial_no());
					pp.setStatus("0PLW01");
					pp.setPline_code(plnmd.getPline_code());
					pp.setMachine_code(plnmd.getMachine_code());
					
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date date = sdf.parse(oci.getMemo1());
					pp.setStart_time(date);
					pp.setCreate_man_name(userName);
					pp.setCreate_time(new Date());
					this.getMapper(PlnLengthwisePlanMapper.class).insert(pp);
					
					// 新增分条计划明细表
					PlnMaterielDetail plnmh = new PlnMaterielDetail();
					plnmh.setLw_plan_no(plan_no);
					plnmh.setObject_no_vt(plnmd.getObject_no_vt());
					plnmh.setPline_code(plnmd.getPline_code());
					doAddDetail(plnmh, userName, plnmd.getMachine_code(),oci.getMemo6()); 
				}
			}

			// 修改其他数据
			PlnMaterielDetail pmdu=new PlnMaterielDetail();
			pmdu.setObject_no_vt(plnmd.getObject_no_vt());
			pmdu.setLw_plan_no(plan_no);
			doAddChildMethod(pmdu);
		}
		rm.setState("200");
		rm.setData(plan_no);
		return rm;
	}


	/**
	 * 分条计划取消
	 * 传入 分条计划号数组
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelPlanWeb(CommonPage<PlnLengthwisePlan> oci) throws Exception {
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<PlnLengthwisePlan> sLwPlanNo=oci.getObjectList();

		for(PlnLengthwisePlan pc:sLwPlanNo){
			//循环处理对应计划中 分条明细（母卷）相关数据
			PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
			plpd.setLw_plan_no(pc.getLw_plan_no());
			List<PlnLengthwisePlanDetail> lplpd=this.getMapper(PlnLengthwisePlanDetailMapper.class).find(plpd, 0, 0);
			rm = doCheckCancelPlanChild(lplpd);
			if(!"200".equals(rm.getState())){
				throw new Exception(rm.getMsgInfo());
			}
			for (PlnLengthwisePlanDetail ppd : lplpd) {
				MesOprLog mol = new MesOprLog("生产管理", "分条计划编制", "取消计划", userName, opr_time, ppd.getObject_no(), null, null, null, null);
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}
		}
		return rm;
	}

	/**
	 * 传入 分条计划号、虚拟母卷号
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCheckCancelPlanWeb(CommonPage<PlnLengthwisePlanDetail> oci) throws Exception {
		List<PlnLengthwisePlanDetail> lplpd=oci.getObjectList();
		ResultModel rm=doCheckCancelPlanChild(lplpd);
		return rm;
	}

	/**
	 * 选定物料移除计划
	 * @throws Exception 
	 * */
	public ResultModel doCheckCancelPlanChild(List<PlnLengthwisePlanDetail> lplpd) throws Exception{
		ResultModel rm=new ResultModel();

		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<PlnLengthwisePlanDetail> lp=new ArrayList<PlnLengthwisePlanDetail>();
		for(PlnLengthwisePlanDetail plpd:lplpd){
			PlnLengthwisePlanDetail pq=new PlnLengthwisePlanDetail();
			pq.setLw_plan_no(plpd.getLw_plan_no());
			pq.setObject_no_vt(plpd.getObject_no_vt());
			List<PlnLengthwisePlanDetail> lpq=this.getMapper(PlnLengthwisePlanDetailMapper.class).find(pq, 0, 1);
			if(lpq==null||lpq.size()==0){
				rm.setState("500");
				rm.setMsgInfo("虚拟母卷["+plpd.getObject_no_vt()+"]的分条计划["+plpd.getLw_plan_no()+"]不存在，无法删除！");
				return rm;
			}
			//状态STATUS>5BLW01, 如果成立，则报错退出
			if("5BLW01".compareTo(lpq.get(0).getStatus())<0){
				rm.setState("500");
				rm.setMsgInfo("母卷["+lpq.get(0).getObject_no_vt()+"]的分条计划已下发，无法删除！");
				return rm;
			}
			lp.add(lpq.get(0));
		}

		for(PlnLengthwisePlanDetail p:lp){
			//写虚拟物料履历，状态填:0PLWXX		母卷																			
			this.getBean(MesApiServiceImpl.class).InsertMatVtProc(p.getObject_no_vt(), "0PLWXX", userName, new Date());
			//子卷履历
			List<PlnMaterielDetail> listchild = this.getMapper(
					PlnMaterielDetailMapper.class).findWithCondition(null,
					" mat_object_no_vt = '" + p.getObject_no_vt() + "'", null, 0,0);
			if (Utils.isNotEmpty(listchild)) {
				for (PlnMaterielDetail pln : listchild) {
					// 写虚拟物料履历，状态填:0PCL01 子卷
					this.getBean(MesApiServiceImpl.class).InsertMatVtProc(
							pln.getObject_no_vt(), "0PLWXX", userName, new Date());
				}
			}

			//修改虚拟物料表 修改各母卷 的 分条计划号[LW_PLANNO]字段为空。																				
			PlnMaterielDetail pmdu=new PlnMaterielDetail();
			pmdu.setObject_no_vt(p.getObject_no_vt());
			pmdu.setLw_plan_no(null);
			pmdu.setStatus("0PDA10");
			this.getMapper(PlnMaterielDetailMapper.class).doUpdateLwPlanNo(pmdu);
			// 修改子卷分条计划号为空
			PlnMaterielDetail child =new PlnMaterielDetail();
			child.setLw_plan_no(null);
			child.setMat_object_no_vt(p.getObject_no_vt());
			child.setStatus("0PDA10");
			// child.setMachine_code("");
			this.getMapper(PlnMaterielDetailMapper.class).updateLwByMat_No(child);

			//删除分条计划明细相关母卷数据
			this.getMapper(PlnLengthwisePlanDetailMapper.class).doDelete(p);

			//======================================================================
			//20180417
			//			PlnMaterielDetail pmdud=new PlnMaterielDetail();
			//			pmdu.setObject_no_vt(p.getObject_no_vt());
			//			pmdu.setLw_plan_no(p.getLw_plan_no());
			//			PlnMaterielDetail pmddd=this.getMapper(PlnMaterielDetailMapper.class).find(pmdud, 0, 1).get(0);

			if(p.getObject_no()!=null){
				//调用生产计划模块物料跟踪撤销接口
				PrcMaterielProcess pmp=new PrcMaterielProcess();
				pmp.setObject_no(p.getObject_no());
				pmp.setPrc_code("5BLW01");//新增的状态
				pmp.setRemark("计划已编制撤销");
				//撤销实物物料状态跟踪函数:
				String tmp=this.getBean(MesApiServiceImpl.class).ARRAYLIST(pmp).getState();
				//				if(tmp=="-1"){
				//					throw new Exception("出现程序异常！撤销跟踪失败！");
				//				}else if(tmp=="-2"){
				//					throw new Exception("出现程序异常！撤销跟踪失败");
				//				}

			}
			//========================================================================	


			//根据虚拟母卷的【CREATE_DESIGN_NO】, 读取【pln_dsn_order_info】中的所有数据(DESIGN_NO= 母卷CREATE_DESIGN_NO)
			PlnMaterielDetail pmdc=new PlnMaterielDetail();
			pmdc.setObject_no_vt(p.getObject_no_vt());
			List<PlnMaterielDetail> lpmd = this.getMapper(PlnMaterielDetailMapper.class).find(pmdc, 0, 0);

			//准备临时变量:  One_Weight=0;   One_Quantity=0;
			double One_Weight=0;
			int One_Quantity=0;

			PlnDsnOrderInfo pdoi=new PlnDsnOrderInfo();
			pdoi.setDesign_no(lpmd.get(0).getCreate_design_no());
			List<PlnDsnOrderInfo> lpdoi=this.getMapper(PlnDsnOrderInfoMapper.class).find(pdoi, 0, 0);
			for(PlnDsnOrderInfo s2:lpdoi){
				//One_Weight+=S2.WEIGHT_IN_ONE;   One_Quantity+=S2.QUANTITY_IN_ONE;
				// 防止为null报错：20230801刘侣
				One_Weight+= (s2.getWeight_in_one() == null ? 0 : s2.getWeight_in_one());
				One_Quantity+=s2.getQuantity_in_one();
				//根据S2的 生产订单号，修改对应 生产订单进程表
				PlnProdorderStatistic pps=new PlnProdorderStatistic();
				pps.setProd_order_no(s2.getProd_order_no());
				pps.setLw_planed(s2.getWeight_in_one()==null?0:(-s2.getWeight_in_one()));
				pps.setLw_planed_cnt(s2.getQuantity_in_one()==null?0:(-s2.getQuantity_in_one()));
				this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);

				//根据S2的 订单号，修改  订单进程表[PLN_ORDER_STATISTIC]
				PlnOrderStatistic pos=new PlnOrderStatistic();
				pos.setOrder_no(s2.getOrder_no());
				pos.setLw_planed(s2.getWeight_in_one()==null?0:(-s2.getWeight_in_one()));
				pos.setLw_planed_cnt(s2.getQuantity_in_one()==null?0:(-s2.getQuantity_in_one()));
				this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);
			}

			//查找分条计划明细表【PLN_LENGTHWISE_PLAN_DETAIL】  where lw_plan_no=【母卷对应 分条计划号】的记录条数。  
			PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
			plpd.setLw_plan_no(p.getLw_plan_no());
			List<PlnLengthwisePlanDetail> lplpdq=this.getMapper(PlnLengthwisePlanDetailMapper.class).find(plpd, 0, 0);


			if(lplpdq==null||lplpdq.size()==0){//如果 记录数=0，
				//删除 分条计划进程表相关分条计划记录 [PLN_ORDER_STATISTIC]
				PlnLwPlanStatistic pps=new PlnLwPlanStatistic();
				pps.setLw_plan_no(p.getLw_plan_no());
				this.getMapper(PlnLwPlanStatisticMapper.class).doDelete(pps);

				//删除分条计划主表数据
				PlnLengthwisePlan pp=new PlnLengthwisePlan();
				pp.setLw_plan_no(p.getLw_plan_no());
				this.getMapper(PlnLengthwisePlanMapper.class).doDeleteLwPlanNo(pp);
			}else{
				//修改对应分条计划主表【PLN_LENGTHWISE_PLAN】
				PlnLengthwisePlan pp=new PlnLengthwisePlan();
				pp.setLw_plan_no(p.getLw_plan_no());
				pp.setMat_quantity(-1);
				pp.setMat_weight(lpmd.get(0).getSingle_weight()==null?null:(-lpmd.get(0).getSingle_weight()));
				this.getMapper(PlnLengthwisePlanMapper.class).doUpdatePlaned(pp);

				//修改分条计划号记录 [PLN_LW_PLAN_STATISTIC]，填写字段
				PlnLwPlanStatistic pps=new PlnLwPlanStatistic();
				pps.setMat_planed(lpmd.get(0).getSingle_weight()==null?0:(-lpmd.get(0).getSingle_weight()));
				pps.setMat_planed_cnt(-1);
				pps.setPlaned(-One_Weight);
				pps.setPlaned_cnt(-One_Quantity);
				pps.setLw_plan_no(p.getLw_plan_no());
				this.getMapper(PlnLwPlanStatisticMapper.class).doUpdatePlaned(pps);

				//调用【接口文档--公共函数SHEET--修改分条计划主表状态
				this.getBean(MesApiServiceImpl.class).doUpdatePlnLengthwisePlan(p.getLw_plan_no());

			}	
		}

		rm.setState("200");
		return rm;
	}
	
	
	
	/**
	 * 选定物料移除计划(质量自动脱单调用)
	 * @throws Exception 
	 * */
	public ResultModel doCancelPlanAuto(List<PlnLengthwisePlanDetail> lplpd,String userName) throws Exception{
		
		ResultModel rm=new ResultModel();
		List<PlnLengthwisePlanDetail> lp=new ArrayList<PlnLengthwisePlanDetail>();
		for(PlnLengthwisePlanDetail plpd:lplpd){
			PlnLengthwisePlanDetail pq=new PlnLengthwisePlanDetail();
			pq.setLw_plan_no(plpd.getLw_plan_no());
			pq.setObject_no_vt(plpd.getObject_no_vt());
			List<PlnLengthwisePlanDetail> lpq=this.getMapper(PlnLengthwisePlanDetailMapper.class).find(pq, 0, 1);
			if(lpq==null||lpq.size()==0){
				rm.setState("500");
				rm.setMsgInfo("虚拟母卷["+plpd.getObject_no_vt()+"]的分条计划["+plpd.getLw_plan_no()+"]不存在，无法删除！");
				return rm;
			}
			//状态STATUS>5BLW01, 如果成立，则报错退出
			if("5BLW01".compareTo(lpq.get(0).getStatus())<0){
				rm.setState("500");
				rm.setMsgInfo("母卷["+lpq.get(0).getObject_no_vt()+"]的分条计划已下发，无法删除！");
				return rm;
			}
			lp.add(lpq.get(0));
		}
		
		for(PlnLengthwisePlanDetail p:lp){
			//写虚拟物料履历，状态填:0PLWXX		母卷																			
			this.getService(MesApiService.class).InsertMatVtProc(p.getObject_no_vt(), "0PLWXX", userName, new Date());
			//子卷履历
			List<PlnMaterielDetail> listchild = this.getMapper(
					PlnMaterielDetailMapper.class).findWithCondition(null,
							" mat_object_no_vt = '" + p.getObject_no_vt() + "'", null, 0,0);
			if (Utils.isNotEmpty(listchild)) {
				for (PlnMaterielDetail pln : listchild) {
					// 写虚拟物料履历，状态填:0PCL01 子卷
					this.getService(MesApiService.class).InsertMatVtProc(
							pln.getObject_no_vt(), "0PLWXX", userName, new Date());
				}
			}
			
			//修改虚拟物料表 修改各母卷 的 分条计划号[LW_PLANNO]字段为空。																				
			PlnMaterielDetail pmdu=new PlnMaterielDetail();
			pmdu.setObject_no_vt(p.getObject_no_vt());
			pmdu.setLw_plan_no(null);
			pmdu.setStatus("0PDA10");
			this.getMapper(PlnMaterielDetailMapper.class).doUpdateLwPlanNo(pmdu);
			// 修改子卷分条计划号为空
			PlnMaterielDetail child =new PlnMaterielDetail();
			child.setLw_plan_no(null);
			child.setMat_object_no_vt(p.getObject_no_vt());
			child.setStatus("0PDA10");
			// child.setMachine_code("");
			this.getMapper(PlnMaterielDetailMapper.class).updateLwByMat_No(child);
			
			//删除分条计划明细相关母卷数据
			this.getMapper(PlnLengthwisePlanDetailMapper.class).doDelete(p);
			
			if(p.getObject_no()!=null){
				//调用生产计划模块物料跟踪撤销接口
				PrcMaterielProcess pmp=new PrcMaterielProcess();
				pmp.setObject_no(p.getObject_no());
				pmp.setPrc_code("5BLW01");//新增的状态
				pmp.setRemark("计划已编制撤销");
				//撤销实物物料状态跟踪函数:
				String tmp=this.getService(MesApiService.class).ARRAYLIST(pmp).getState();
			}
			
			//根据虚拟母卷的【CREATE_DESIGN_NO】, 读取【pln_dsn_order_info】中的所有数据(DESIGN_NO= 母卷CREATE_DESIGN_NO)
			PlnMaterielDetail pmdc=new PlnMaterielDetail();
			pmdc.setObject_no_vt(p.getObject_no_vt());
			List<PlnMaterielDetail> lpmd = this.getMapper(PlnMaterielDetailMapper.class).find(pmdc, 0, 0);
			
			//准备临时变量:  One_Weight=0;   One_Quantity=0;
			double One_Weight=0;
			int One_Quantity=0;
			PlnDsnOrderInfo pdoi=new PlnDsnOrderInfo();
			pdoi.setDesign_no(lpmd.get(0).getCreate_design_no());
			List<PlnDsnOrderInfo> lpdoi=this.getMapper(PlnDsnOrderInfoMapper.class).find(pdoi, 0, 0);
			for(PlnDsnOrderInfo s2:lpdoi){
				//One_Weight+=S2.WEIGHT_IN_ONE;   One_Quantity+=S2.QUANTITY_IN_ONE;
				One_Weight+=s2.getWeight_in_one();
				One_Quantity+=s2.getQuantity_in_one();
				//根据S2的 生产订单号，修改对应 生产订单进程表
				PlnProdorderStatistic pps=new PlnProdorderStatistic();
				pps.setProd_order_no(s2.getProd_order_no());
				pps.setLw_planed(s2.getWeight_in_one()==null?0:(-s2.getWeight_in_one()));
				pps.setLw_planed_cnt(s2.getQuantity_in_one()==null?0:(-s2.getQuantity_in_one()));
				this.getMapper(PlnProdorderStatisticMapper.class).doUpdatePlaned(pps);
				
				//根据S2的 订单号，修改  订单进程表[PLN_ORDER_STATISTIC]
				PlnOrderStatistic pos=new PlnOrderStatistic();
				pos.setOrder_no(s2.getOrder_no());
				pos.setLw_planed(s2.getWeight_in_one()==null?0:(-s2.getWeight_in_one()));
				pos.setLw_planed_cnt(s2.getQuantity_in_one()==null?0:(-s2.getQuantity_in_one()));
				this.getMapper(PlnOrderStatisticMapper.class).doUpdatePlaned(pos);
			}
			
			//查找分条计划明细表【PLN_LENGTHWISE_PLAN_DETAIL】  where lw_plan_no=【母卷对应 分条计划号】的记录条数。  
			PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
			plpd.setLw_plan_no(p.getLw_plan_no());
			List<PlnLengthwisePlanDetail> lplpdq=this.getMapper(PlnLengthwisePlanDetailMapper.class).find(plpd, 0, 0);
			
			
			if(lplpdq==null||lplpdq.size()==0){//如果 记录数=0，
				//删除 分条计划进程表相关分条计划记录 [PLN_ORDER_STATISTIC]
				PlnLwPlanStatistic pps=new PlnLwPlanStatistic();
				pps.setLw_plan_no(p.getLw_plan_no());
				this.getMapper(PlnLwPlanStatisticMapper.class).doDelete(pps);
				
				//删除分条计划主表数据
				PlnLengthwisePlan pp=new PlnLengthwisePlan();
				pp.setLw_plan_no(p.getLw_plan_no());
				this.getMapper(PlnLengthwisePlanMapper.class).doDeleteLwPlanNo(pp);
			}else{
				//修改对应分条计划主表【PLN_LENGTHWISE_PLAN】
				PlnLengthwisePlan pp=new PlnLengthwisePlan();
				pp.setLw_plan_no(p.getLw_plan_no());
				pp.setMat_quantity(-1);
				pp.setMat_weight(lpmd.get(0).getSingle_weight()==null?null:(-lpmd.get(0).getSingle_weight()));
				this.getMapper(PlnLengthwisePlanMapper.class).doUpdatePlaned(pp);
				
				//修改分条计划号记录 [PLN_LW_PLAN_STATISTIC]，填写字段
				PlnLwPlanStatistic pps=new PlnLwPlanStatistic();
				pps.setMat_planed(lpmd.get(0).getSingle_weight()==null?0:(-lpmd.get(0).getSingle_weight()));
				pps.setMat_planed_cnt(-1);
				pps.setPlaned(-One_Weight);
				pps.setPlaned_cnt(-One_Quantity);
				pps.setLw_plan_no(p.getLw_plan_no());
				this.getMapper(PlnLwPlanStatisticMapper.class).doUpdatePlaned(pps);
				
				//调用【接口文档--公共函数SHEET--修改分条计划主表状态
				this.getService(MesApiService.class).doUpdatePlnLengthwisePlan(p.getLw_plan_no());
				
			}	
		}
		rm.setState("200");
		return rm;
	}


	/**
	 * 分条计划下发 
	 * objectList
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSendPlanWeb(CommonPage<PlnLengthwisePlan> oci) throws Exception {
		ResultModel rm=new ResultModel();
		List<PlnLengthwisePlan> lplp=oci.getObjectList();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		//去重操作
		List<PlnLengthwisePlan> lplpC=new ArrayList<PlnLengthwisePlan>();
		for(PlnLengthwisePlan plp:lplp){
			if(lplpC.size()==0){
				lplpC.add(plp);
			}else{
				boolean flag=true;
				for(PlnLengthwisePlan plpc:lplpC){
					if(plpc.getLw_plan_no().equals(plp.getLw_plan_no())){
						flag=false;
						break;
					}
				}
				//未重复
				if(flag){
					lplpC.add(plp);
				}
			}
		}


		for(PlnLengthwisePlan pc:lplpC){
			
			// 判断物料是否在库
		    this.getBean(MesApiDesignInfoImpl.class).JudgeIsOrNotZk(pc.getObject_no());
						
			PlnLengthwisePlan pp=new PlnLengthwisePlan();
			pp.setLw_plan_no(pc.getLw_plan_no());
			List<PlnLengthwisePlan> lp=this.getMapper(PlnLengthwisePlanMapper.class).find(pp, 0, 0);
			if(lp==null||lp.size()==0){
				rm.setState("500");
				rm.setMsgInfo("分条计划["+pc.getLw_plan_no()+"]信息不存在!");
				return rm;
			}
			if(!"0PLW01".equals(lp.get(0).getStatus())){
				rm.setState("500");
				rm.setMsgInfo("分条计划["+pc.getLw_plan_no()+"]已下发，不能重复下发!");
				return rm;
			}
			// 实际上包含了母卷跟子卷
			PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
			plpd.setLw_plan_no(pc.getLw_plan_no());
			pc.setChild(this.getMapper(PlnLengthwisePlanDetailMapper.class).find(plpd, 0, 0));
		}

		for(PlnLengthwisePlan pc:lplpC){
			// 修改分条计划表： 相关计划的状态给为：0PLW02																					
			pc.setStatus("0PLW02");
			this.getMapper(PlnLengthwisePlanMapper.class).doUpdate(pc);

			// 修改分条计划明细表：计划内的的各母卷分别修改状态为：0PLW02																					
			for(PlnLengthwisePlanDetail pcc:pc.getChild()){
				pcc.setStatus("5BLW02");
				// 修改分条计划明细表：计划内的的各母卷分别修改状态为：5BLW02	
				// 增加下发时间下发人
				pcc.setSender(userName);
				pcc.setSend_date(new Date());
				this.getMapper(PlnLengthwisePlanDetailMapper.class).doUpdateStatus(pcc);
				
				// 修改虚拟物料信息状态
				PlnMaterielDetail pmd = new PlnMaterielDetail();
				pmd.setLw_plan_no(pcc.getLw_plan_no());
				pmd.setObject_no_vt(pcc.getObject_no_vt());
				List<PlnMaterielDetail> pmddd = this.getMapper(PlnMaterielDetailMapper.class).find(pmd, 0, 1);
				
				List<PlnProdorder> ppoL = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, " PROD_ORDER_NO='"+pmddd.get(0).getProd_order_no()+"'", null, 0, 0);
				if (ppoL == null || ppoL.size() <= 0) {
					throw new Exception("生产订单：" + ppoL.get(0).getOrder_no() + " 不存在");
				}
				// 验证生产订单状态是否为订单保留：
				if ("0PAA60".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]为 ‘订单保留’ 状态，不允许下发");
				}
				if ("0PAA70".equals(ppoL.get(0).getStatus())) {
					throw new Exception("生产订单["+ppoL.get(0).getProd_order_no()+"]为 ‘订单作废’ 状态，不允许下发");
				}
				
				// 验证生产订单是否锁定
				boolean flag_l = this.getBean(MesApiDesignInfoImpl.class).pOrdIsLocked(pmddd.get(0).getProd_order_no());
				if (flag_l) {
					throw new Exception("生产订单已经锁定[订单变更中],不允许下发计划到车间!");
				}
				
				pmd.setStatus("0PLW02");
				this.getMapper(PlnMaterielDetailMapper.class).doUpdateLwPlanNo(pmd);
				// 修改虚拟子卷
				PlnMaterielDetail child =new PlnMaterielDetail();
				child.setLw_plan_no(pcc.getLw_plan_no());
				child.setMat_object_no_vt(pcc.getObject_no_vt());
				child.setStatus("0PLW02");
				this.getMapper(PlnMaterielDetailMapper.class).updateLwByMat_No(child);
				
				//写虚拟物料履历，状态填:0PLW02		母卷跟子卷信息																			
				this.getBean(MesApiServiceImpl.class).InsertMatVtProc(pcc.getObject_no_vt(), "0PLW02", userName, new Date());
				
				//2018-05-05新增实物跟踪 //调用生产计划模块物料跟踪接口 
				PrcMaterielProcess pmp=new PrcMaterielProcess();
				pmp.setPrc_code("5BLW02");//新增的状态
				pmp.setCreate_time(new Date());//来源.
				pmp.setObject_no(pcc.getObject_no());
				pmp.setCreate_man_name(userName);
				//pmp.setRemark(mcsm.getMemo());//来源？
				//新增物料跟踪
				int tmp= this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
//				if(tmp==-1){
//					throw new Exception("物料跟踪失败");
//				}
				
				
			}
		}

		rm.setState("200");
		return rm;
	}

	/**
	 * 分条计划取消下发
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSendPlanCancelWeb(CommonPage<PlnLengthwisePlan> oci) throws Exception {
		ResultModel rm=new ResultModel();

		List<PlnLengthwisePlan> lplp=oci.getObjectList();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);

		for(PlnLengthwisePlan pc:lplp){
			PlnLengthwisePlan pp=new PlnLengthwisePlan();
			pp.setLw_plan_no(pc.getLw_plan_no());
			List<PlnLengthwisePlan> lp=this.getMapper(PlnLengthwisePlanMapper.class).find(pp, 0, 0);
			if(lp==null||lp.size()==0){
				rm.setState("500");
				rm.setMsgInfo("分条计划["+pc.getLw_plan_no()+"]信息不存在!");
				return rm;
			}
			if("0PLW01".equals(lp.get(0).getStatus())){
				rm.setState("500");
				rm.setMsgInfo("分条计划["+pc.getLw_plan_no()+"]尚未下发，不能取消!");
				return rm;
			}
			
			// 详表 使用实物状态
			// 5BLW01 分条计划已编制
			// 5BLW02 分条计划已下发
			// 5BLW03 开始分条作业
			// 5BLW09 分条剪废
			// 5BLW10 分条作业完成
			// 5BLW33 等待分条判定
			// 5BLW40 分条判定完成
			// 0PLWXX 分条计划已失效
			PlnLengthwisePlanDetail plpt = new PlnLengthwisePlanDetail();
			plpt.setLw_plan_no(pc.getLw_plan_no());
			List<PlnLengthwisePlanDetail> plnpd = this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(plpt, "status <> '0PLWXX'", null, 0, 0);
			if (plnpd != null && plnpd.size()>0) {
				for (PlnLengthwisePlanDetail plnLe : plnpd) {
					if (!"5BLW02".equals(plnLe.getStatus())) {
						rm.setState("500");
						rm.setMsgInfo("分条计划["+pc.getLw_plan_no()+"]内的某些母卷已开始作业,不能取消!");
						return rm;
					}
				}
			}
			
			//实际上包含了母卷跟子卷
			PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
			plpd.setLw_plan_no(pc.getLw_plan_no());
			pc.setChild(this.getMapper(PlnLengthwisePlanDetailMapper.class).find(plpd, 0, 0));
		}


		for(PlnLengthwisePlan pc:lplp){
			//修改分条计划表： 相关计划的状态给为：0PLW01																					
			pc.setStatus("0PLW01");
			this.getMapper(PlnLengthwisePlanMapper.class).doUpdate(pc);

			//修改分条计划明细表：计划内的的各母卷分别修改状态为：5BLW01																					
			for(PlnLengthwisePlanDetail pcc:pc.getChild()){
				pcc.setStatus("5BLW01");
				//修改分条计划明细表：计划内的的各母卷分别修改状态为：5BLW01	
				//清空下发时间下发人
				pcc.setSender(null);
				pcc.setSend_date(null);
				this.getMapper(PlnLengthwisePlanDetailMapper.class).doUpdateStatus(pcc);

				// 修改虚拟物料信息状态
				PlnMaterielDetail pmd = new PlnMaterielDetail();
				pmd.setLw_plan_no(pcc.getLw_plan_no());
				pmd.setObject_no_vt(pcc.getObject_no_vt());
				pmd.setStatus("0PLW01");
				this.getMapper(PlnMaterielDetailMapper.class).doUpdateLwPlanNo(pmd);
				// 修改虚拟子卷
				PlnMaterielDetail child =new PlnMaterielDetail();
				child.setLw_plan_no(pcc.getLw_plan_no());
				child.setMat_object_no_vt(pcc.getObject_no_vt());
				child.setStatus("0PLW01");
				this.getMapper(PlnMaterielDetailMapper.class).updateLwByMat_No(child);

				//写虚拟物料履历，状态填:0PLW01		母卷跟子卷信息																			
				this.getBean(MesApiServiceImpl.class).InsertMatVtProc(pcc.getObject_no_vt(), "0PLW01", userName, new Date());
				
				// 撤销实物进程跟踪调用生产计划模块物料跟踪撤销接口
				PrcMaterielProcess pmp=new PrcMaterielProcess();
				pmp.setObject_no(pcc.getObject_no());
				pmp.setPrc_code("5BLW02");//新增的状态
				pmp.setRemark("计划取消下发");
				pmp.setKeep_sametime_status(0);
				//撤销实物物料状态跟踪函数:
				String tmp=this.getBean(MesApiServiceImpl.class).ARRAYLIST(pmp).getState();
			}
		}

		rm.setState("200");
		return rm;
	}

	
	/**
	 * 报表导出
	 * */
	public ResultModel doExportCompletePlanWeb(CommonPage<PlnLengthwiseDsnMain> sum){
		ResultModel rm=new ResultModel();
		try{
			// 1，创建一个webbook，对应一个Excel文件
			WritableWorkbook workbook;
			//2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator;  //临时保存路径
			File dir = new File(path);
			if(!dir.exists()) {
				new File(path).mkdir();
			}
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat stdSdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String sTime=sum.getStartTime();
			if(sTime!=null&&sTime.length()>1){
				Date sDate=sdf.parse(sTime);
				sTime=sdf.format(sDate);
			}
			String eTime=sum.getEndTime();
			if(eTime!=null&&eTime.length()>1){
				Date eDate=sdf.parse(eTime);
				eTime=sdf.format(eDate);
			}
			String filename = sTime +"至"+ eTime +  "已编制分条计划报表";
			String file=filename+".xls";  //文件名
			//3. 操作EXCEL文件
			workbook = Workbook.createWorkbook(new File(path+file));
			WritableSheet sheet = workbook.createSheet(filename, 1);
			//行高
			sheet.getSettings().setDefaultRowHeight(300);
			//列宽
			sheet.setColumnView(0,5);
			sheet.setColumnView(1,18);
			sheet.setColumnView(2,22);
			sheet.setColumnView(3,30);
			sheet.setColumnView(4,18);
			sheet.setColumnView(5,15);		//状态
			sheet.setColumnView(6,20);		//虚拟母卷号
			sheet.setColumnView(7,15);		//实物卷号
			sheet.setColumnView(8,18);
			sheet.setColumnView(9,20);
			sheet.setColumnView(10,10);		//销售备注
			sheet.setColumnView(11,10);
			sheet.setColumnView(12,10);		//产线
			sheet.setColumnView(13,10);		//机台
			sheet.setColumnView(20,15);		//分条规格
			sheet.setColumnView(23,15);		//最早交货日期
			sheet.setColumnView(24,15);		//最晚交货日期
			sheet.setColumnView(26,20);		//创建时间
			sheet.setColumnView(27,20);		//生产时间			
			//字体  参数可自行配置
			WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
			WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
			cellFormat1.setAlignment(Alignment.CENTRE);
			cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
			//表头
			sheet.mergeCells(0, 0, 0, 1);
			sheet.addCell(new Label(0,0,"序号",cellFormat1));
			sheet.mergeCells(1, 0, 1, 1);
			sheet.addCell(new Label(1,0,"合同号",cellFormat1));
			sheet.mergeCells(2, 0, 2, 1);
			sheet.addCell(new Label(2,0,"订单号",cellFormat1));
			sheet.mergeCells(3, 0, 3, 1);
			sheet.addCell(new Label(3,0,"客户名称",cellFormat1));
			sheet.mergeCells(4, 0, 4, 1);
			sheet.addCell(new Label(4,0,"分条计划号",cellFormat1));
			sheet.mergeCells(5, 0, 5, 1);
			sheet.addCell(new Label(5,0,"状态",cellFormat1));
			sheet.mergeCells(6, 0, 6, 1);
			sheet.addCell(new Label(6,0,"虚拟母卷号(母卷)",cellFormat1));
			sheet.mergeCells(7, 0, 7, 1);
			sheet.addCell(new Label(7,0,"实物卷号",cellFormat1));
			sheet.mergeCells(8, 0, 8, 1);
			sheet.addCell(new Label(8,0,"原料卷号",cellFormat1));
			sheet.mergeCells(9, 0, 9, 1);
			sheet.addCell(new Label(9,0,"销售备注",cellFormat1));
			sheet.mergeCells(10, 0, 10, 1);
			sheet.addCell(new Label(10,0,"加工计划备注",cellFormat1));
			sheet.mergeCells(11, 0, 11, 1);
			sheet.addCell(new Label(11,0,"产线",cellFormat1));
			sheet.mergeCells(12, 0, 12, 1);
			sheet.addCell(new Label(12,0,"机台",cellFormat1));
			sheet.mergeCells(13, 0, 13, 1);
			sheet.addCell(new Label(13,0,"牌号",cellFormat1));
			sheet.mergeCells(14, 0, 14, 1);
			sheet.addCell(new Label(14,0,"重量",cellFormat1));
			sheet.mergeCells(15, 0, 18, 0);
			sheet.addCell(new Label(15,0,"母卷规格",cellFormat1));
			sheet.addCell(new Label(15,1,"厚度",cellFormat1));
			sheet.addCell(new Label(16,1,"宽度",cellFormat1));
			sheet.addCell(new Label(17,1,"内径",cellFormat1));
			sheet.addCell(new Label(18,1,"外径",cellFormat1));
			sheet.mergeCells(19, 0, 19, 1);
			sheet.addCell(new Label(19,0,"分条数",cellFormat1));
			sheet.mergeCells(20, 0, 20, 1);
			sheet.addCell(new Label(20,0,"分条规格",cellFormat1));
			sheet.mergeCells(21, 0, 21, 1);
			sheet.addCell(new Label(21,0,"切边方式",cellFormat1));
			sheet.mergeCells(22, 0, 22, 1);
			sheet.addCell(new Label(22,0,"横切方式",cellFormat1));
			sheet.mergeCells(23, 0, 23, 1);
			sheet.addCell(new Label(23,0,"最早交货日期",cellFormat1));
			sheet.mergeCells(24, 0, 24, 1);
			sheet.addCell(new Label(24,0,"最晚交货日期",cellFormat1));
			sheet.mergeCells(25, 0, 25, 1);
			sheet.addCell(new Label(25,0,"创建人",cellFormat1));
			sheet.mergeCells(26, 0, 26, 1);
			sheet.addCell(new Label(26,0,"创建时间",cellFormat1));
			sheet.mergeCells(27, 0, 27, 1);
			sheet.addCell(new Label(27,0,"生产时间",cellFormat1));

			WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
			WritableCellFormat cellFormat = new WritableCellFormat(font); 
			cellFormat.setAlignment(Alignment.CENTRE);
			cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);

			//获取查询结果
			rm=doQueryCompletePlanWeb(sum);
			if("500".equals(rm.getState())) return rm;
			List<PlnLengthwiseDsnMainSum> list=(List<PlnLengthwiseDsnMainSum>) rm.getData();
			Double total_weight=0d;
			for(int v=0;v<list.size();v++){
				PlnLengthwiseDsnMainSum main=list.get(v);
				sheet.addCell(new Label(0,v+2,""+(v+1),cellFormat));
				if(main.getContract_no() != null ) {
					sheet.addCell(new Label(1,v+2,main.getContract_no(),cellFormat));
				}
				if(main.getOrder_no() != null) {
					sheet.addCell(new Label(2,v+2,main.getOrder_no(),cellFormat));
				}
				if(main.getCustomer_name() != null) {
					sheet.addCell(new Label(3,v+2,main.getCustomer_name(),cellFormat));
				}
				if(main.getLw_plan_no() != null) {
					sheet.addCell(new Label(4,v+2,main.getLw_plan_no(),cellFormat));
				}
				String status_content="";
				if("5BLW10".equals(main.getStatus())) status_content="分条作业完成";
				if("5BLW01".equals(main.getStatus())) status_content="计划已编制";
				if("5BLW02".equals(main.getStatus())) status_content="计划已下发";
				if("5BLW03".equals(main.getStatus())) status_content="开始分条作业";
				sheet.addCell(new Label(5,v+2,status_content,cellFormat));
				if(main.getObject_no_vt() != null ) {
					sheet.addCell(new Label(6,v+2,main.getObject_no_vt(),cellFormat));
				}
				if(main.getObject_no() != null ) {
					sheet.addCell(new Label(7,v+2,main.getObject_no(),cellFormat));
				}
				if(main.getMaterailcoilno() != null ) {
					sheet.addCell(new Label(8,v+2,main.getMaterailcoilno(),cellFormat));
				}
				if(main.getOrder_memo() != null) {
					sheet.addCell(new Label(9,v+2,main.getOrder_memo(),cellFormat));
				}
				if(main.getProcessMemo() != null ) {
					sheet.addCell(new Label(10,v+2,main.getProcessMemo(),cellFormat));
				}
				if(main.getPline_name() != null ) {
					sheet.addCell(new Label(11,v+2,main.getPline_name(),cellFormat));
				}
				if(main.getMachine_name() != null ) {
					sheet.addCell(new Label(12,v+2,main.getMachine_name(),cellFormat));
				}
				if(main.getSteel_name() != null ) {
					sheet.addCell(new Label(13,v+2,main.getSteel_name(),cellFormat));
				}
				if(main.getSingle_weight() != null ) {
					sheet.addCell(new Label(14,v+2,main.getSingle_weight(),cellFormat));
					double weight=Double.parseDouble(main.getSingle_weight());
					total_weight+=weight;
				}
				if(main.getThick() != null ) {
					sheet.addCell(new Label(15,v+2,main.getThick(),cellFormat));
				}
				if(main.getWidth() != null ) {
					sheet.addCell(new Label(16,v+2,main.getWidth(),cellFormat));
				}
				if(main.getDiameter_inn() != null) {
					sheet.addCell(new Label(17,v+2,main.getDiameter_inn(),cellFormat));
				}
				if(main.getDiameter_out() != null) {
					sheet.addCell(new Label(18,v+2,main.getDiameter_out(),cellFormat));
				}
				if(main.getSub_count() != null) {
					sheet.addCell(new Label(19,v+2,main.getSub_count(),cellFormat));
				}
				if(main.getCut_style() != null) {
					sheet.addCell(new Label(20,v+2,main.getCut_style(),cellFormat));
				}
				String content="";
				if("102501".equals(main.getCut_edge_type_no())) content="四毛";
				if("102502".equals(main.getCut_edge_type_no())) content="二切";
				if("102503".equals(main.getCut_edge_type_no())) content="四切";
				sheet.addCell(new Label(21,v+2,content,cellFormat));

				if(main.getCrosscut_style()==null) main.setCrosscut_style("不横切");
				sheet.addCell(new Label(22,v+2,main.getCrosscut_style(),cellFormat));
				if(main.getDeliver_date_earliest() != null) {
					sheet.addCell(new Label(23,v+2,main.getDeliver_date_earliest(),cellFormat));
				}
				if(main.getDeliver_date_latest() != null) {
					sheet.addCell(new Label(24,v+2,main.getDeliver_date_latest(),cellFormat));
				}
				if(main.getCreate_man_name() != null ) {
					sheet.addCell(new Label(25,v+2,main.getCreate_man_name(),cellFormat));
				}
				if(main.getCreate_time() != null ) {
					Date createDate=stdSdf.parse(main.getCreate_time());
					String create_time=stdSdf.format(createDate);
					sheet.addCell(new Label(26,v+2,create_time,cellFormat));
				}
				if(main.getFeeding_time() != null ) {
					Date feedingDate=stdSdf.parse(main.getFeeding_time());
					String feeding_time=stdSdf.format(feedingDate);
					sheet.addCell(new Label(27,v+2,feeding_time,cellFormat));
				}
			}
			sheet.addCell(new Label(0,list.size()+2,"合计",cellFormat1));

			sheet.addCell(new Label(14,list.size()+2,String.valueOf(total_weight),cellFormat));
			sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
			sheet.getSettings().setVerticalFreeze(2);
			
			//关闭
			workbook.write();
			workbook.close();

			rm.setData("/download?filename="+file);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * @return 计划号和序列号
	 */
	public  PlnLengthwisePlan getPlanNo(){
		
		String Dt=new SimpleDateFormat("yyMMdd").format(new Date());
		//分条计划表： 分条计划号(LW+15位流水); 其他字段参考																					
		PlnLengthwisePlan pp=new PlnLengthwisePlan();
		//倒叙找到最后一条数据
		List<PlnLengthwisePlan> lpp=this.getMapper(PlnLengthwisePlanMapper.class).findWithCondition(null, "", " serial_no desc ", 0, 1);
		if(lpp==null||lpp.size()==0){
			pp.setSerial_no(1l);
			pp.setLw_plan_no("LW"+Dt+String.format("%03d", 1));//lw180531001
		}else{
			pp.setSerial_no(lpp.get(0).getSerial_no()+1);
			if(Dt.equals(lpp.get(0).getLw_plan_no().substring(2,8))){
				pp.setLw_plan_no("LW"+Dt+String.format("%03d", Integer.parseInt(lpp.get(0).getLw_plan_no().substring(8,lpp.get(0).getLw_plan_no().length()))+1 ));
			}else{
				pp.setLw_plan_no("LW"+Dt+String.format("%03d", 1));
			}
		}
		return pp;
	}
	
	
	/**
	 * 分条计划明细表：对选中的母卷增加明细记录
	 * 修改虚拟物料信息  写虚拟履历
	 * @param plnmd 虚拟物料号、计划号
	 * @param userName
	 */
	public void doAddDetail(PlnMaterielDetail plnmd, String userName,String memo2,String memo6){
		
		PlnLengthwisePlan plpl = new PlnLengthwisePlan();
		plpl.setLw_plan_no(plnmd.getLw_plan_no());
		List<PlnLengthwisePlan> lplp=this.getMapper(PlnLengthwisePlanMapper.class).find(plpl, 0, 1);
		
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(plnmd.getObject_no_vt());
		List<PlnMaterielDetail> lpmdq=this.getMapper(PlnMaterielDetailMapper.class).find(pmd, 0, 0);
		pmd = lpmdq.get(0);
		List<PlnLengthwisePlanDetail> lppd=this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(null, "", " serial_no desc ", 0, 1);
		long sNo=0;
		if(lppd==null||lppd.size()==0){
			sNo=1;
		}else{
			sNo=lppd.get(0).getSerial_no()+1;
		}
		int isqe=0;
		
		PlnLengthwisePlanDetail plpdq=new PlnLengthwisePlanDetail();
		plpdq.setLw_plan_no(plnmd.getLw_plan_no());
		lppd=this.getMapper(PlnLengthwisePlanDetailMapper.class).findWithCondition(plpdq, "", " lw_seq desc ", 0, 1);
		if(lppd==null||lppd.size()==0){
			isqe=1;
		}else{
			isqe=lppd.get(0).getLw_seq()+1;
		}

			PlnLengthwisePlanDetail plpd=new PlnLengthwisePlanDetail();
			plpd.setSerial_no(sNo++);
			plpd.setLw_plan_no(plnmd.getLw_plan_no());
			plpd.setLw_seq(isqe++);
			plpd.setObject_no_vt(pmd.getObject_no_vt());
			plpd.setLw_design_no(pmd.getLw_design_no());
			plpd.setStatus("5BLW01");
			plpd.setObject_no(pmd.getObject_no());
			plpd.setPline_code(plnmd.getPline_code());// 产线--大小纵剪
			plpd.setMachine_code(memo2); // 机台编码--大小纵剪
			plpd.setSteel_code(pmd.getSteel_code());
			plpd.setMat_width(pmd.getWidth());
			plpd.setMat_thick(pmd.getThick());
			plpd.setMat_diameter_inn(pmd.getDiameter_inn());
			plpd.setMat_diameter_out(pmd.getDiameter_out());
			plpd.setMat_length(pmd.getLength());
			plpd.setMat_single_weight(pmd.getSingle_weight());
			plpd.setPlan_opt_time(lplp.get(0).getStart_time());
			plpd.setCreate_man_name(userName);
			plpd.setCreate_time(new Date());

			PlnLengthwiseDsnMain pldm=new PlnLengthwiseDsnMain();
			pldm.setLw_design_no(pmd.getLw_design_no());
			List<PlnLengthwiseDsnMain> lpldm=this.getMapper(PlnLengthwiseDsnMainMapper.class).find(pldm, 0, 1);
			plpd.setRate(lpldm.get(0).getProd_rate());
			plpd.setSub_count(lpldm.get(0).getSub_count().intValue()*Integer.parseInt(lpldm.get(0).getCrosscut_style()));
			plpd.setPlan_hand_time(memo6);
			this.getMapper(PlnLengthwisePlanDetailMapper.class).insert(plpd);

			//虚拟物料表：修改母卷的 分条计划号[LW_PLANNO]字段以及状态
			PlnMaterielDetail pmdu=new PlnMaterielDetail();
			pmdu.setLw_plan_no(plnmd.getLw_plan_no());
			pmdu.setSerial_no(pmd.getSerial_no());
			pmdu.setMachine_code(memo2);
			pmdu.setStatus("0PLW01");
			this.getMapper(PlnMaterielDetailMapper.class).update(pmdu);
			
			// 虚拟物料表 : 修改子卷的分条计划号[LW_PLANNO]字段状态
			PlnMaterielDetail child=new PlnMaterielDetail();
			child.setLw_plan_no(plnmd.getLw_plan_no());
			child.setMat_object_no_vt(pmd.getObject_no_vt());
			child.setStatus("0PLW01");
			// child.setMachine_code(memo2);
			this.getMapper(PlnMaterielDetailMapper.class).updateLwByMat_No(child);
			
			//写虚拟物料履历，状态填:0PLW01 母卷																			
			this.getBean(MesApiServiceImpl.class).InsertMatVtProc(pmd.getObject_no_vt(), "0PLW01", userName, new Date());
			// 查询子卷
			List<PlnMaterielDetail> listchild=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, " mat_object_no_vt = '"+pmd.getObject_no_vt()+"'", null, 0, 0);
			if (Utils.isNotEmpty(listchild)) {
				for (PlnMaterielDetail pln : listchild) {
					//写虚拟物料履历，状态填:0PLW01 子卷																			
					this.getBean(MesApiServiceImpl.class).InsertMatVtProc(pln.getObject_no_vt(), "0PLW01", userName, new Date());
				}
			}
	}
	
	/**
	 * 编制计划 判断虚拟物料号
	 * @param Object_no_vt
	 * @return
	 */
	public ResultModel doPlanJudgeByObject_no_vt(String Object_no_vt){
		ResultModel rm = new ResultModel();
		//查询虚拟卷
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(Object_no_vt);
		List<PlnMaterielDetail> lpmdq=this.getMapper(PlnMaterielDetailMapper.class).find(pmd, 0, 0);

		if(lpmdq==null||lpmdq.size()==0){
			rm.setState("500");
			rm.setMsgInfo("虚拟物料["+Object_no_vt+"]信息不存在!");
			return rm;
		}
		//实际上只有一条
		for(PlnMaterielDetail pmdq:lpmdq){
			if(!"".equals(pmdq.getLw_plan_no())&&pmdq.getLw_plan_no()!=null){
				rm.setState("500");
				rm.setMsgInfo("虚拟物料["+Object_no_vt+"]已经在计划["+pmdq.getLw_plan_no()+"]内，无法再次编制！");
				return rm;
			}

			PlnLengthwisePlanDetail ppd=new PlnLengthwisePlanDetail();
			ppd.setObject_no_vt(pmdq.getObject_no_vt());
			int icount=this.getMapper(PlnLengthwisePlanDetailMapper.class).countWithCondition(ppd," STATUS != '0PLWXX' ");
			if(icount>0){
				rm.setState("500");
				rm.setMsgInfo("虚拟物料["+Object_no_vt+"]已经在计划["+pmdq.getLw_plan_no()+"]内，无法再次编制！");
				return rm;
			}
			//若虚拟物料表的 (OPT_TIMES >=1 AND NEED_EXTOPT =0) ,则报错退出
			if(pmdq.getOpt_times()!=null&&pmdq.getOpt_times()>=1
					&&"1".equals(pmdq.getNeed_extopt())){
				rm.setState("500");
				rm.setMsgInfo("虚拟物料["+Object_no_vt+"]已经生产完毕，不能编制计划！");
				return rm;
			}
		}
		rm.setState("200");
		return rm;
	}
}

