/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2017.10.24
 * 描述               :        			客户订单信息
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/
package market.Slm.OrderManagement.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import market.Api.Mes.impl.MesApiDesignInfoImpl;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseStationMapper;
import market.Com.mapper.PbModelDbMapper;
import market.Com.pb.DoubleUtil;
import market.Com.pb.PbMethod;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.ComBaseStation;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Mes.OrderManager.Plan.impl.PlnProdorderStatisticServiceImpl;
import market.Pms.Util.ImportUtil;
import market.Qms.slmord.impl.DesignOrderReviewImpl;
import market.Slm.ContractManagement.impl.SlmContractBaseStationServiceImpl;
import market.Slm.ContractManagement.impl.SlmContractLineInfoServiceImpl;
import market.Slm.ContractManagement.impl.SlmContractLineLvServiceImpl;
import market.Slm.ContractManagement.mapper.SlmContractBaseStationMapper;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineLvMapper;
import market.Slm.ContractManagement.vo.SlmContractBaseStation;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmContractLineLv;
import market.Slm.CustomerInformation.impl.SlmCustomerTransSolutionServiceImpl;
import market.Slm.CustomerInformation.mapper.SlmCustomerTransSolutionMapper;
import market.Slm.CustomerInformation.vo.SlmCustomerTransSolution;
import market.Slm.DeliveryManagement.vo.SlmDeliveryPlanHeat;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.FundManagement.impl.SlmFundThirdAccountUsedServiceImpl;
import market.Slm.OrderManagement.mapper.SlmOrderChangeApplyMapper;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.mapper.SlmOrderSplitInfoMapper;
import market.Slm.OrderManagement.mapper.SlmProcessPlanMapper;
import market.Slm.OrderManagement.service.SlmOrderInfoService;
import market.Slm.OrderManagement.vo.SlmContractProcessPlan;
import market.Slm.OrderManagement.vo.SlmOrderChangeApply;
import market.Slm.OrderManagement.vo.SlmOrderInfo;
import market.Slm.OrderManagement.vo.SlmOrderSplitInfo;
import market.Slm.OrderManagement.vo.SlmProcessPlan;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
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 com.ibm.icu.text.SimpleDateFormat;

@Service("SlmOrderInfoService")
@RemoteService(path="SlmOrderInfoService")
public class SlmOrderInfoServiceImpl extends BaseServiceImpl<SlmOrderInfo,Object> implements SlmOrderInfoService {

	/**
	 * 订单查询
	 * memo1客户编号,memo2合同文本号
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String customer_no=sum.getMemo1();
		String txt_contract_no=sum.getMemo2();
		String flag=sum.getMemo3();
		String startTime=sum.getStartTime();		//用于查询创建时间
		String endTime=sum.getEndTime();
		String startTime2=sum.getStartTime2();		//用于查询交货期
		String endTime2=sum.getEndTime2();
		PageModel<SlmOrderInfo> pm=new PageModel<SlmOrderInfo>(pageIndex, pageSize);
		try{
			if(StringUtils.isNotEmpty(startTime)){
				startTime += " 00:00:00";
			} 
			if(StringUtils.isNotEmpty(startTime2)){
				startTime2 += " 00:00:00";
			}
			if(StringUtils.isNotEmpty(endTime)){
				endTime += " 23:59:59";
			} 
			if(StringUtils.isNotEmpty(endTime2)){
				endTime2 += " 23:59:59";
			} 
			if(order.getContract_no()!=null&&!"".equals(order.getContract_no())){
				order.setContract_no(order.getContract_no().trim());
			}
			String flags="";
			if("1".equals(flag)) flags=" and ORDER_FLAG_NO in('103408','103409')";
			if("103402".equals(order.getOrder_flag_no())){
				flags=" and ORDER_FLAG_NO ='103413'";
			}else 
				if("103403".equals(order.getOrder_flag_no())){
					flags=" and ORDER_FLAG_NO in ('103403','103413','103414','103415')";
				}else if(order.getOrder_flag_no()!=null&&!"".equals(order.getOrder_flag_no())){
					flags=" and ORDER_FLAG_NO ='"+order.getOrder_flag_no()+"'";
				}
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).doQuery(order,customer_no,txt_contract_no,startTime,endTime,startTime2,endTime2,(pageIndex-1)*pageSize,pageIndex*pageSize,flags);
			int count=this.getMapper(SlmOrderInfoMapper.class).doQueryCount(order,customer_no,txt_contract_no,startTime,endTime,startTime2,endTime2,flags);
			for(SlmOrderInfo orders:list){
				orders.setHave_plan("1");
				//原料卷  查询是否有加工计划
				if("2".equals(orders.getOrder_nature())){		
					SlmProcessPlan plan=new SlmProcessPlan();
					plan.setContract_no(orders.getContract_no());
					plan.setContract_line_seq(orders.getContract_line_seq());
					plan.setOrder_seq(orders.getOrder_seq());
					plan.setValid_flag("1");
					int p_count=this.getMapper(SlmProcessPlanMapper.class).count(plan);
					if(p_count==0) {						
						orders.setHave_plan("0"); 	//没有加工计划
					}
				}
				//生产状态的订单判断是否下发超过2天
				if(orders.getIssuer_time()!=null){
					long now_sec = new Date().getTime();
					long issuer_sec = orders.getIssuer_time().getTime();
					long cha = now_sec-issuer_sec;
					long day = 24*60*60*1000;
					if(cha > 1*day && cha < 3*day){
						orders.setColour("2");
					}else if(cha>=3*day){
						orders.setColour("3");
					}
				}
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 销售管理-订单管理-订单维护：查询功能
	 * @param sum
	 * @return
	 */
	public ResultModel doQueryOrderInfo(CommonPage<SlmOrderInfo> cp){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order = cp.getObject();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		String customer_no=cp.getMemo1().trim();
		String txt_contract_no=cp.getMemo2().trim();		//合同文本号
		
		String startTime = cp.getStartTime();			//用于查询创建时间
		String endTime = cp.getEndTime();
		String startTime2 = cp.getStartTime2();		//用于查询交货期
		String endTime2 = cp.getEndTime2();
		PageModel<SlmOrderInfo> pm=new PageModel<SlmOrderInfo>(pageIndex, pageSize);
		try{
			String condition = "";
			if (StringUtils.isNotEmpty(startTime)) {
				condition += " and t.create_time >= to_date('"+startTime+" 00:00:00', 'yyyy-MM-dd HH24:mi:ss')";
			}
			if (StringUtils.isNotEmpty(endTime)) {
				condition += " and t.create_time <= to_date('"+endTime+" 23:59:59', 'yyyy-MM-dd HH24:mi:ss')";
			}
			if (StringUtils.isNotEmpty(startTime2)) {
				condition += " and t.deliver_date >= to_date('"+startTime+" 00:00:00', 'yyyy-MM-dd HH24:mi:ss')";
			}
			if (StringUtils.isNotEmpty(endTime2)) {
				condition += " and t.deliver_date <= to_date('"+endTime+" 23:59:59', 'yyyy-MM-dd HH24:mi:ss')";
			}
			if (StringUtils.isNotEmpty(customer_no)) {
				condition += " and t.customer_no = '"+customer_no+"'";
			}
			if (StringUtils.isNotEmpty(order.getContract_no().trim())) {	//合同号(订单号)
				condition += " and t.contract_no||t.contract_line_seq||t.order_seq like '%"+order.getContract_no().trim()+"%'";
			}
			if (StringUtils.isNotEmpty(order.getSteel_code())) {			//牌号
				condition += " and t.steel_code = '"+order.getSteel_code()+"'";
			}
			if (StringUtils.isNotEmpty(order.getSteel_name().trim())) {		//牌号
				condition += " and t.steel_name like '%"+order.getSteel_name().trim()+"%'";
			}
			if (StringUtils.isNotEmpty(order.getOrder_nature())) {			//订单属性
				condition += " and t.order_nature = '"+order.getOrder_nature()+"'";
			}
			if (StringUtils.isNotEmpty(order.getDelivery_state_desc().trim())) {	//交货状态
				condition += " and t.delivery_state_desc like '%"+order.getDelivery_state_desc().trim()+"%'";
			}
			if (StringUtils.isNotEmpty(txt_contract_no)) {					//合同文本号
				condition += " and t.contract_pk in (select contract_pk from slm_contract_heat_info where txt_contract_no like '%"+txt_contract_no+"%')";
			}
			if (StringUtils.isNotEmpty(order.getOrder_flag_no())) {			//订单状态
				if ("103402".equals(order.getOrder_flag_no())) {	//103402交期评审中 = 103413质量设计评审中
					condition += " and t.order_flag_no = '103413'";
				}else if ("103403".equals(order.getOrder_flag_no())) {	//103403评审通过(正常) = 103413质量设计评审中+103414质量设计评审通过+103415质量设计评审失败
					condition += " and t.order_flag_no in ('103403','103413','103414','103415')";
				}else {
					condition += " and t.order_flag_no = '"+order.getOrder_flag_no()+"'";
				}
			}
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).doQueryOrderInfo(condition,(pageIndex-1)*pageSize,pageIndex*pageSize);
			String sql = "select count(1) from slm_order_info t where 1=1" + condition;
			int count = this.getMapper(PbModelDbMapper.class).doQueryCount(sql);
			for(SlmOrderInfo orders:list){				 
				//生产状态的订单判断是否下发超过2天
				if(orders.getIssuer_time()!=null){
					long now_sec = new Date().getTime();
					long issuer_sec = orders.getIssuer_time().getTime();
					long cha = now_sec-issuer_sec;
					long day = 24*60*60*1000;
					if(cha > 1*day && cha < 3*day){
						orders.setColour("2");
					}else if(cha>=3*day){
						orders.setColour("3");
					}
				}
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 订单新增
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddWeb(CommonPage<SlmOrderInfo> 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);

		SlmOrderInfo order=sum.getObject();
		try{
			if(order.getContract_pk()!=null){
				SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(order.getContract_pk());
				if(heat!=null){
					if("101606".equals(heat.getContract_type_no())&&"1".equals(order.getOrder_nature())){
						rm.setState("500");
						rm.setMsgInfo("来料加工合同无法新增原卷订单");
						return rm;
					}
					if(!"101602".equals(heat.getContract_type_no())&&"3".equals(order.getOrder_nature())){
						rm.setState("500");
						rm.setMsgInfo("只允许现货合同新增现货订单");
						return rm;
					}
				}
			}

			String orderNo=order.getContract_line_no();		//主键
			String seq="001";			//序号
			String max_seq=this.getMapper(SlmOrderInfoMapper.class).doQueryMax(order.getContract_line_no());
			if(max_seq==null){
				orderNo+=String.format("%03d",1);
			}else{
				int count=Integer.parseInt(max_seq);
				seq=String.format("%03d",(count+1));
				orderNo+=seq;
			}
			rm=doQueryWeightLimit(order);
			if("500".equals(rm.getState())){
				return rm;
			}
			if(order.getOrder_seq()==null||"".equals(order.getOrder_seq()))
				order.setOrder_seq(seq);
			order.setOrder_no(orderNo);
			order.setCreate_man_no(userId);
			order.setCreate_man_name(userName);
			if(order.getCreate_time()==null)
				order.setCreate_time(new Date());
			order.setOrder_flag_no("103401");
			order.setOrder_flag_name("编辑");
			order.setValid_flag("1");
			if(!"return".equals(sum.getMemo1()))
				order=doAddLv(order);
			if(!"2".equals(order.getOrder_nature()))
				order.setWhole_coil("0");
			
			
			//酸洗，冷轧合同 且合同号带H的，工序必须带退火 20210305 李xq
			if ("5".equals(order.getOrder_nature()) || "4".equals(order.getOrder_nature())) {//酸洗冷轧合同
				if (order.getContract_no()!=null && order.getContract_no().contains("H")) {//带H的合同
					if (StringUtils.isEmpty(order.getProcess()) || !order.getProcess().contains("退火")) {
						rm.setState("500");
						rm.setMsgInfo("合同号带H的酸洗冷轧合同，必须含有退火工序");
						return rm;
					}
				}
			}
			
			this.getMapper(SlmOrderInfoMapper.class).insert(order);
			//插入工艺要求
			if(order.getStation_list()!=null){
				if(order.getStation_list().size()>0){
					for(SlmContractBaseStation stations:order.getStation_list()){
						stations.setOrder_no(orderNo);
						stations.setSeq(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3));
						stations.setCreate_name(userName);
						stations.setCreate_time(new Date());
						this.getMapper(SlmContractBaseStationMapper.class).insert(stations);
					}
					this.getBean(SlmContractBaseStationServiceImpl.class).updateOrder(orderNo);
				}
			}
			
			//酸洗,冷轧订单，自动新增需加工计划20201119
			if ("5".equals(order.getOrder_nature()) || "4".equals(order.getOrder_nature())) {
				CommonPage<SlmProcessPlan> cp = new CommonPage<SlmProcessPlan>();
				SlmProcessPlan spp = new SlmProcessPlan();
				BeanUtils.copyProperties(spp, order);//复制order的属性到加工计划表
				spp.setContract_no(order.getContract_no());
				spp.setContract_line_seq(order.getContract_line_seq());
				spp.setOrder_seq(order.getOrder_seq());
				spp.setCut_type("0");//酸洗的切边方式默认不切
				spp.setContract_line_no(order.getContract_line_no());
				spp.setSpec(order.getThick()+"*"+order.getWidth());//规格
				spp.setPurchase_contract_no(order.getPurchase_contract_no());
				cp.setObject(spp);
				cp.setMemo1("0");//分切规则
				ResultModel rm1 = this.getBean(SlmProcessPlanServiceImpl.class).doAutoAddWeb(cp);
				if ("".equals(rm1.getState())) {
					rm.setState("500");
					rm.setMsgInfo("酸洗订单自动新增加工计划失败：" + rm1.getMsgInfo());
					return rm;
				}
			}
			
			
			
			rm.setState("200");
			if("return".equals(sum.getMemo1())) rm.setData(order);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("新增失败"+ex.getMessage());
			ex.printStackTrace();
			throw new Exception("新增失败"+ex.getMessage());
		}
		return rm;
	}

	/**
	 * 订单强冲新增
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doForceAddWeb(CommonPage<SlmOrderInfo> 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);
		SlmOrderInfo order=sum.getObject();
		try{
			if(order.getContract_pk()!=null){
				SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(order.getContract_pk());
				if(heat!=null){
					if("101606".equals(heat.getContract_type_no())&&"1".equals(order.getOrder_nature())){
						rm.setState("500");
						rm.setMsgInfo("来料加工合同无法新增原卷订单");
						return rm;
					}
					if(!"101602".equals(heat.getContract_type_no())&&"3".equals(order.getOrder_nature())){
						rm.setState("500");
						rm.setMsgInfo("只允许现货合同新增现货订单");
						return rm;
					}
				}
			}
			String orderNo=order.getContract_line_no();		//主键
			String seq="001";			//序号
			String maxNo=this.getMapper(SlmOrderInfoMapper.class).doQueryMax(order.getContract_line_no());
			if(maxNo==null){
				orderNo+=String.format("%03d",1);
			}else{
				maxNo=maxNo.substring(maxNo.length()-3);
				int count=Integer.parseInt(maxNo);
				seq=String.format("%03d",(count+1));
				orderNo+=seq;
			}
			if(order.getOrder_seq()==null||"".equals(order.getOrder_seq()))
				order.setOrder_seq(seq);
			order.setOrder_no(orderNo);
			order.setCreate_man_no(userId);
			order.setCreate_man_name(userName);
			if(order.getCreate_time()==null)
				order.setCreate_time(new Date());
			order.setOrder_flag_no("103401");
			order.setOrder_flag_name("编辑");
			order.setValid_flag("1");
			if(order.getMemo()==null||"".equals(order.getMemo()))
				order.setMemo("强冲订单");
			order=doAddLv(order);
			if(!"2".equals(order.getOrder_nature()))
				order.setWhole_coil("0");
			this.getMapper(SlmOrderInfoMapper.class).insert(order);
			//插入工艺要求
			if(order.getStation_list()!=null){
				for(SlmContractBaseStation stations:order.getStation_list()){
					stations.setOrder_no(orderNo);
					stations.setSeq(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3));
					stations.setCreate_name(userName);
					stations.setCreate_time(new Date());
					this.getMapper(SlmContractBaseStationMapper.class).insert(stations);
				}
				this.getBean(SlmContractBaseStationServiceImpl.class).updateOrder(orderNo);
			}
			rm.setState("200");
			if("return".equals(sum.getMemo1())) rm.setData(order);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("新增失败"+ex.getMessage());
			ex.printStackTrace();
			throw new Exception("新增失败"+ex.getMessage());
		}
		return rm;
	}

	/**
	 * 带入合同行的精度等级
	 * */
	private SlmOrderInfo doAddLv(SlmOrderInfo order){
		if(order.getLv_list()!=null&&order.getLv_list().size()>0){
			for(SlmContractLineLv lvs:order.getLv_list()){
				lvs.setContract_line_no(order.getContract_line_no());
				lvs.setContract_line_seq(order.getContract_line_seq());
				lvs.setContract_pk(order.getContract_pk());
				lvs.setOrder_no(order.getOrder_no());
				lvs.setOrder_seq(order.getOrder_seq());
			}
			CommonPage<SlmContractLineLv> lv_sum=new CommonPage<SlmContractLineLv>();
			lv_sum.setObjectList(order.getLv_list());
			try {
				lv_sum.setMemo4(order.getOrder_no());
				this.getBean(SlmContractLineLvServiceImpl.class).doSaveWeb(lv_sum);
			} catch (Exception e) {
			}
		}else{
			SlmContractLineLv lv=new SlmContractLineLv();
			lv.setContract_line_no(order.getContract_line_no());
			lv.setIs_flag("0");
			List<SlmContractLineLv> lv_list=this.getMapper(SlmContractLineLvMapper.class).find(lv, 0, 0);
			for(SlmContractLineLv lvs:lv_list){
				lvs.setIs_flag("1");
				lvs.setOrder_no(order.getOrder_no());
				lvs.setSeq(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3));
				this.getMapper(SlmContractLineLvMapper.class).insert(lvs);
			}
			SlmContractLineInfo line=this.getMapper(SlmContractLineInfoMapper.class).findById(order.getContract_line_no());
			if(line!=null){
				order.setLv_code(line.getLv_code());
				order.setLv_desc(line.getLv_desc());
				order.setPrecisicon_type_code(line.getPrecisicon_type_code());
				order.setPrecisicon_type_desc(line.getPrecisicon_type_desc());
			}
		}
		return order;
	}

	/**
	 * 订单编辑
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmOrderInfo> 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);
		SlmOrderInfo order=sum.getObject();
		try{
			//判断何种状态可以进行编辑
			SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(order.getOrder_no());
			if(!"103401".equals(newOrder.getOrder_flag_no())&&!"1".equals(newOrder.getValid_flag())){		//只有编辑状态才可修改
				rm.setMsgInfo("当前状态无法编辑");
				rm.setState("500");
				return rm;
			}
			//重量判断
			//			SlmContractLineInfo line=this.getMapper(SlmContractLineInfoMapper.class).findById(newOrder.getContract_line_no());
			//			if(line!=null){
			//				//获取所有的订单信息
			//				SlmOrderInfo Sorder=new SlmOrderInfo();
			//				Sorder.setContract_line_seq(line.getContract_line_seq());
			//				if(order.getContract_no()!=null&&!"".equals(order.getContract_no()))
			//					Sorder.setContract_no(order.getContract_no());
			//				else
			//					Sorder.setContract_pk(order.getContract_pk());
			//				List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(Sorder, null, null, 0, 0);
			//				Double material_total=0d;		//原料卷总重
			//				Double work_total=0d;		//加工总重
			//				Double unplan_total=0d;		//非计划总重
			//				for(SlmOrderInfo orders:orderList){
			//					if("1".equals(orders.getOrder_nature())){
			//						material_total+=orders.getEstimate_weight();
			//					}
			//					if("2".equals(orders.getOrder_nature())){
			//						work_total+=orders.getEstimate_weight();
			//					}
			//					if("3".equals(orders.getOrder_nature())){
			//						unplan_total+=orders.getEstimate_weight();
			//					}
			//				}
			//				double org_weight=order.getEstimate_weight();
			//				if("1".equals(order.getOrder_nature())){
			//					if((material_total-newOrder.getEstimate_weight()+org_weight+unplan_total)>line.getEstimate_weight()){
			//						rm.setState("500");
			//						rm.setMsgInfo("订单重量数值不得超过"+(line.getEstimate_weight()-material_total+newOrder.getEstimate_weight()));
			//						return rm;
			//					}
			//				}else if("2".equals(order.getOrder_nature())){
			//					if((work_total-newOrder.getEstimate_weight()+org_weight+unplan_total)>line.getEstimate_weight()){
			//						rm.setState("500");
			//						rm.setMsgInfo("订单重量数值不得超过"+(line.getEstimate_weight()-work_total+newOrder.getEstimate_weight()));
			//						return rm;
			//					}
			//				}else if("3".equals(order.getOrder_nature())){
			//					double bigger=material_total;
			//					if(material_total<work_total) bigger=work_total;
			//					if((unplan_total-newOrder.getEstimate_weight()+bigger)>line.getEstimate_weight()){
			//						rm.setState("500");
			//						rm.setMsgInfo("订单重量数值不得超过"+(line.getEstimate_weight()-bigger-unplan_total+newOrder.getEstimate_weight()));
			//						return rm;
			//					}
			//				}
			//			}
			
			//判断是否是拆分订单，如果是则联动母订单修改重量
			if(newOrder.getOrder_no().contains("-")){
				double weight_cha=DoubleUtil.sub(order.getEstimate_weight(), newOrder.getEstimate_weight());		//重量差
				String p_order_no=newOrder.getOrder_no().split("-")[0];
				SlmOrderInfo p_order=this.getMapper(SlmOrderInfoMapper.class).findById(p_order_no);
				if(p_order!=null){
					if(weight_cha>p_order.getEstimate_weight()){
						throw new Exception("修改的重量差["+weight_cha+"]不得大于原订单的重量");
					}
				}
				p_order.setEstimate_weight(DoubleUtil.sub(p_order.getEstimate_weight(), weight_cha));
				this.getMapper(SlmOrderInfoMapper.class).update(p_order);
			}
			order.setUpdate_man_no(userId);
			order.setUpdate_man_name(userName);
			order.setUpdate_time(new Date());
			this.getMapper(SlmOrderInfoMapper.class).update(order);
			//给加工计划赋上采购合同号
			if(order.getContract_no()!=null&&!"".equals(order.getContract_no())){
				SlmProcessPlan plan=new SlmProcessPlan();
				plan.setContract_no(order.getContract_no());
				plan.setContract_line_seq(order.getContract_line_seq());
				plan.setOrder_seq(order.getOrder_seq());
				List<SlmProcessPlan> plan_list=this.getMapper(SlmProcessPlanMapper.class).find(plan, 0, 0);
				
				for(SlmProcessPlan plans:plan_list){
					//================eason 2019-08-13 add==================
					if("1".equals(order.getWhole_coil())){
						plans.setPlan_flag("0");
					}
					//============================================
					plans.setPurchase_contract_no(order.getPurchase_contract_no());
					this.getMapper(SlmProcessPlanMapper.class).update(plans);
				}
			}
			//新增精度等级
			if(order.getLv_list()!=null){
				for(SlmContractLineLv lvs:order.getLv_list()){
					lvs.setContract_line_no(newOrder.getContract_line_no());
					lvs.setContract_line_seq(newOrder.getContract_line_seq());
					lvs.setContract_pk(newOrder.getContract_pk());
					lvs.setOrder_no(newOrder.getOrder_no());
					lvs.setOrder_seq(newOrder.getOrder_seq());
				}
				if(order.getLv_list().size()>0){
					CommonPage<SlmContractLineLv> lv_sum=new CommonPage<SlmContractLineLv>();
					lv_sum.setObjectList(order.getLv_list());
					lv_sum.setMemo2(newOrder.getContract_line_no());
					lv_sum.setMemo4(newOrder.getOrder_no());
					this.getBean(SlmContractLineLvServiceImpl.class).doSaveWeb(lv_sum);
				}
			}
			this.getBean(SlmContractBaseStationServiceImpl.class).updateOrder(newOrder.getOrder_no());
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("编辑失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单启用停用
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSwitchWeb(CommonPage<SlmOrderInfo> 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);
		SlmOrderInfo order=sum.getObject();
		String state="1".equals(order.getValid_flag())?"启用":"停用";
		try{
			//判断何种状态可以进行启用停用
			SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(order.getOrder_no());
			if(!"103401".equals(newOrder.getOrder_flag_no())){		//103401 编辑之前的都可以启用停用
				rm.setMsgInfo("当前状态无法"+state);
				rm.setState("500");
				return rm;
			}
			if("0".equals(order.getValid_flag())){		//停用
				order.setDelete_man_no(userId);
				order.setDelete_man_name(userName);
				order.setDelete_time(new Date());
				this.getMapper(SlmOrderInfoMapper.class).update(order);
				//				//删除工艺要求
				//				SlmContractBaseStation station=new SlmContractBaseStation();
				//				station.setOrder_no(order.getOrder_no());
				//				List<SlmContractBaseStation> station_list=this.getMapper(SlmContractBaseStationMapper.class).find(station,0,0);
				//				for(SlmContractBaseStation stations:station_list){
				//					this.getMapper(SlmContractBaseStationMapper.class).delete(stations.getSeq());
				//				}
			}else{			//启用
				order.setUpdate_man_no(userId);
				order.setUpdate_man_name(userName);
				order.setUpdate_time(new Date());
				this.getMapper(SlmOrderInfoMapper.class).doEnable(order);
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(state+"失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单删除
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doActualDeleteWeb(CommonPage<SlmOrderInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userName2=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		SlmOrderInfo order=sum.getObject();
		try{
			//判断何种状态可以进行删除
			SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(order.getOrder_no());			
			if(newOrder!=null){
				if(!"103401".equals(newOrder.getOrder_flag_no())){		//103401 编辑之前的都可以删除
					rm.setMsgInfo("当前状态无法删除");
					rm.setState("500");
					return rm;
				}  
				// ==========================eason add/update 2019-06-22=================
				//如果是拆分出来的订单，删除之后重量要还原回去
				if(newOrder.getP_order_no()!=null&&!"".equals(newOrder.getP_order_no())){
					SlmOrderInfo p_order=this.getMapper(SlmOrderInfoMapper.class).findById(newOrder.getP_order_no());
					if(p_order!=null){
						p_order.setEstimate_weight(DoubleUtil.add(p_order.getEstimate_weight(), newOrder.getEstimate_weight()));
						this.getMapper(SlmOrderInfoMapper.class).update(p_order);
					}
					//删除拆分订单信息
					String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
					String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
					
					
					SlmOrderSplitInfo split=new SlmOrderSplitInfo();
					split.setOrder_no_child(order.getOrder_no());
					List<SlmOrderSplitInfo> ls=this.getMapper(SlmOrderSplitInfoMapper.class).find(split, 0, 0);
					for(SlmOrderSplitInfo su:ls){
						SlmOrderSplitInfo sp=new SlmOrderSplitInfo();
						sp.setId(su.getId());
						sp.setValid_flag("0"); 
						sp.setDelete_man_no(userId);
						sp.setDelete_man_name(userName);
						sp.setDelete_time(new Date());
						this.getMapper(SlmOrderSplitInfoMapper.class).update(sp);
					}
				}
				/*
				//如果是拆分出来的订单，删除之后重量要还原回去
				if(newOrder.getOrder_no().contains("-")){
					String p_order_no=newOrder.getOrder_no().split("-")[0];
					SlmOrderInfo p_order=this.getMapper(SlmOrderInfoMapper.class).findById(p_order_no);
					if(p_order!=null){
						p_order.setEstimate_weight(DoubleUtil.add(p_order.getEstimate_weight(), newOrder.getEstimate_weight()));
						this.getMapper(SlmOrderInfoMapper.class).update(p_order);
					}
				}
				//*/
				//======================================================
				this.getMapper(SlmOrderInfoMapper.class).delete(order.getOrder_no());
				//删除加工计划
				SlmProcessPlan plan=new SlmProcessPlan();
				plan.setContract_no(newOrder.getContract_no());
				plan.setContract_line_seq(newOrder.getContract_line_seq());
				plan.setOrder_seq(newOrder.getOrder_seq());
				List<SlmProcessPlan> planList=this.getMapper(SlmProcessPlanMapper.class).find(plan, 0, 0);
				for(SlmProcessPlan plans:planList){
					this.getMapper(SlmProcessPlanMapper.class).delete(plans.getPlan_no());
				}
				//删除精度等级
				SlmContractLineLv lv=new SlmContractLineLv();
				lv.setOrder_no(newOrder.getOrder_no());
				lv.setIs_flag("1");
				List<SlmContractLineLv> lv_list=this.getMapper(SlmContractLineLvMapper.class).find(lv, 0, 0);
				for(SlmContractLineLv lvs:lv_list){
					this.getMapper(SlmContractLineLvMapper.class).delete(lvs.getSeq());
				}
				//删除工艺要求
				SlmContractBaseStation station=new SlmContractBaseStation();
				station.setOrder_no(newOrder.getOrder_no());
				List<SlmContractBaseStation> station_list=this.getMapper(SlmContractBaseStationMapper.class).find(station, 0, 0);
				for(SlmContractBaseStation stations:station_list){
					this.getMapper(SlmContractBaseStationMapper.class).delete(stations.getSeq());
				}
				
				MesOprLog mol = new MesOprLog("销售管理", "订单维护", "订单删除", userName2, opr_time, null, null, null, null, newOrder.getContract_no() + newOrder.getContract_line_seq() + newOrder.getOrder_seq());
				this.getMapper(MesOprLogMapper.class).insert(mol);
				
			}else{
				rm.setMsgInfo("该订单已经被删除");
				rm.setState("500");
				return rm;
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("删除失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单提报，支持批量提报
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSubmitWeb(CommonPage<SlmOrderInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		try{
			if(order!=null){
				List<SlmOrderInfo> list=order.getList();
				if(list!=null){
					for(SlmOrderInfo orders:list){
						//判断何种状态可以提报
						SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(orders.getOrder_no());
						if(newOrder==null) continue;
						if(!"103401".equals(newOrder.getOrder_flag_no())||!"1".equals(newOrder.getValid_flag())){	//只有编辑状态才可提报
							rm.setState("500");
							rm.setMsgInfo("订单的状态不符合要求，无法提交");
							return rm;
						}
						//需加工订单需要加工计划方可提交
						List<SlmProcessPlan> plan_list=new ArrayList<SlmProcessPlan>();
						//20201027 华p:酸洗和冷轧订单提交订单时，取消加工计划的要求控制
						if("2".equals(newOrder.getOrder_nature())||"4".equals(newOrder.getOrder_nature())||"5".equals(newOrder.getOrder_nature())){
						//if("2".equals(newOrder.getOrder_nature())){
							if(!"1".equals(newOrder.getWhole_coil())){			//不为整卷发运
								SlmProcessPlan plan=new SlmProcessPlan();
								plan.setContract_no(newOrder.getContract_no());
								plan.setContract_line_seq(newOrder.getContract_line_seq());
								plan.setOrder_seq(newOrder.getOrder_seq());
								plan.setValid_flag("1");
								plan_list=this.getMapper(SlmProcessPlanMapper.class).find(plan,0,0);
								if(plan_list.size()==0 && "2".contains(newOrder.getOrder_nature())){
									rm.setState("500");
									rm.setMsgInfo("订单无加工计划，无法提交");
									return rm;
								}
								if(plan_list.size()>0){			//加工订单带入加工计划第一条的备注(卷号)
									orders.setPlan_memo(plan_list.get(0).getMemo());
								}
								//	需加工订单调用质量接口修改加工计划的评审状态【改为评审中
								CommonPage<SlmContractProcessPlan> param=generateParam(newOrder,plan_list);
								ResultModel newRm=this.getBean(DesignOrderReviewImpl.class).OrderPossibleReview(param);
								if("404".equals(newRm.getState())){
									newRm.setState("500");
									return newRm;
								}
								orders.setOrder_flag_no("103413");
								orders.setOrder_flag_name("质量设计评审中");

							}else{
								orders.setOrder_flag_no("103403");
								orders.setOrder_flag_name("评审通过(正常)");
							}
						}else{
							orders.setOrder_flag_no("103403");
							orders.setOrder_flag_name("评审通过(正常)");
						}
						//修改状态
						orders.setP_order_flag_no(newOrder.getOrder_flag_no());
						orders.setP_order_flag_name(newOrder.getOrder_flag_name());	
						this.getMapper(SlmOrderInfoMapper.class).update(orders);
					}
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("提报失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单回撤  到编辑
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRollbackWeb(CommonPage<SlmOrderInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmOrderInfo> list=sum.getObjectList();
		try{
			if(list!=null){
				for(SlmOrderInfo orders:list){
					//判断何种状态可以进行回撤
					SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(orders.getOrder_no());
					if(!"103403".equals(newOrder.getOrder_flag_no())&&!"103414".equals(newOrder.getOrder_flag_no())&&!"103415".equals(newOrder.getOrder_flag_no())
							&&!"103404".equals(newOrder.getOrder_flag_no())){		
						rm.setState("500");
						rm.setMsgInfo("有订单的状态不符合要求，无法撤回");
						return rm;
					}
					//已质量评审不让撤回？
					if("245".contains(newOrder.getOrder_nature())){
						SlmProcessPlan plan=new SlmProcessPlan();
						plan.setOrder_no(newOrder.getOrder_no());
						plan.setValid_flag("1");
						List<SlmProcessPlan> plan_list=this.getMapper(SlmProcessPlanMapper.class).find(plan, 0, 0);
						for(SlmProcessPlan plans:plan_list){
							if("103413".equals(plans.getPlan_flag())){
								rm.setState("500");
								rm.setMsgInfo("有加工计划处于质量评审中，无法撤回");
								return rm;
							}
						}
						for(SlmProcessPlan plans:plan_list){		//可撤回
							//===============eason add 2019-08-13==========
							//plans.setPlan_flag("103413");
							plans.setPlan_flag("0");
							//============================================
							this.getMapper(SlmProcessPlanMapper.class).update(plans);
						}
					}
					orders.setPlan_memo("");
					orders.setP_order_flag_no(newOrder.getOrder_flag_no());
					orders.setP_order_flag_name(newOrder.getOrder_flag_name());
					orders.setOrder_flag_no("103401");
					orders.setOrder_flag_name("编辑");
					orders.setUpdate_man_no(userId);
					orders.setUpdate_man_name(userName);
					orders.setUpdate_time(new Date());
					this.getMapper(SlmOrderInfoMapper.class).update(orders);


				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("回撤失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单下发，支持批量下发
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doIssuedWeb(CommonPage<SlmOrderInfo> 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);
		SlmOrderInfo order=sum.getObject();
		try{
			if(order!=null){
				List<SlmOrderInfo> list=order.getList();
				if(list!=null){
					for(SlmOrderInfo orders:list){	//判断何种状态可以下发
						SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(orders.getOrder_no());
						if(newOrder==null||"0".equals(newOrder.getValid_flag())){
							rm.setState("500");
							rm.setMsgInfo("无效订单无法下发");
							return rm;
						}
						if(!"245".contains(newOrder.getOrder_nature())&&!"103402".equals(newOrder.getOrder_flag_no())&&!"103403".equals(newOrder.getOrder_flag_no())&&!"103404".equals(newOrder.getOrder_flag_no())){
							rm.setState("500");
							rm.setMsgInfo("该订单状态无法下发");
							return rm;
						}	
						if("245".contains(newOrder.getOrder_nature())&&!"1".equals(newOrder.getWhole_coil())){
							if(!"103414".equals(newOrder.getOrder_flag_no())){
								rm.setState("500");
								rm.setMsgInfo("加工、酸洗、冷轧订单需评审通过才可下发");
								return rm;
							}
						}
						//无合同号不让下发
						if(newOrder.getContract_no()==null||"".equals(newOrder.getContract_no())){
							rm.setState("500");
							rm.setMsgInfo("无合同号订单无法下发");
							return rm;
						}
						orders.setP_order_flag_no(newOrder.getOrder_flag_no());
						orders.setP_order_flag_name(newOrder.getOrder_flag_name());
					}
					for(SlmOrderInfo orders:list){
						orders.setOrder_flag_no("103406");
						orders.setOrder_flag_name("下发");
						orders.setIssuer_man_no(userId);
						orders.setIssuer_man_name(userName);
						orders.setIssuer_time(new Date());
						this.getMapper(SlmOrderInfoMapper.class).update(orders);
					}
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("下发失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}


	/**
	 * 订单回收
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRecoveryWeb(CommonPage<SlmOrderInfo> 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);
		SlmOrderInfo order=sum.getObject();
		try{
			if(order!=null){
				List<SlmOrderInfo> list=order.getList();
				if(list!=null){
					for(SlmOrderInfo orders:list){
						//判断何种状态可以进行回收
						SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(orders.getOrder_no());
						if(!"103406".equals(newOrder.getOrder_flag_no())){		
							rm.setState("500");
							rm.setMsgInfo("有订单的状态不符合要求，无法回收");
							return rm;
						}
						orders.setP_order_flag_no(newOrder.getOrder_flag_no());
						orders.setP_order_flag_name(newOrder.getOrder_flag_name());
						orders.setOrder_flag_no("103403");
						orders.setOrder_flag_name("评审通过(正常)");
						if("245".contains(newOrder.getOrder_nature())&&!"1".equals(newOrder.getWhole_coil())){
							orders.setOrder_flag_no("103414");
							orders.setOrder_flag_name("质量设计评审通过");
						}
						orders.setUpdate_man_no(userId);
						orders.setUpdate_man_name(userName);
						orders.setUpdate_time(new Date());
						this.getMapper(SlmOrderInfoMapper.class).update(orders);
					}
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("回收失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单关闭
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCloseWeb(CommonPage<SlmOrderInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmOrderInfo> list=sum.getObjectList();
		try{
			if(list!=null){
				for(SlmOrderInfo orders:list){
					//判断何种状态可以关闭
					SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(orders.getOrder_no());
					if(!"103412".equals(newOrder.getOrder_flag_no())){		//非关闭状态
						orders.setOrder_flag_no("103412");
						orders.setOrder_flag_name("关闭");
						orders.setP_order_flag_no(newOrder.getOrder_flag_no());
						orders.setP_order_flag_name(newOrder.getOrder_flag_name());
						orders.setUpdate_man_no(userId);
						orders.setUpdate_man_name(userName);
						orders.setUpdate_time(new Date());
						this.getMapper(SlmOrderInfoMapper.class).update(orders);
						//占用资金释放
						rm=this.getBean(SlmFundThirdAccountUsedServiceImpl.class).doReleaseFund(newOrder.getContract_no(),null,newOrder,null);
						if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
					
						//============eason add 2019-07-19 增加生产接口调用==============
						try{
							this.getBean(PlnProdorderStatisticServiceImpl.class).Prod_Over(orders.getOrder_no(), true);
						}catch(Exception e){ }
						//=============================================================
					}
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("回收失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单取消关闭
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelCloseWeb(CommonPage<SlmOrderInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmOrderInfo> list=sum.getObjectList();
		try{
			if(list!=null){
				for(SlmOrderInfo orders:list){
					SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(orders.getOrder_no());
					SlmContractLineInfo line=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryById(newOrder.getContract_line_no());
					if("102609".equals(line.getLine_flag_no())){
						rm.setState("500");
						rm.setMsgInfo("该订单所在的合同行已结案，无法启用");
						return rm;
					}
					if("1".equals(newOrder.getValid_flag())&&"103412".equals(newOrder.getOrder_flag_no())){		//关闭状态
						orders.setOrder_flag_no(newOrder.getP_order_flag_no());
						orders.setOrder_flag_name(newOrder.getP_order_flag_name());
						orders.setUpdate_man_no(userId);
						orders.setUpdate_man_name(userName);
						orders.setUpdate_time(new Date());
						this.getMapper(SlmOrderInfoMapper.class).update(orders);
						
						//============eason add 2019-07-19 增加生产接口调用==============
						try{
							this.getBean(PlnProdorderStatisticServiceImpl.class).Prod_Over(orders.getOrder_no(), false);
						}catch(Exception e){ }
						//=============================================================
					}
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("回收失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}

	/**
	 * 订单详情
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		try{
			if(order!=null){
				order=this.getMapper(SlmOrderInfoMapper.class).findById(order.getOrder_no());
				SlmCustomerTransSolution solutions=this.getBean(SlmCustomerTransSolutionServiceImpl.class).doQueryOne(order.getSolutions_no());
				if(solutions!=null) order.setSolutions_name(solutions.getSolutions_name());
				SlmContractLineInfo line=new SlmContractLineInfo();
				if(order.getContract_no()!=null&&!"".equals(order.getContract_no())){
					line.setContract_no(order.getContract_no());
					line.setContract_line_seq(order.getContract_line_seq());
				}else{
					line.setContract_line_no(order.getContract_line_no());
				}
				List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).find(line, 0, 0);
				if(lineList.size()>0){
					order.setWidth(lineList.get(0).getWidth());
					order.setLength(lineList.get(0).getLength());
					order.setThick(lineList.get(0).getThick());
				}
			}
			rm.setState("200");
			rm.setData(order);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 新增订单时调用，查询合同量的上限
	 * */
	public ResultModel doQueryWeightMax(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		try{
			rm.setState("200");
			//重量判断
			SlmContractLineInfo line=this.getMapper(SlmContractLineInfoMapper.class).findById(order.getContract_line_no());
			if(line==null){
				rm.setState("500");
				rm.setMsgInfo("合同行数据丢失，请联系管理员");
				return rm;
			}
			SlmOrderInfo Sorder=new SlmOrderInfo();
			Sorder.setContract_line_seq(line.getContract_line_seq());
			if(line.getContract_no()!=null&&!"".equals(line.getContract_no()))
				Sorder.setContract_no(line.getContract_no());
			else
				Sorder.setContract_pk(line.getContract_pk());
			List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(Sorder, null, null, 0, 0);
			Double material_total=0d;	//原料卷总重
			Double work_total=0d;		//加工总重
			Double cool_total=0d;       //冷轧总重
			Double scour_total=0d;      //酸洗总重
			Double unplan_total=0d;		//非计划总重
			Double max_total=0d;        //最大重量

			for(SlmOrderInfo orders:orderList){
				//原料卷
				if("1".equals(orders.getOrder_nature())){
					material_total=DoubleUtil.add(material_total,orders.getEstimate_weight());
					max_total=Math.max(material_total, max_total);
				}
				//需加工
				if("2".equals(orders.getOrder_nature())){
					work_total=DoubleUtil.add(orders.getEstimate_weight(),work_total);
					max_total=Math.max(work_total, max_total);
				}
				//非计划
				if("3".equals(orders.getOrder_nature())){
					unplan_total=DoubleUtil.add(orders.getEstimate_weight(),unplan_total);
				}
				//冷轧
				if("4".equals(orders.getOrder_nature())){
					cool_total=DoubleUtil.add(orders.getEstimate_weight(),cool_total);
					max_total=Math.max(cool_total, max_total);
				}
				//酸洗
				if("5".equals(orders.getOrder_nature())){
					scour_total=DoubleUtil.add(orders.getEstimate_weight(),scour_total);
					max_total=Math.max(scour_total, max_total);
				}
			}
			String order_type="原料卷";
//			交货量误差上限
			Double permit_total=line.getDelivery_error_max();
			//原料卷
			if("1".equals(order.getOrder_nature())){
				permit_total=DoubleUtil.sub(permit_total,material_total);
				order_type="原料卷";
			}
			//需加工
			if("2".equals(order.getOrder_nature())){
				permit_total=DoubleUtil.sub(permit_total,work_total);
				order_type="加工";
			}
			//非计划
			if("3".equals(order.getOrder_nature())){
				permit_total=DoubleUtil.sub(permit_total,unplan_total);
				order_type="非计划";
			}
			//冷轧
			if("4".equals(order.getOrder_nature())){
				permit_total=DoubleUtil.sub(permit_total,cool_total);
				order_type="冷轧";
			}
			//酸洗
			if("5".equals(order.getOrder_nature())){
				permit_total=DoubleUtil.sub(permit_total,scour_total);
				order_type="酸洗";
			}
			if(permit_total<=0){
				if(line.getEstimate_weight().equals(unplan_total)){
					order_type="非计划";
				}
				rm.setState("500");
				rm.setData(0);
				rm.setMsgInfo("该合同行下"+order_type+"订单重量已满额");
				return rm;
			}
			rm.setData(DoubleUtil.round(permit_total-line.getDelivery_error_max()+line.getEstimate_weight(),DoubleUtil.DEF_DIV_SCALE));
			return rm;
		}catch(Exception e){
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 为发运查询
	 * */
	public ResultModel doQueryForDeliveryWeb(CommonPage<SlmDeliveryPlanHeat> sum){
		ResultModel rm=new ResultModel();
		SlmDeliveryPlanHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String order_no=sum.getMemo1();
		PageModel<SlmOrderInfo> pm=new PageModel<SlmOrderInfo>(pageIndex, pageSize);
		try{
			SlmOrderInfo order=new SlmOrderInfo();
			order.setCustomer_no(heat.getCustomer_no());
			order.setReciver_unit_no(heat.getReciver_unit_no());
			if(order_no!=null&&!"".equals(order_no)){
				String contract_no=order_no.substring(0,order_no.length()-6);
				String line_seq=order_no.substring(order_no.length()-6,order_no.length()-3);
				String order_seq=order_no.substring(order_no.length()-3);
				order.setContract_no(contract_no);
				order.setContract_line_seq(line_seq);
				order.setOrder_seq(order_seq);
			}
			//			order.setOrder_no(order_no);
			order.setValid_flag("1");
			//			String date=heat.getPlan_year()+"-"+heat.getPlan_month();
			//			String sWhere="'"+date+"' >=to_char(deliver_date, 'yyyy-mm') ";
			String sWhere=" order_flag_no in('103407','103408','103409','103410')";		//接收到发货
			//订单状态为未结算、未关闭状态 【后续添加
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, sWhere, " create_time desc", (pageIndex-1)*pageSize, pageSize);
			int count=this.getMapper(SlmOrderInfoMapper.class).countWithCondition(order, sWhere);
			for(SlmOrderInfo orders:list){
				String orderNo=orders.getContract_no()+orders.getContract_line_seq()+orders.getOrder_seq();
				orders.setOrder_no(orderNo);
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	/**
	 * 为提单查询-new version 
	 * order by 未发量
	 * */
	public ResultModel doQueryForBillWeb(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String order_no=sum.getMemo1();
		List<SlmOrderInfo> list = new ArrayList<SlmOrderInfo>();
		int count;
		PageModel<SlmOrderInfo> pm=new PageModel<SlmOrderInfo>(pageIndex, pageSize);
		try{
			SlmOrderInfo order=new SlmOrderInfo();
			order.setCustomer_no(heat.getCustomer_no());
			order.setReciver_unit_no(heat.getReciver_unit_no());
			order.setContract_no(heat.getContract_no());
			if(order_no!=null&&!"".equals(order_no)){
				String contract_no=order_no.substring(0,order_no.length()-6);
				String line_seq=order_no.substring(order_no.length()-6,order_no.length()-3);
				String order_seq=order_no.substring(order_no.length()-3);
				order.setContract_no(contract_no);
				order.setContract_line_seq(line_seq);
				order.setOrder_seq(order_seq);
			}
			order.setValid_flag("1");
			order.setOrder_nature(heat.getOrder_nature());//设置订单属性
			//订单状态为未结算、未关闭状态 【后续添加
			List<SlmOrderInfo> order_no_list=this.getMapper(SlmOrderInfoMapper.class).doQueryYdm();
			String order_no_sum=" and o.order_no in (";
			if(order_no_list.size()>0){
				for(SlmOrderInfo orders:order_no_list){
					order_no_sum+="'"+orders.getOrder_no()+"',";
				}
				order_no_sum=order_no_sum.substring(0,order_no_sum.length()-1);
				order_no_sum+=")";
			}else{
				order_no_sum=null;
			}
			
			list=this.getMapper(SlmOrderInfoMapper.class).doQueryForBill(order,order_no_sum,(pageIndex-1)*pageSize, pageIndex*pageSize);
			count=this.getMapper(SlmOrderInfoMapper.class).doQueryForBillCount(order,order_no_sum);
			
			for(SlmOrderInfo orders:list){
				orders.setTotal_bill_weight(DoubleUtil.round(orders.getTotal_bill_weight(),DoubleUtil.DEF_DIV_SCALE));
				orders.setUnshipped_bill_weight(DoubleUtil.round(orders.getUnshipped_bill_weight()/1000,DoubleUtil.DEF_DIV_SCALE));
				orders.setUndisposed_bill_weight(DoubleUtil.sub(orders.getEstimate_weight(), orders.getTotal_bill_weight()));
				String orderNo=orders.getContract_no()+orders.getContract_line_seq()+orders.getOrder_seq();
				orders.setOrder_no(orderNo);
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 获取可发重量
	 * @param sum
	 * @return
	 */
	public ResultModel doQueryForBillWebForWeight(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String order_no=sum.getMemo1();
		try{
			SlmOrderInfo order=new SlmOrderInfo();
			order.setCustomer_no(heat.getCustomer_no());
			order.setReciver_unit_no(heat.getReciver_unit_no());
			order.setContract_no(heat.getContract_no());
			if(order_no!=null&&!"".equals(order_no)){
				String contract_no=order_no.substring(0,order_no.length()-6);
				String line_seq=order_no.substring(order_no.length()-6,order_no.length()-3);
				String order_seq=order_no.substring(order_no.length()-3);
				order.setContract_no(contract_no);
				order.setContract_line_seq(line_seq);
				order.setOrder_seq(order_seq);
			}
			order.setValid_flag("1");
			//直接根据合同号进行查询
			String order_no_sum= " and o.contract_no || o.contract_line_seq || o.order_seq = '"+sum.getMemo2()+"'";
			
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).doQueryForBill(order,order_no_sum,(pageIndex-1)*pageSize, pageIndex*pageSize);			
			if (list!=null &&list.size()>0) {				
				for(SlmOrderInfo orders:list){
					orders.setUnshipped_bill_weight(DoubleUtil.round(orders.getUnshipped_bill_weight()/1000,DoubleUtil.DEF_DIV_SCALE));
					String orderNo=orders.getContract_no()+orders.getContract_line_seq()+orders.getOrder_seq();
					orders.setOrder_no(orderNo);
				}
			}
			rm.setData(list);
			rm.setMsgInfo("获取可发重量成功");
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
//
//	/**
//	 * 为提单查询-new version 
//	 * order by 未发量
//	 * */
//	public ResultModel doQueryForBillWeb(CommonPage<SlmLadingBillHeat> sum){
//		ResultModel rm=new ResultModel();
//		SlmLadingBillHeat heat=sum.getObject();
//		int pageIndex=sum.getPageIndex();
//		int pageSize=sum.getPageSize();
//		String order_no=sum.getMemo1();
//		List<SlmOrderInfo> list = new ArrayList<SlmOrderInfo>();
//		int count;
//		String sType=sum.getMemo6()==null?"":sum.getMemo6(); // 为1则是火运
//		PageModel<SlmOrderInfo> pm=new PageModel<SlmOrderInfo>(pageIndex, pageSize);
//		try{
//			
//			if(!"1".equals(sType)){
//				SlmOrderInfo order=new SlmOrderInfo();
//				order.setCustomer_no(heat.getCustomer_no());
//				order.setReciver_unit_no(heat.getReciver_unit_no());
//				order.setContract_no(heat.getContract_no());
//				if(order_no!=null&&!"".equals(order_no)){
//					String contract_no=order_no.substring(0,order_no.length()-6);
//					String line_seq=order_no.substring(order_no.length()-6,order_no.length()-3);
//					String order_seq=order_no.substring(order_no.length()-3);
//					order.setContract_no(contract_no);
//					order.setContract_line_seq(line_seq);
//					order.setOrder_seq(order_seq);
//				}
//				order.setValid_flag("1");
//				//订单状态为未结算、未关闭状态 【后续添加
//				List<SlmOrderInfo> order_no_list=this.getMapper(SlmOrderInfoMapper.class).doQueryYdm();
//				String order_no_sum=" and o.order_no in (";
//				if(order_no_list.size()>0){
//					for(SlmOrderInfo orders:order_no_list){
//						order_no_sum+="'"+orders.getOrder_no()+"',";
//					}
//					order_no_sum=order_no_sum.substring(0,order_no_sum.length()-1);
//					order_no_sum+=")";
//				}else{
//					order_no_sum=null;
//				}
//				
//				list=this.getMapper(SlmOrderInfoMapper.class).doQueryForBill(order,order_no_sum,(pageIndex-1)*pageSize, pageIndex*pageSize);
//				count=this.getMapper(SlmOrderInfoMapper.class).doQueryForBillCount(order,order_no_sum);
//				//			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).doQueryForBill(order,(pageIndex-1)*pageSize, pageIndex*pageSize);
//				//			int count=this.getMapper(SlmOrderInfoMapper.class).doQueryForBillCount(order);
//				
//				for(SlmOrderInfo orders:list){
//					orders.setTotal_bill_weight(DoubleUtil.round(orders.getTotal_bill_weight(),DoubleUtil.DEF_DIV_SCALE));
//					orders.setUnshipped_bill_weight(DoubleUtil.round(orders.getUnshipped_bill_weight()/1000,DoubleUtil.DEF_DIV_SCALE));
//					orders.setUndisposed_bill_weight(DoubleUtil.sub(orders.getEstimate_weight(), orders.getTotal_bill_weight()));
//					String orderNo=orders.getContract_no()+orders.getContract_line_seq()+orders.getOrder_seq();
//					orders.setOrder_no(orderNo);
//				}
//			}
//			else{
//				list = this.getMapper(SlmOrderInfoMapper.class).doQueryForTranBill(heat);
//				count=this.getMapper(SlmOrderInfoMapper.class).doQueryForTranBillCount(heat);
//			}
//			pm.setRows(list);
//			pm.setTotal(count);
//			rm.setData(pm);
//			rm.setState("200");
//		}catch(Exception ex){
//			rm.setState("500");
//			rm.setMsgInfo("查询失败"+ex.getMessage());
//			ex.printStackTrace();
//		}
//		return rm;
//	}
	/**
	 * 判断合同行下是否存在有效订单
	 * memo1传合同行号
	 * */
	public boolean doQueryOrderWeb(CommonPage<SlmOrderInfo> sum){
		SlmOrderInfo order=new SlmOrderInfo();
		order.setContract_line_no(sum.getMemo1());
		order.setValid_flag("1");
		int count=this.getMapper(SlmOrderInfoMapper.class).count(order);
		if(count>0)
			return false;
		return true;
	}

	/**
	 * 给合同跟踪查看排产量时 调用
	 * */
	public ResultModel doQueryForContractWeb(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		try{
			String sWhere=" 1=1 ";
			sWhere+=" and order_flag_no in('103407','103408','103409')";
			order.setValid_flag("1");
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, sWhere, " create_time desc", 0, 0);
			for(SlmOrderInfo orders:list){		//从合同行里查询规格
				SlmContractLineInfo line=new SlmContractLineInfo();
				if(orders.getContract_no()!=null&&!"".equals(orders.getContract_no())){
					line.setContract_no(orders.getContract_no());
					line.setContract_line_seq(orders.getContract_line_seq());
				}else{
					line.setContract_line_no(orders.getContract_line_no());
				}
				List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).find(line, 0, 0);
				if(lineList.size()>0){
					orders.setWidth(lineList.get(0).getWidth());
					orders.setLength(lineList.get(0).getLength());
					orders.setThick(lineList.get(0).getThick());
				}
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 订单跟踪
	 * */
	public ResultModel doQueryTrackWeb(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();			//合同签订时间
		try{
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).doQueryTrack(order, startTime,endTime);
			rm.setData(list);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	private ResultModel doQueryWeightLimit(SlmOrderInfo order){
		ResultModel rm=new ResultModel();
		rm.setState("200");
		//重量判断
		SlmContractLineInfo line=this.getMapper(SlmContractLineInfoMapper.class).findById(order.getContract_line_no());
		if(line==null){
			rm.setState("500");
			rm.setMsgInfo("合同行数据丢失，请联系管理员");
			return rm;
		}
		SlmOrderInfo Sorder=new SlmOrderInfo();
		Sorder.setContract_line_seq(order.getContract_line_seq());
		if(order.getContract_no()!=null&&!"".equals(order.getContract_no()))
			Sorder.setContract_no(order.getContract_no());
		else
			Sorder.setContract_pk(order.getContract_pk());
		List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(Sorder, null, null, 0, 0);
		Double material_total=0d;	//原料卷总重
		Double work_total=0d;		//加工总重
		Double cool_total=0d;       //冷轧总重
		Double scour_total=0d;      //酸洗总重
		Double unplan_total=0d;		//非计划总重
		Double max_total=0d;        //最大重量

		for(SlmOrderInfo orders:orderList){
			//原料卷
			if("1".equals(orders.getOrder_nature())){
				material_total=DoubleUtil.add(material_total,orders.getEstimate_weight());
				max_total=Math.max(material_total, max_total);
			}
			//需加工
			if("2".equals(orders.getOrder_nature())){
				work_total=DoubleUtil.add(orders.getEstimate_weight(),work_total);
				max_total=Math.max(work_total, max_total);
			}
			//非计划
			if("3".equals(orders.getOrder_nature())){
				unplan_total=DoubleUtil.add(orders.getEstimate_weight(),unplan_total);
			}
			//冷轧
			if("4".equals(orders.getOrder_nature())){
				cool_total=DoubleUtil.add(orders.getEstimate_weight(),cool_total);
				max_total=Math.max(cool_total, max_total);
			}
			//酸洗
			if("5".equals(orders.getOrder_nature())){
				scour_total=DoubleUtil.add(orders.getEstimate_weight(),scour_total);
				max_total=Math.max(scour_total, max_total);
			}
		}
		//合同行交货量上限-非计划
		Double permit_total=DoubleUtil.sub(line.getDelivery_error_max(),unplan_total);
		//原料卷
		if("1".equals(order.getOrder_nature())){
			permit_total=DoubleUtil.sub(permit_total,material_total);
			if(permit_total<=0){
				rm.setState("500");
				rm.setMsgInfo("该合同行下重量已满额，无法新增订单");
				return rm;
			}
			if(order.getEstimate_weight()>permit_total){
				rm.setState("500");
				rm.setMsgInfo("订单重量数值不得超过"+permit_total);
				return rm;
			}
		}
		//需加工
		if("2".equals(order.getOrder_nature())){
			permit_total=DoubleUtil.sub(permit_total,work_total);
			if(permit_total<=0){
				rm.setState("500");
				rm.setMsgInfo("该合同行下重量已满额，无法新增订单");
				return rm;
			}
			if(order.getEstimate_weight()>permit_total){
				rm.setState("500");
				rm.setMsgInfo("订单重量数值不得超过"+permit_total);
				return rm;
			}
		}
		//非计划
		if("3".equals(order.getOrder_nature())){
			permit_total=DoubleUtil.sub(permit_total,unplan_total);
			if(permit_total<=0){
				rm.setState("500");
				rm.setMsgInfo("该合同行下重量已满额，无法新增订单");
				return rm;
			}
			if(order.getEstimate_weight()>permit_total){
				rm.setState("500");
				rm.setMsgInfo("订单重量数值不得超过"+permit_total);
				return rm;
			}
		}
		//冷轧
		if("4".equals(order.getOrder_nature())){
			permit_total=DoubleUtil.sub(permit_total,cool_total);
			if(permit_total<=0){
				rm.setState("500");
				rm.setMsgInfo("该合同行下重量已满额，无法新增订单");
				return rm;
			}
			if(order.getEstimate_weight()>permit_total){
				rm.setState("500");
				rm.setMsgInfo("订单重量数值不得超过"+permit_total);
				return rm;
			}
		}
		//酸洗
		if("5".equals(order.getOrder_nature())){
			permit_total=DoubleUtil.sub(permit_total,scour_total);
			if(permit_total<=0){
				rm.setState("500");
				rm.setMsgInfo("该合同行下重量已满额，无法新增订单");
				return rm;
			}
			if(order.getEstimate_weight()>permit_total){
				rm.setState("500");
				rm.setMsgInfo("订单重量数值不得超过"+permit_total);
				return rm;
			}
		}
		rm.setData(permit_total);
		return rm;
	}

	/***
	 * 订单变更，生成新订单（修改主键）
	 * 老订单状态改为变更无效
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doChangeWeb(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo old=sum.getObject();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			old=this.getMapper(SlmOrderInfoMapper.class).findById(old.getOrder_no());
			if(old==null){
				rm.setState("500");
				rm.setMsgInfo("订单号有误，请检查参数");
				return rm;
			}
			//检验申报状态
			List<SlmOrderChangeApply> apply_list=this.getMapper(SlmOrderChangeApplyMapper.class).findWithCondition(null, " order_no='"+old.getOrder_no()+"' and valid_flag='1' and status='3'"," create_time desc",0,0);
			if(apply_list.size()<1){
				rm.setState("500");
				rm.setMsgInfo("该订单未申请变更通过或已变更");
				return rm;
			}else{
				apply_list.get(0).setStatus("5"); 		//已变更
				this.getMapper(SlmOrderChangeApplyMapper.class).update(apply_list.get(0));
			}
			//旧订单变更为无效
			old.setChange_flag("1");
			this.getMapper(SlmOrderInfoMapper.class).update(old);
			//新增一条订单（变更有效）
			int count=this.getMapper(SlmOrderInfoMapper.class).countWithCondition(null, " order_no like '%"+old.getOrder_no()+"B%'")+1;
			String newOrderNo=old.getOrder_no();
			if(newOrderNo.length()>=20) newOrderNo=newOrderNo.substring(0,20);
			newOrderNo+="B"+String.format("%03d", count);
			old.setOrder_no(newOrderNo);
			old.setChange_flag("3"); 			//变更有效
			old.setCreate_time(new Date());
			old.setCreate_man_no(userId);
			old.setCreate_man_name(userName);
			old.setOrder_flag_no("103401");
			old.setOrder_flag_name("编辑");
			old.setProcess(null);
			this.getMapper(SlmOrderInfoMapper.class).insert(old);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/***
	 * 订单拆分，生成多条新订单（订单序号往上累加） 
	 * 旧订单重量瓜分，新订单修改工艺路径，重量，加工费
	 * 需判断生产是否满足需求
	 * [{"memo1":"order_no"}]
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSplitWeb(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String order_no=sum.getMemo1();
		try{
			SlmOrderInfo old=this.getMapper(SlmOrderInfoMapper.class).findById(order_no);
			if(old==null) 	throw new Exception("订单号有误，请检查参数");
			if(old.getContract_no()==null) throw new Exception("订单未生效");
			// ========2019-06-14 eason add==========
			SlmOrderChangeApply soca=new SlmOrderChangeApply();
			soca.setOrder_no(order_no);
			soca.setValid_flag("1");
			int icount=this.getMapper(SlmOrderChangeApplyMapper.class).count(soca);
			if(icount>0){
				throw new Exception("变更订单无法进行拆分操作");
			}
			// ============================
			
			SlmOrderSplitInfo split=new SlmOrderSplitInfo();
			split.setOrder_no(order_no);
			// ================2019-06-22 eason add===============
			split.setStatus("0");
			// ==================================================
			split.setValid_flag("1");
			List<SlmOrderSplitInfo> split_list=this.getMapper(SlmOrderSplitInfoMapper.class).findWithCondition(split, null, " id", 0, 0); 
			//验证 
			double total_weight=0d;
			double old_weight=old.getEstimate_weight();
			for(SlmOrderSplitInfo splits:split_list){
				total_weight=DoubleUtil.add(splits.getEstimate_weight(), total_weight);
			}
			if(total_weight>old_weight) 	throw new Exception("拆分总重量["+total_weight+"]不得大于原来订单的重量["+old_weight+"]");
			//调用生产接口，判断质量是否允许
			double param_weight=total_weight;
			if(total_weight==old_weight) param_weight=0d;
			boolean can=true;
			try{
				can=this.getBean(MesApiDesignInfoImpl.class).cib_Split(order_no,param_weight);
			}catch(Exception e){
				throw new Exception("生产未完成当前所需拆分重量["+total_weight+"]");
			}
			if(!can) throw new Exception("生产未完成当前所需拆分重量["+total_weight+"]");
			//查询最大的订单序号
			String seq="002";
			List<SlmOrderInfo> seq_list=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, "contract_no='"+old.getContract_no()+"' and contract_line_seq='"+old.getContract_line_seq()+"'", " order_seq desc", 0, 0);
			if(seq_list.size()>0) seq=seq_list.get(0).getOrder_seq();
			int int_seq=Integer.parseInt(seq);
			for(SlmOrderSplitInfo orders:split_list){
				int_seq++;
				old.setP_order_no(orders.getOrder_no());
				old.setOrder_seq(String.format("%03d", int_seq));
				String new_order_no=old.getContract_line_no()+old.getOrder_seq();
				old.setOrder_no(new_order_no);
				old.setProcess(orders.getProcess_desc());
				old.setEstimate_weight(orders.getEstimate_weight());
				old.setWork_price(orders.getWork_price());
				//===============2019-06-22 eason add===============
				old.setTrade_price(orders.getTrade_price());
				old.setProcess_price(orders.getProcess_price());
				//=================================================
				old.setCreate_man_no(userId);
				old.setCreate_man_name(userName);
				old.setCreate_time(new Date());
				old.setOrder_flag_no("103401");
				old.setOrder_flag_name("编辑");
				old.setChange_flag(null);
				old.setIs_split("1");
				this.getMapper(SlmOrderInfoMapper.class).insert(old);
				//插入工艺要求数据
				List<ComBaseStation> station_list=this.getMapper(ComBaseStationMapper.class).findWithCondition(null, "PROCESS_POINT_TYPE='403206' and process_desc='"+orders.getProcess_desc()+"'", null, 0,0);
				ComBaseStation base=new ComBaseStation();
				if(station_list.size()>0){
					base=station_list.get(0);
					SlmContractBaseStation station=geneteStation(base,old,new_order_no);
					this.getMapper(SlmContractBaseStationMapper.class).insert(station);
				}
				//拆分信息标为已拆分
				orders.setStatus("1");
				orders.setOrder_no_child(new_order_no);
				this.getMapper(SlmOrderSplitInfoMapper.class).update(orders);
			}
			//原订单重量削减
			SlmOrderInfo param=new SlmOrderInfo();
			param.setOrder_no(order_no);
			param.setIs_split("1");
			param.setEstimate_weight(DoubleUtil.sub(old_weight, total_weight));
			this.getMapper(SlmOrderInfoMapper.class).update(param);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 导入拆分订单
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doImportSplitWeb() throws Exception{
		ResultModel rm=new ResultModel();
		Workbook wb=null;
		try{
			URL url = this.getClass().getClassLoader().getResource("/");
			// 替换路径中的空格
			String filePath = url.getPath().replaceAll("%20", " ");
			File file = new File(filePath);
//												 file = new File("D:/file/订单拆分导入表.xls");
//												 wb = new HSSFWorkbook(new FileInputStream(file));
			List<FileItem> items = ImportUtil.getUpload(SlmOrderInfoServiceImpl.this,file,getRequest());			
			for (FileItem item : items) {
				// 若是文件域则读取文件流
				if (!item.isFormField()) {
					wb = ImportUtil.getWB(item, file.length());
				}
			}
			String cell0,cell1,cell2,cell3,cell4,cell5,cell6;
			Sheet sheet=wb.getSheetAt(0);
			int num=1;
			SlmOrderInfo param=new SlmOrderInfo();
			List<SlmOrderSplitInfo> list=new ArrayList<SlmOrderSplitInfo>();
			while (true) {
				Row row = sheet.getRow(num);
				num++;

				cell0=((int)Double.parseDouble(ImportUtil.getCellValue(row.getCell(0))))+"";		//序号
				cell1=ImportUtil.getCellValue(row.getCell(1));		//合同号
				cell2=ImportUtil.getCellValue(row.getCell(2));		//合同号序号
				cell3=ImportUtil.getCellValue(row.getCell(3));		//订单序号
				cell4=ImportUtil.getCellValue(row.getCell(4));		//工艺要求
				cell5=ImportUtil.getCellValue(row.getCell(5));		//数量
				cell6=ImportUtil.getCellValue(row.getCell(6));		//加工配送费
//				cell7=ImportUtil.getCellValue(row.getCell(7));		//
				if("".equals(cell0)) break;

				SlmOrderSplitInfo split=new SlmOrderSplitInfo();

				param.setContract_no(cell1);
				param.setContract_line_seq(cell2);
				param.setOrder_seq(cell3);
				param.setValid_flag("1");
				List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(param, 0, 0);
				if(order_list.size()<1){
					rm.setState("500");
					rm.setMsgInfo("第"+cell0+"条未找到对应的有效订单");
					wb.close(); 
					return rm;
				}else if(order_list.size()>1){
					split.setOrder_no(order_list.get(0).getOrder_no());
					for(SlmOrderInfo orders:order_list){			//变更有效的
						if("3".equals(orders.getChange_flag())){
							split.setOrder_no(orders.getOrder_no());
							break;							
						}
					}
				}else{
					split.setOrder_no(order_list.get(0).getOrder_no());
				}
				if(split.getOrder_no().contains("-")) throw new Exception("第"+cell0+"条订单是拆分订单，不允许再次拆分");
				//工艺要求检测
				List<ComBaseStation> station_list=this.getMapper(ComBaseStationMapper.class).findWithCondition(null, "PROCESS_POINT_TYPE='403206' and process_desc='"+cell4+"'", null, 0,0);
				if(station_list.size()<1){			
					rm.setState("500");
					rm.setMsgInfo("第"+cell0+"条未找到对应的工艺要求");
					wb.close(); 
					return rm;
				}else{
					split.setProcess_code(station_list.get(0).getProcess_code());
					split.setProcess_desc(station_list.get(0).getProcess_desc());
				}
				//重量检测
				try{
					double weight=Double.parseDouble(cell5);
					if(weight>0){
						split.setEstimate_weight(weight);
					}else{
						throw new Exception();
					}
				}catch(Exception e){
					rm.setState("500");
					rm.setMsgInfo("第"+cell0+"条未输入正确的数量");
					wb.close(); 
					return rm;
				}
				//加工费检测
				try{
					double price=Double.parseDouble(cell6);
					if(price>0){
						split.setWork_price(price);
					}else{
						throw new Exception();
					}
				}catch(Exception e){
					rm.setState("500");
					rm.setMsgInfo("第"+cell0+"条未输入正确的数量");
					wb.close(); 
					return rm;
				}
				list.add(split);
			}
			//验证完毕
			CommonPage<SlmOrderSplitInfo> split_sum=new CommonPage<SlmOrderSplitInfo>();
			Set<String> order_set=new HashSet<String>();
			for(SlmOrderSplitInfo splits:list){
				split_sum.setObject(splits);
				this.getBean(SlmOrderSplitInfoServiceImpl.class).doAddWeb(split_sum);
				order_set.add(splits.getOrder_no());
			}
			//执行拆分
			CommonPage<SlmOrderInfo> order_sum=new CommonPage<SlmOrderInfo>();
			for(String order_no:order_set){
				order_sum.setMemo1(order_no);
				rm=doSplitWeb(order_sum);
				if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
			}
			wb.close(); 
			rm.setState("200");
			rm.setMsgInfo("导入成功");
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	//------------------逻辑方法-------------------------------------------------
	public List<SlmOrderInfo> doQueryWithCondition(SlmOrderInfo line,String sWhere,String sOrder,int pageIndex,int pageSize){
		List<SlmOrderInfo> heatList=this.getMapper(SlmOrderInfoMapper.class).findWithCondition(line, sWhere, sOrder, pageIndex, pageSize);
		return heatList;
	}
	public void doUpdate(SlmOrderInfo line){
		this.getMapper(SlmOrderInfoMapper.class).update(line);
	}

	public List<SlmOrderInfo> doQuery(SlmOrderInfo orderNo) {
		return this.getMapper(SlmOrderInfoMapper.class).find(orderNo,0,0);
	}

	public SlmOrderInfo doQueryOne(String id) {
		return this.getMapper(SlmOrderInfoMapper.class).findById(id);
	}

	public ResultModel doDelete(SlmOrderInfo order){
		ResultModel rm=new ResultModel();
		try{
			this.getMapper(SlmOrderInfoMapper.class).doDelete(order);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	//合同号 与 采购合同号 验证
	private boolean checkContract_no(String contract_no,String purchase){
		boolean pass=true;
		if(contract_no==null||"".equals(contract_no)) return false;
		if(purchase!=null&&!"".equals(purchase)){
			purchase=purchase.trim();
			if(contract_no.contains(purchase)){
				return pass;
			}else{
				return false;
			}
		}
		return pass;
	}

	public CommonPage<SlmContractProcessPlan> generateParam(SlmOrderInfo order, List<SlmProcessPlan> plan_list) {
		CommonPage<SlmContractProcessPlan> sum=new CommonPage<SlmContractProcessPlan>();
		List<SlmContractProcessPlan> list=new ArrayList<SlmContractProcessPlan>();
		SlmContractLineInfo line=this.getMapper(SlmContractLineInfoMapper.class).findById(order.getContract_line_no());
		for(SlmProcessPlan plans:plan_list){
			SlmContractProcessPlan pplan=new SlmContractProcessPlan();
			pplan.setIs_auto("1");
			pplan.setContract_line_no(plans.getPlan_no()); 			//contract_line_no放plan_no
			pplan.setMsc(order.getMsc());
			pplan.setMsc_desc(order.getMsc_desc());
			pplan.setPsc(order.getPsc());
			pplan.setPsc_desc(order.getPsc_desc());
			pplan.setMsc_type_no(order.getMsc_type_no());
			pplan.setProd_code(order.getProd_code());
			pplan.setProd_name(order.getProd_name());
			pplan.setStd_code(order.getStd_code());
			pplan.setStd_name(order.getStd_name());
			pplan.setSteel_code(order.getSteel_code());
			pplan.setSteel_name(order.getSteel_name());
			pplan.setThick(plans.getThick());
			pplan.setWidth(plans.getWidth());
			pplan.setLength(plans.getLen());
			pplan.setUser_no(order.getUser_no());
			pplan.setUser_name(order.getUser_name());
			pplan.setAdd_ask_no(order.getAdd_ask_no());
			pplan.setCustomer_alpha_no(order.getCustomer_alpha_no());
			pplan.setDelivery_state_code(order.getDelivery_state_code());
			pplan.setDelivery_state_desc(order.getDelivery_state_desc());
			if(order.getPrecisicon_type_code()!=null)
				pplan.setH_precisicon_type_code(order.getPrecisicon_type_code());
			if(order.getPrecisicon_type_desc()!=null)
				pplan.setH_precisicon_type_desc(order.getPrecisicon_type_desc());
			pplan.setUser_no(order.getUser_no());
			pplan.setUser_name(order.getUser_name());
			if(line!=null){
				if(pplan.getUser_no()==null)
					pplan.setUser_no(line.getUser_no());
				if(pplan.getUser_name()==null)
					pplan.setUser_name(line.getUser_name());
				pplan.setCut_edge_type_code(line.getCut_edge_type_no());
				pplan.setCut_edge_type_name(line.getCut_edge_type_name());
			}
			//			SlmCustAlphaPhy phy=new SlmCustAlphaPhy();
			//			phy.setValidflag("1");
			//			phy.setCust_alpha_no(line.getCustomer_alpha_no());
			//			List<SlmCustAlphaPhy> phy_list=this.getMapper(SlmCustAlphaPhyMapper.class).find(phy,0,0);
			//			if(phy_list.size()>0){
			//				phy=phy_list.get(0);
			//				pplan.setPhy_type(phy.getPhy_type());
			//			}
			//			SlmContractLineInfo line=this.getMapper(SlmContractLineInfoMapper.class).findById(order.getContract_line_no());
			//			if(line!=null){
			//				SlmCustAlphaSpec spec=new SlmCustAlphaSpec();
			//				spec.setCust_alpha_no(line.getCustomer_alpha_no());
			//				List<SlmCustAlphaSpec> spec_list=this.getMapper(SlmCustAlphaSpecMapper.class).find(spec,0,0);
			//				if(spec_list.size()>0){
			//					spec=spec_list.get(0);
			//				}
			//			}
			list.add(pplan);
		}
		sum.setObjectList(list);
		return sum;
	}

	/**
	 * 订单-加工计划-导入
	 * */
	@SuppressWarnings("deprecation")
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doImportWeb() throws Exception{
		ResultModel rm=new ResultModel();
		String rownum="";
		Workbook wb=null;
		try{
			URL url = this.getClass().getClassLoader().getResource("/");
			// 替换路径中的空格
			String filePath = url.getPath().replaceAll("%20", " ");
			File file = new File(filePath);
			List<FileItem> items = ImportUtil.getUpload(SlmOrderInfoServiceImpl.this,file,getRequest());			
			for (FileItem item : items) {
				// 若是文件域则读取文件流
				if (!item.isFormField()) {
					wb = ImportUtil.getWB(item, file.length());
				}
			}
			String cell0,cell2,cell3,cell4,cell5,cell6,cell7,cell8,cell9,cell10,cell11,cell12,cell13,cell14,cell15,cell16,cell17,cell18,cell19,cell20,cell21,cell22;
			Sheet sheet=wb.getSheetAt(0);
			//验证数据合法性，全部合格才新增	
			List<SlmOrderInfo> order_list=new ArrayList<SlmOrderInfo>();
			SlmOrderInfo order=new SlmOrderInfo();
			SlmProcessPlan plan=new SlmProcessPlan();
			int count = sheet.getLastRowNum();

			String temp_contract_no="";
			String temp_spec="";
			String temp_formula="";
			String temp_steel_name="";
			//合同号 规格 分切公式 牌号一致时，合并重量及卷号

			int order_num=1;
			String same="0";
			while (order_num<=count) {
				Row row = sheet.getRow(order_num);
				order_num++;
				
				cell0=((int)Double.parseDouble(ImportUtil.getCellValue(row.getCell(0))))+"";		//序号
				//cell1=ImportUtil.getCellValue(row.getCell(1));		//客户名称
				//==============eason 2019-08-20 add 增加判断牌号针对牌号为数值的情况做处理===================
				row.getCell(2).setCellType(HSSFCell.CELL_TYPE_STRING);
				//==========================================================================================
				cell2=ImportUtil.getCellValue(row.getCell(2));		//牌号
				cell3=ImportUtil.getCellValue(row.getCell(3));		//规格
				cell4=ImportUtil.getCellValue(row.getCell(4));		//数量
				cell5=ImportUtil.getCellValue(row.getCell(5));		//钢卷号
				cell6=ImportUtil.getCellValue(row.getCell(6));		//销售合同号
				//==============eason 2019-08-20 add 增加判断牌号针对牌号为数值的情况做处理===================
				row.getCell(7).setCellType(HSSFCell.CELL_TYPE_STRING);
				//==========================================================================================
				cell7=ImportUtil.getCellValue(row.getCell(7));		//采购合同号
				cell8=ImportUtil.getCellValue(row.getCell(8));		//运输方案
				cell9=ImportUtil.getCellValue(row.getCell(9));		//订单备注
				cell10=ImportUtil.getCellValue(row.getCell(10));		//加工尺寸
				cell11=ImportUtil.getCellValue(row.getCell(11));		//出厂价
				cell12=ImportUtil.getCellValue(row.getCell(12));		//加工价
				//==============eason 2019-07-05 add 增加一列===================
				cell13=ImportUtil.getCellValue(row.getCell(13));		//配送价
				cell14=ImportUtil.getCellValue(row.getCell(14));		//分切方式
				cell15=ImportUtil.getCellValue(row.getCell(15));		//工艺要求
				cell16=ImportUtil.getCellValue(row.getCell(16));		//整卷发运
				//=================================================================
				// 订单导入增加原料卷，酸洗，冷轧订单导入：2023031301 刘侣
				cell17=ImportUtil.getCellValue(row.getCell(17));		//订单属性
				cell18=ImportUtil.getCellValue(row.getCell(18));		//内径要求
				cell19=ImportUtil.getCellValue(row.getCell(19));		//表面等级
				cell20=ImportUtil.getCellValue(row.getCell(20));		//是否涂油
				cell21=ImportUtil.getCellValue(row.getCell(21));		//是否切边
				cell22=ImportUtil.getCellValue(row.getCell(22));		//计重方式
				// end
				
				rownum=cell0;  		//记录错误条数序号
				logger.info("virshow|"+cell4);
				//与上一条一致：合同号，规格，加工尺寸，牌号
				if(temp_contract_no.equals(cell6)&&temp_spec.equals(cell3)
						&&temp_formula.equals(cell10)&&temp_steel_name.equals(cell2)){
					same="1";
				}else{
					temp_contract_no=cell6;
					temp_spec=cell3;
					temp_formula=cell10;
					temp_steel_name=cell2;
					same="0";
				}

				if("".equals(cell2)&&"".equals(cell3)&&"".equals(cell4)&&"".equals(cell5)&&"".equals(cell6)){
					same="0";
					continue;
				}
				if("".equals(cell3)){
					rm.setState("500");
					rm.setMsgInfo("第"+rownum+"条数据规格未填写，请检查数据");
					wb.close(); 
					return rm;
				}
				double thick=Double.parseDouble(cell3.split("\\*")[0]);
				double width=Double.parseDouble(cell3.split("\\*")[1]);
				String steel_name=cell2;
				String contract_no=cell6;
				//处理牌号中的#号
				if(steel_name.contains("#"))
					steel_name=steel_name.replaceAll("#", "");
				//寻找对应的合同行及订单
				SlmContractLineInfo line=new SlmContractLineInfo();
				line.setContract_no(contract_no);
				line.setSteel_name(steel_name);
				line.setThick(thick);
				line.setWidth(width);
				line.setValid_flag("1");
				List<SlmContractLineInfo> line_list=this.getMapper(SlmContractLineInfoMapper.class).find(line,0,0);
				if(line_list.size()<1){
					rm.setState("500");
					rm.setMsgInfo("第"+cell0+"条数据未找到对应的合同行，请检查数据或手工输入");
					wb.close(); 
					return rm;
				}else if(line_list.size()>1){
					line=line_list.get(0);
					SlmOrderInfo order_param=new SlmOrderInfo();
					if(line.getPrecisicon_type_code()==null||line.getPrecisicon_type_code().equals("")){
						order.setPrecisicon_type_code("411205");
						order.setPrecisicon_type_desc("PT.A");
					}else{
						order.setLv_code(line.getLv_code());
						order.setLv_desc(line.getLv_desc());
						order.setPrecisicon_type_code(line.getPrecisicon_type_code());
						order.setPrecisicon_type_desc(line.getPrecisicon_type_desc());
					}
					order.setPk_ask_code(line.getPk_ask_code());
					order.setPk_ask_desc(line.getPk_ask_desc());
					for(SlmContractLineInfo lines:line_list){
						order_param.setContract_line_no(lines.getContract_line_no());
						order_param.setValid_flag("1");
						List<SlmOrderInfo> temp_order_list=this.getMapper(SlmOrderInfoMapper.class).find(order_param, 0, 0);
						double order_total=0d;
						for(SlmOrderInfo orders:temp_order_list){
							order_total=DoubleUtil.add(order_total, orders.getEstimate_weight());
						}
						if(DoubleUtil.add(order_total,Double.parseDouble(cell4))<=lines.getEstimate_weight()){
							line=lines;
						}
					}
				}else{
					line=line_list.get(0);
				}
				SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(line.getContract_pk());
				SlmCustomerTransSolution solution=new SlmCustomerTransSolution();
				if(heat!=null){
					solution.setCustomer_no(heat.getCustomer_no());
				}
				//查找运输方案
				solution.setSolutions_name(cell8);
				solution.setValid_flag("1");
				List<SlmCustomerTransSolution> solution_list=this.getMapper(SlmCustomerTransSolutionMapper.class).find(solution, 0, 0);
				if(solution_list.size()<1){
					rm.setState("500");
					rm.setMsgInfo("第"+cell0+"条数据未找到运输方案，请检查数据或手工输入");
					wb.close(); 
					return rm;
				}
				solution=solution_list.get(0);
				//合同号与采购合同号验证
				if(!checkContract_no(cell6, cell7)){
					rm.setState("500");
					rm.setMsgInfo("第"+cell0+"条数据销售合同号与采购合同号有误，请检查数据");
					wb.close(); 
					return rm;
				}
				//组装数据 一行对应一条订单
				order=new SlmOrderInfo();
				order.setColour(same); 		//是否与上一条一致0否 1是
				order.setHave_plan(cell0); 			//序号
				order.setEstimate_weight(Double.parseDouble(cell4));   //重量
				if(!"".equals(cell11)){
					order.setBalance_price(Double.parseDouble(cell11)); 		//结算价
					order.setOut_price(Double.parseDouble(cell11)); 		//出厂价
				}
				//==================eason add 2019-07-05========================
				double dbWorkPrice=0d;
				if(!"".equals(cell12)){
					dbWorkPrice+=Double.parseDouble(cell12);
					order.setProcess_price(Double.parseDouble(cell12));
				}
				if(!"".equals(cell13)){
					dbWorkPrice+=Double.parseDouble(cell13);
					order.setTrade_price(Double.parseDouble(cell13));
				}
				order.setWork_price(dbWorkPrice);  		//加工配送费
				//===============================================================
				order.setMemo(cell9);   		//订单备注
				order.setContract_no(cell6);  			//合同号
				order.setPurchase_contract_no(cell7);  		//采购合同号
				order.setProcess(cell15);  		//工艺要求
				order.setWhole_coil("0");
				if(cell16!=null&&(cell16.contains("是")||cell16.contains("1")))
					order.setWhole_coil("1");
				
				// 增加酸洗（5），冷轧（4），原料卷订单（1）的数据：
				if (cell17 != null && ("酸洗".equals(cell17) || "冷轧".equals(cell17) || "原料卷".equals(cell17))) {
					// 那么是否涂油，是否切边，内径要求和表面等级不可缺少：
					if (cell18 == null || cell19 == null || cell20 == null || cell21 == null || cell22 == null) {
						rm.setState("500");
						rm.setMsgInfo("第"+cell0+"条数据是否涂油，是否切边，内径要求，表面等级或者计重方式存在数据缺失，请检查数据；");
						wb.close(); 
						return rm;
					}
					order.setIs_oil("是".equals(cell20) ? "1" : "0");
					order.setIs_side_cute("是".equals(cell21) ? "1" : "0");
					order.setIndia_require(cell18); // 内径要求
					ComBaseInfo cbi = new ComBaseInfo();
					cbi.setSort_code("411101");
					cbi.setBase_name(cell19);
					List<ComBaseInfo> cbis = this.getMapper(ComBaseInfoMapper.class).find(cbi, 0, 1);
					if (cbis.size() == 0) {
						rm.setState("500");
						rm.setMsgInfo("第"+cell0+"数据的表面等级：" + cell19 + " 编码未查询到；");
						wb.close(); 
						return rm;
					}
					order.setLevel_code(cbis.get(0).getBase_code());
					order.setLevel_name(cbis.get(0).getBase_name());
					order.setOrder_nature("酸洗".equals(cell17) ? "5" : "冷轧".equals(cell17) ? "4" : "1");
					order.setWeight_type_no("净重".equals(cell22) ? "102301" : "毛重".equals(cell22) ? "102302" : "");
					order.setWeight_type_name("净重".equals(cell22) ? "净重" : "毛重".equals(cell22) ? "毛重" : "");
				}
				// end
				
				order=setOrderParam(order,line_list.get(0),solution,heat,cell17);			//组装订单数据
				//加工计划
				plan=new SlmProcessPlan();
				
				// 非需加工订单，加工尺寸不用填：20230315 刘侣
				if ("2".equals(order.getOrder_nature())) {
					//加工尺寸检验 是否能识别
					ResultModel plan_rm=this.getBean(SlmProcessPlanServiceImpl.class).analysisFormula(cell10);
					if("500".equals(plan_rm.getState())){
						rm.setState("500");
						rm.setMsgInfo("第"+cell0+"条数据加工尺寸无法识别，请检查数据");
						wb.close(); 
						return rm;
					}
					plan.setCrosscut_stype(plan_rm.getMsgInfo());
					plan.setCustomer_alpha_desc((String) plan_rm.getData());
				}
				// end
				
				plan.setMemo(cell5);    		//备注/钢卷号
				plan.setPurchase_contract_no(cell7); 			//采购合同号
				plan.setCut_type(cell14);			//分切方式
				order.setPlan(plan);
				order_list.add(order);
			}

			Date create_time=new Date();
			//数据验证合格，新增
			CommonPage<SlmOrderInfo> order_sum=new CommonPage<SlmOrderInfo>();
			SlmOrderInfo	re_order=new SlmOrderInfo();
			SlmOrderInfo	orders=new SlmOrderInfo();
			int len=order_list.size();
			for(int x=0;x<len;x++){
				if("1".equals(order_list.get(x).getColour())){			//与上一条一致
					re_order.setEstimate_weight(DoubleUtil.add(re_order.getEstimate_weight(),order_list.get(x).getEstimate_weight()));
					this.getMapper(SlmOrderInfoMapper.class).update(re_order);
					SlmProcessPlan param_plan=new SlmProcessPlan();
					param_plan.setContract_no(re_order.getContract_no());
					param_plan.setContract_line_seq(re_order.getContract_line_seq());
					param_plan.setOrder_seq(re_order.getOrder_seq());
					List<SlmProcessPlan> plan_list=this.getMapper(SlmProcessPlanMapper.class).find(param_plan, 0, 0);
					for(SlmProcessPlan plans:plan_list){
						plans.setMemo(plans.getMemo()+"/"+order_list.get(x).getPlan().getMemo());
						this.getMapper(SlmProcessPlanMapper.class).update(plans);
					}
					continue;
				}

				orders=order_list.get(x);
				rownum=orders.getHave_plan();			//条数，excel表里的序号
				orders.setHave_plan(null);
				create_time =new Date(create_time.getTime()-1000);
				orders.setCreate_time(create_time);
				//订单数据
				order_sum.setMemo1("return"); 		//新增完返回订单对象
				order_sum.setObject(orders);
				ResultModel order_rm=doAddWeb(order_sum); // 新增订单：
				//如果无法新增（达重量上限） 调用强冲接口新增
				if("500".equals(order_rm.getState())){
					if(order_rm.getMsgInfo()!=null&&order_rm.getMsgInfo().contains("重量")){
						order_rm=doForceAddWeb(order_sum);
						if("500".equals(order_rm.getState())){
							wb.close(); 							
							throw new Exception(order_rm.getMsgInfo());
						} 
					}else{
						wb.close(); 
						throw new Exception(order_rm.getMsgInfo());
					}
				}
				//加工计划新增(获取到完整的订单信息之后
				re_order=(SlmOrderInfo)order_rm.getData();
				
				// 非需加工订单，第二次的增加加工计划就不用了：20230315 刘侣
				if ("2".equals(order_list.get(x).getOrder_nature())) {
					ResultModel plan_rm=this.getBean(SlmProcessPlanServiceImpl.class).setPlanParam(orders.getPlan(),re_order);       //组装加工计划数据
					if("500".equals(plan_rm.getState())){
						plan_rm.setMsgInfo("第"+rownum+"条数据加工计划新增出现错误："+plan_rm.getMsgInfo());
						wb.close(); 
						throw new Exception(plan_rm.getMsgInfo());
					}
				}
				// end
				
				//精度等级
				try{
					doAddLv(re_order);
				}catch(Exception e){}
				//工艺要求
				ResultModel base_rm=this.getBean(SlmContractBaseStationServiceImpl.class).setProcessParam(orders.getProcess(),re_order.getOrder_no());
				if("500".equals(base_rm.getState())){
					base_rm.setMsgInfo("第"+rownum+"条数据工艺要求新增出现错误："+base_rm.getMsgInfo());
					wb.close(); 
					throw new Exception(base_rm.getMsgInfo());
				}
			}
			wb.close(); 
			rm.setState("200");
			rm.setMsgInfo("导入成功");
		} catch (FileNotFoundException e) {  
			e.printStackTrace();  
			rm.setState("500");
			rm.setMsgInfo("未找到文件");
		} catch (SocketException e) {  
			logger.error("连接FTP失败");  
			rm.setMsgInfo("连接FTP失败"+e.getMessage());
			rm.setState("500");
		} catch (IOException e) {  
			e.printStackTrace();  
			logger.error("文件读取错误");
			rm.setMsgInfo("文件读取错误"+e.getMessage());
			rm.setState("500");
			return rm;
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("第"+rownum+"条数据新增时出现错误："+e.getMessage());
			e.printStackTrace(); 
			throw new Exception(rm.getMsgInfo());
			//return rm;
		} 
		return rm;
	}

	private SlmOrderInfo setOrderParam(SlmOrderInfo order,SlmContractLineInfo line,SlmCustomerTransSolution solution, SlmContractHeatInfo heat, String orderNatureName) {
		order.setPrecisicon_type_code(line.getPrecisicon_type_code());
		order.setPrecisicon_type_desc(line.getPrecisicon_type_desc());
		//		order.setWhole_coil("0"); 		//非整卷
		order.setContract_pk(line.getContract_pk());
		order.setContract_no(line.getContract_no());
		order.setContract_line_no(line.getContract_line_no());
		order.setContract_line_seq(line.getContract_line_seq());
		order.setEstimate_weight_unit_no("100306");
		order.setEstimate_weight_unit_name("t");
		if (orderNatureName != null && ("酸洗".equals(orderNatureName) || "冷轧".equals(orderNatureName) || "原料卷".equals(orderNatureName))) {
			
		} else {
			order.setWeight_type_no(line.getWeight_type_no());
			order.setWeight_type_name(line.getWeight_type_name());
		}
		
		if(heat!=null){			//取合同头的交货期
			order.setDeliver_date(heat.getDeliver_date());
			order.setSupplier_unit_no(heat.getSupply_unit_no());
			order.setSupplier_unit_name(heat.getSupply_unit_name());
			order.setSupplier_address(heat.getSupplier_address());
			order.setBalance_unit_no(heat.getBalance_unit_no());
			order.setBalance_unit_name(heat.getBalance_unit_name());
			order.setTxt_contract_no(heat.getTxt_contract_no());
			order.setPrice_type_no(heat.getPrice_type_no());
			order.setPrice_type_name(heat.getPrice_type_name());
			order.setCustomer_no(heat.getCustomer_no());
			order.setCustomer_name(heat.getCustomer_name());
		}
		order.setSolutions_no(solution.getSolutions_no());
		order.setSolutions_name(solution.getSolutions_name());
		order.setReciver_unit_no(solution.getReciver_org_no());
		order.setReciver_unit_name(solution.getReciver_org_name());
		order.setReciver_address(solution.getReciver_address());
		//		order.setOut_price(0d);
		//		order.setBalance_price(0d);
		order.setIs_pickup("0");
		order.setIs_liku("0");
		// 20230313刘侣：
		if (order.getOrder_nature() == null) {
			order.setOrder_nature("2");       	//需加工
		}
		if (orderNatureName != null && ("酸洗".equals(orderNatureName) || "冷轧".equals(orderNatureName) || "原料卷".equals(orderNatureName))) {
			// 说明是酸洗冷轧原料卷订单：
			// 结算价抓取合同行的   配送费抓取合同行运费的  
			order.setOut_price(line.getOrder_price1());
			order.setBalance_price(line.getOrder_price1());
			order.setTrade_price(line.getTrade_price());
			order.setWork_price(line.getTrade_price());
			order.setProcess_price(0d);
			// 运输方案取合同行的运输方案：
			order.setSolutions_no(line.getSolutions_no());
			order.setSolutions_name(line.getSolutions_name());
			// 重新获取运输方案信息：
			SlmCustomerTransSolution solutionEC = new SlmCustomerTransSolution();
			solutionEC.setSolutions_name(line.getSolutions_name());
			solutionEC.setSolutions_no(line.getSolutions_no());
			solutionEC.setCustomer_no(order.getCustomer_no());
			solutionEC.setCustomer_name(order.getCustomer_name());
			solutionEC.setValid_flag("1");
			List<SlmCustomerTransSolution> solution_listEC=this.getMapper(SlmCustomerTransSolutionMapper.class).find(solutionEC, 0, 0);
			
			if (solution_listEC != null && solution_listEC.size() > 0) {
				SlmCustomerTransSolution ssR = solution_listEC.get(0);
				order.setReciver_unit_no(ssR.getReciver_org_no());
				order.setReciver_unit_name(ssR.getReciver_org_name());
				order.setReciver_address(ssR.getReciver_address());
			}
			
		}
		// end
		
		order.setWidth(line.getWidth());
		order.setPsc(line.getPsc());
		order.setPsc_desc(line.getPsc_desc());
		order.setMsc(line.getMsc());
		order.setMsc_desc(line.getMsc_desc());
		order.setMsc_type_no(line.getMsc_type_no());
		order.setMsc_type_name(line.getMsc_type_name());
		order.setUse_code(line.getUse_code());
		order.setUse_desc(line.getUse_desc());
		order.setProd_cls_no(line.getProd_cls_no());
		order.setProd_cls_name(line.getProd_cls_name());
		order.setProd_code(line.getProd_code());
		order.setProd_name(line.getProd_name());
		order.setStd_code(line.getStd_code());
		order.setStd_name(line.getStd_name());
		order.setSteel_code(line.getSteel_code());
		order.setSteel_name(line.getSteel_name());
		order.setStd_type_no(line.getStd_type_no());
		order.setStd_type_name(line.getStd_type_name());
		order.setProd_figure_no(line.getProd_figure_no());
		order.setProd_figure_name(line.getProd_figure_name());
		order.setThick(line.getThick());
		order.setLength(line.getLength());
		order.setAdd_ask_no(line.getAdd_ask_no());
		order.setAdd_ask_desc(line.getAdd_ask_desc());
		order.setCustomer_alpha_no(line.getCustomer_alpha_no());
		order.setCustomer_alpha_desc(line.getCustomer_alpha_desc());
		order.setIs_lock("0");
		order.setDelivery_state_code(line.getDelivery_state_code());
		order.setDelivery_state_desc(line.getDelivery_state_desc());
		order.setIs_tax(line.getIs_tax());
		order.setPk_ask_code(line.getPk_ask_code());
		order.setPk_ask_desc(line.getPk_ask_desc());
		return order;
	}

	private SlmContractBaseStation geneteStation(ComBaseStation base,SlmOrderInfo old,String new_order_no){
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		SlmContractBaseStation station=new SlmContractBaseStation();
		station.setOrder_no(new_order_no);
		station.setSeq(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3));
		station.setCreate_name(userName);
		station.setCreate_time(new Date());
		station.setContract_no(old.getContract_no());
		station.setContract_line_seq(old.getContract_line_seq());
		station.setOrder_seq(old.getOrder_seq());
		station.setProcess_code(base.getProcess_code());
		station.setProcess_desc(base.getProcess_desc());
		station.setProcess_point_code(base.getProcess_point_code());
		station.setProcess_point_desc(base.getProcess_point_desc());
		station.setProcess_point_type(base.getProcess_point_type());
		station.setProcess_point_seq((long)base.getProcess_point_seq());
		station.setChoose(base.getChoose());
		station.setReturn_result(base.getReturn_result());
		station.setSend_checkplan(base.getSend_checkplan());
		station.setValidflag("1");
		station.setIs_craft(base.getIs_craft());
		station.setStation_hour(base.getStation_hour());
		return station;
	}

	private final static Log logger = LogFactory.getLog(SlmOrderInfoServiceImpl.class); 
	
	
	//=========================APP eason add 2019-07-15 ================================
	/**
	 * 订单查询
	 * memo1客户编号,memo2合同文本号
	 * */
	public ResultModel doQueryApp(CommonPage<SlmOrderInfo> sum){
		ResultModel rm=new ResultModel();
		SlmOrderInfo order=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String customer_no=(String)this.getSession().getAttribute(HomeService.SESSION_DEPT_ID);
		String txt_contract_no=sum.getMemo2();
		String flag=sum.getMemo3();
		String startTime=sum.getStartTime();		//用于查询创建时间
		String endTime=sum.getEndTime();
		String startTime2=sum.getStartTime2();		//用于查询交货期
		String endTime2=sum.getEndTime2();
		PageModel<SlmOrderInfo> pm=new PageModel<SlmOrderInfo>(pageIndex, pageSize);
		try{
			if(StringUtils.isNotEmpty(endTime) && !"null".equals(endTime)) {
				endTime+=" 23:59:59";
			}
			if(StringUtils.isNotEmpty(endTime2) && !"null".equals(endTime2)) {
				endTime2+=" 23:59:59";
			}
			if(order.getContract_no()!=null&&!"".equals(order.getContract_no())){
				order.setContract_no(order.getContract_no().trim());
			}
			String flags="";
			if("1".equals(flag)) flags=" and order_flag_no in('103408','103409')";
			if("103402".equals(order.getOrder_flag_no())){
				flags=" and order_flag_no ='103413'";
			}else 
				if("103403".equals(order.getOrder_flag_no())){
					flags=" and order_flag_no in ('103403','103413','103414','103415')";
				}else if(order.getOrder_flag_no()!=null&&!"".equals(order.getOrder_flag_no())){
					flags=" and order_flag_no ='"+order.getOrder_flag_no()+"'";
				}
			List<SlmOrderInfo> list=this.getMapper(SlmOrderInfoMapper.class).doQuery(order,customer_no,txt_contract_no,startTime,endTime,startTime2,endTime2,(pageIndex-1)*pageSize,pageIndex*pageSize,flags);
			int count=this.getMapper(SlmOrderInfoMapper.class).doQueryCount(order,customer_no,txt_contract_no,startTime,endTime,startTime2,endTime2,flags);
			for(SlmOrderInfo orders:list){		//从合同行里查询规格
				if(orders.getContract_no()!=null){
					String sale=orders.getContract_no()+orders.getContract_line_seq()+orders.getOrder_seq();
					orders.setSale_order_no(sale);
				}
				SlmContractLineInfo line=new SlmContractLineInfo();
				if(orders.getContract_no()!=null&&!"".equals(orders.getContract_no())){
					line.setContract_no(orders.getContract_no());
					line.setContract_line_seq(orders.getContract_line_seq());
				}else{
					line.setContract_line_no(orders.getContract_line_no());
				}
				List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).find(line, 0, 0);
				if(lineList.size()>0){
					orders.setWidth(lineList.get(0).getWidth());
					orders.setLength(lineList.get(0).getLength());
					orders.setThick(lineList.get(0).getThick());
				}
				orders.setHave_plan("1");
				//原料卷  查询是否有加工计划
				if("2".equals(orders.getOrder_nature())){		
					SlmProcessPlan plan=new SlmProcessPlan();
					plan.setContract_no(orders.getContract_no());
					plan.setContract_line_seq(orders.getContract_line_seq());
					plan.setOrder_seq(orders.getOrder_seq());
					plan.setValid_flag("1");
					int p_count=this.getMapper(SlmProcessPlanMapper.class).count(plan);
					if(p_count==0) orders.setHave_plan("0"); 	//没有加工计划
				}
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}
	
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doActualDeleteWebSum(CommonPage<SlmOrderInfo> sum) throws Exception{
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		ResultModel rm=new ResultModel();
		List<SlmOrderInfo> list = sum.getObjectList();
		if (list==null || list.size()<=0) {
			rm.setMsgInfo("请传入参数");
			rm.setState("500");
			return rm;
		}
		try{
			for (SlmOrderInfo order : list) {				
				SlmOrderInfo newOrder=this.getMapper(SlmOrderInfoMapper.class).findById(order.getOrder_no());	
				if(newOrder!=null){
					//只有创建人才能删除批量数据
					if (!userName.equals(newOrder.getCreate_man_name())) {
						rm.setMsgInfo("订单的创建人是【"+newOrder.getCreate_man_name()+"】,您无法进行批量删除");
						rm.setState("500");
						return rm;
					}
					//判断何种状态可以进行删除
					if(!"103401".equals(newOrder.getOrder_flag_no())){		//103401 编辑之前的都可以删除
						rm.setMsgInfo("当前状态无法删除");
						rm.setState("500");
						return rm;
					}  
					// ==========================eason add/update 2019-06-22=================
					//如果是拆分出来的订单，删除之后重量要还原回去
					if(newOrder.getP_order_no()!=null&&!"".equals(newOrder.getP_order_no())){
						SlmOrderInfo p_order=this.getMapper(SlmOrderInfoMapper.class).findById(newOrder.getP_order_no());
						if(p_order!=null){
							p_order.setEstimate_weight(DoubleUtil.add(p_order.getEstimate_weight(), newOrder.getEstimate_weight()));
							this.getMapper(SlmOrderInfoMapper.class).update(p_order);
						}
						//删除拆分订单信息																	
						SlmOrderSplitInfo split=new SlmOrderSplitInfo();
						split.setOrder_no_child(order.getOrder_no());
						List<SlmOrderSplitInfo> ls=this.getMapper(SlmOrderSplitInfoMapper.class).find(split, 0, 0);
						for(SlmOrderSplitInfo su:ls){
							SlmOrderSplitInfo sp=new SlmOrderSplitInfo();
							sp.setId(su.getId());
							sp.setValid_flag("0"); 
							sp.setDelete_man_no(userId);
							sp.setDelete_man_name(userName);
							sp.setDelete_time(new Date());
							this.getMapper(SlmOrderSplitInfoMapper.class).update(sp);
						}
					}				
					//======================================================
					this.getMapper(SlmOrderInfoMapper.class).delete(order.getOrder_no());
					//删除加工计划
					SlmProcessPlan plan=new SlmProcessPlan();
					plan.setContract_no(newOrder.getContract_no());
					plan.setContract_line_seq(newOrder.getContract_line_seq());
					plan.setOrder_seq(newOrder.getOrder_seq());
					List<SlmProcessPlan> planList=this.getMapper(SlmProcessPlanMapper.class).find(plan, 0, 0);
					for(SlmProcessPlan plans:planList){
						this.getMapper(SlmProcessPlanMapper.class).delete(plans.getPlan_no());
					}
					//删除精度等级
					SlmContractLineLv lv=new SlmContractLineLv();
					lv.setOrder_no(newOrder.getOrder_no());
					lv.setIs_flag("1");
					List<SlmContractLineLv> lv_list=this.getMapper(SlmContractLineLvMapper.class).find(lv, 0, 0);
					for(SlmContractLineLv lvs:lv_list){
						this.getMapper(SlmContractLineLvMapper.class).delete(lvs.getSeq());
					}
					//删除工艺要求
					SlmContractBaseStation station=new SlmContractBaseStation();
					station.setOrder_no(newOrder.getOrder_no());
					List<SlmContractBaseStation> station_list=this.getMapper(SlmContractBaseStationMapper.class).find(station, 0, 0);
					for(SlmContractBaseStation stations:station_list){
						this.getMapper(SlmContractBaseStationMapper.class).delete(stations.getSeq());
					}
					
					MesOprLog mol = new MesOprLog("销售管理", "订单维护", "批量删除", userName, opr_time, null, null, null, null, newOrder.getContract_no() + newOrder.getContract_line_seq() + newOrder.getOrder_seq());
					this.getMapper(MesOprLogMapper.class).insert(mol);
					
				}else{
					rm.setMsgInfo("该订单已经被删除");
					rm.setState("500");
					return rm;
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("删除失败"+ex.getMessage());
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}
	
	/**
	 * 根据订单号查询订单信息
	 * @param sum
	 * @return
	 */
	public ResultModel doQuerySlmOrderInfoByOrderno(CommonPage<SlmOrderInfo> cp){
		ResultModel rm = new ResultModel();
		SlmOrderInfo soi = cp.getObject();
		String swhere = "";
		if (soi.getOrder_no()!=null && !"".equals(soi.getOrder_no())) {
			swhere += " and soi.contract_no||soi.contract_line_seq||soi.order_seq = '"+soi.getOrder_no()+"' "
					+ "and nvl(soi.change_flag,'0') <> '1'";			
		}
		List<SlmOrderInfo> soiList = this.getMapper(SlmOrderInfoMapper.class).doQuerySlmOrderInfoByOrderno(swhere);
		rm.setData(soiList);
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 订单进程跟踪，弹框显示产量信息
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryCLByOrderno(CommonPage<SlmOrderInfo> cp){
		ResultModel rm = new ResultModel();
		SlmOrderInfo soi = cp.getObject();
		String orderno = soi.getOrder_no();//订单号
		List<HashMap> list = new ArrayList<>();
		String condition = " and contract_no||contract_line_seq||order_seq = '"+orderno+"' and nvl(change_flag,'0') <> '1'";
		List<SlmOrderInfo> soiList = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
		if (CollectionUtils.isNotEmpty(soiList)) {
			soi = soiList.get(0);
			if (StringUtils.isEmpty(soi.getProcess())) {
				//订单进程为null，直接不进行查询
				return null;
			}
			HashMap<String,Object> hm0 = new HashMap<String,Object>();
			HashMap<String,Object> hm = null;
			//20201210 新增原料卷信息
			Double weight = this.getMapper(SlmOrderInfoMapper.class).doQueryOrderWeight3(orderno,"3");
			hm0.put("MACHINE_NAME", "原料");
			hm0.put("WEIGHT1", null);
			hm0.put("WEIGHT2", null);
			hm0.put("WEIGHT3", weight);
			list.add(hm0);
			
			//拆分工艺路径
			List<String> processList = Arrays.asList(soi.getProcess().split("-"));
			for (String process : processList) {
				//指示待机： 已挂单编制计划，但是计划未下发（已交工，已入库） weight1
				//作业待机： 计划已下发，但是未交工（发运锁定） weight2
				//完成重量： 已交工，未入库  weight3
				if (process.contains("酸洗")) {	
					hm = new HashMap<String,Object>();
					Double weight1 = this.getMapper(SlmOrderInfoMapper.class).doQuerySxWeight1(orderno,"('5BPC01')");
					// 指示待机 = 订单中已编制计划的卷重 + 入库后还没编制计划的卷重 20230112 刘侣：需求黄涛提出
					Double weightOther = this.getMapper(SlmOrderInfoMapper.class).doQuerySxWeightOther(orderno);
					Double weightSum = null;
					// 相加：
					if (weight1 == null) {
						if (weightOther != null) {
							weightSum = weightOther;
						}
					} else {
						if (weightOther == null) {
							weightSum = weight1;
						} else {
							weightSum = weight1 + weightOther;
						}
					}
					// end
					
					Double weight2 = this.getMapper(SlmOrderInfoMapper.class).doQuerySxWeight2(orderno,"('5BPC02','5BPC03')");
					Double weight3 = this.getMapper(SlmOrderInfoMapper.class).doQuerySxWeight3(orderno,"('5BPC10')");
					hm.put("MACHINE_NAME", "酸洗");
					hm.put("WEIGHT1", weightSum);
					hm.put("WEIGHT2", weight2);
					hm.put("WEIGHT3", weight3);
					list.add(hm);
					continue;
				}else if (process.contains("退火")) {
					hm = new HashMap<String,Object>();
					Double weight1 = this.getMapper(SlmOrderInfoMapper.class).doQueryThWeight1(orderno,"('5BAN01')");// 指示待机 = 订单中已编制计划的卷重 + 入库后还没编制计划的卷重 20230112 刘侣
					Double weightOther = this.getMapper(SlmOrderInfoMapper.class).doQueryThWeightOther(orderno);
					Double weightSum = null;
					// 相加：
					if (weight1 == null) {
						if (weightOther != null) {
							weightSum = weightOther;
						}
					} else {
						if (weightOther == null) {
							weightSum = weight1;
						} else {
							weightSum = weight1 + weightOther;
						}
					}
					// end
					Double weight2 = this.getMapper(SlmOrderInfoMapper.class).doQueryThWeight2(orderno,"('5BAN02','5BAN03')");
					Double weight3 = this.getMapper(SlmOrderInfoMapper.class).doQueryThWeight3(orderno,"('5BAN80')");
					hm.put("MACHINE_NAME", "退火");
					hm.put("WEIGHT1", weightSum);
					hm.put("WEIGHT2", weight2);
					hm.put("WEIGHT3", weight3);
					list.add(hm);
					continue;
				}else if (process.contains("平整")) {
					hm = new HashMap<String,Object>();
					Double weight1 = this.getMapper(SlmOrderInfoMapper.class).doQueryPzWeight1(orderno,"('5BSR01')");
					// 指示待机 = 订单中已编制计划的卷重 + 入库后还没编制计划的卷重 20230112 刘侣
					Double weightOther = this.getMapper(SlmOrderInfoMapper.class).doQueryPzWeightOther(orderno);
					Double weightSum = null;
					// 相加：
					if (weight1 == null) {
						if (weightOther != null) {
							weightSum = weightOther;
						}
					} else {
						if (weightOther == null) {
							weightSum = weight1;
						} else {
							weightSum = weight1 + weightOther;
						}
					}
					// end
					
					Double weight2 = this.getMapper(SlmOrderInfoMapper.class).doQueryPzWeight2(orderno,"('5BSR02','5BSR03')");
					Double weight3 = this.getMapper(SlmOrderInfoMapper.class).doQueryPzWeight3(orderno,"('5BSR10')");
					hm.put("MACHINE_NAME", "平整");
					hm.put("WEIGHT1", weightSum);
					hm.put("WEIGHT2", weight2);
					hm.put("WEIGHT3", weight3);
					list.add(hm);
					continue;
				}else if (process.contains("开平")) {
					hm = new HashMap<String,Object>();
					Double weight1 = this.getMapper(SlmOrderInfoMapper.class).doQueryKpWeight1(orderno,"('5BCL01')");
					// 指示待机 = 订单中已编制计划的卷重 + 入库后还没编制计划的卷重 20230112 刘侣
					Double weightOther = this.getMapper(SlmOrderInfoMapper.class).doQueryKpWeightOther(orderno);
					Double weightSum = null;
					// 相加：
					if (weight1 == null) {
						if (weightOther != null) {
							weightSum = weightOther;
						}
					} else {
						if (weightOther == null) {
							weightSum = weight1;
						} else {
							weightSum = weight1 + weightOther;
						}
					}
					// end
					
					Double weight2 = this.getMapper(SlmOrderInfoMapper.class).doQueryKpWeight2(orderno,"('5BCL02','5BCL03')");
					Double weight3 = this.getMapper(SlmOrderInfoMapper.class).doQueryKpWeight3(orderno,"('5BCL10')");
					hm.put("MACHINE_NAME", "开平");
					hm.put("WEIGHT1", weightSum);
					hm.put("WEIGHT2", weight2);
					hm.put("WEIGHT3", weight3);
					list.add(hm);
					continue;
				}else if (process.contains("分条")) {
					hm = new HashMap<String,Object>();
					Double weight1 = this.getMapper(SlmOrderInfoMapper.class).doQueryFtWeight1(orderno,"('5BLW01')");
					// 指示待机 = 订单中已编制计划的卷重 + 入库后还没编制计划的卷重 20230112 刘侣
					Double weightOther = this.getMapper(SlmOrderInfoMapper.class).doQueryFtWeightOther(orderno);
					Double weightSum = null;
					// 相加：
					if (weight1 == null) {
						if (weightOther != null) {
							weightSum = weightOther;
						}
					} else {
						if (weightOther == null) {
							weightSum = weight1;
						} else {
							weightSum = weight1 + weightOther;
						}
					}
					// end
					
					Double weight2 = this.getMapper(SlmOrderInfoMapper.class).doQueryFtWeight2(orderno,"('5BLW02','5BLW03')");
					Double weight3 = this.getMapper(SlmOrderInfoMapper.class).doQueryFtWeight3(orderno,"('5BLW10')");
					hm.put("MACHINE_NAME", "分条");
					hm.put("WEIGHT1", weightSum);
					hm.put("WEIGHT2", weight2);
					hm.put("WEIGHT3", weight3);
					list.add(hm);
					continue;
				}else if (process.contains("冷轧")) {
					hm = new HashMap<String,Object>();
					Double weight1 = this.getMapper(SlmOrderInfoMapper.class).doQueryZjWeight1(orderno,"('5BRL01')");
					// 指示待机 = 订单中已编制计划的卷重 + 入库后还没编制计划的卷重 20230112 刘侣
					Double weightOther = this.getMapper(SlmOrderInfoMapper.class).doQueryZjWeightOther(orderno);
					Double weightSum = null;
					// 相加：
					if (weight1 == null) {
						if (weightOther != null) {
							weightSum = weightOther;
						}
					} else {
						if (weightOther == null) {
							weightSum = weight1;
						} else {
							weightSum = weight1 + weightOther;
						}
					}
					// end
					
					Double weight2 = this.getMapper(SlmOrderInfoMapper.class).doQueryZjWeight2(orderno,"('5BRL02','5BRL03')");
					Double weight3 = this.getMapper(SlmOrderInfoMapper.class).doQueryZjWeight3(orderno,"('5BRL10')");
					hm.put("MACHINE_NAME", "轧机");
					hm.put("WEIGHT1", weightSum);
					hm.put("WEIGHT2", weight2);
					hm.put("WEIGHT3", weight3);
					list.add(hm);
					continue;
				}
			}
			//设置库存：已交工，已入库       发运锁定        已发运出库
			String lastProcess = processList.get(processList.size()-1);
			lastProcess = lastProcess.replaceAll("\\d+","");//最后的工艺路径去除数字
			lastProcess = lastProcess.replace("开平", "横剪");
			lastProcess = lastProcess.replace("冷轧", "轧机");
			HashMap<String,Object> hm1 = new HashMap<String,Object>();
			Double weight1 = this.getMapper(SlmOrderInfoMapper.class).doQueryKcWeight1(orderno,lastProcess);
			Double weight2 = this.getMapper(SlmOrderInfoMapper.class).doQueryKcWeight2(orderno,lastProcess);
			Double weight3 = this.getMapper(SlmOrderInfoMapper.class).doQueryKcWeight3(orderno,lastProcess);
			hm1.put("MACHINE_NAME", "库存");
			hm1.put("WEIGHT1", weight1);
			hm1.put("WEIGHT2", weight2);
			hm1.put("WEIGHT3", weight3);
			list.add(hm1);
		}
		//rm.setData(soiList);
		rm.setData(list);
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 弹框显示具体的明细
	 * @param cp
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryCLDetailByOrderno(CommonPage<YdmProductDetail> cp){
		ResultModel rm = new ResultModel();
		YdmProductDetail ypd = cp.getObject();
		String memo1 = cp.getMemo1();//memo1 = "0" 代表生产进行(还未交工)  "1" 代表生产完成(已经交工)
		List<HashMap> list = new ArrayList<HashMap>();
		if ("酸洗".equals(ypd.getMachine_name())) {
			list = this.getMapper(SlmOrderInfoMapper.class).doQuerySxDetailByOrderno(ypd.getOrderno(), memo1);
		}else if ("轧机".equals(ypd.getMachine_name())) {
			list = this.getMapper(SlmOrderInfoMapper.class).doQueryZjDetailByOrderno(ypd.getOrderno(), memo1);
		}else if ("退火".equals(ypd.getMachine_name())) {
			list = this.getMapper(SlmOrderInfoMapper.class).doQueryThDetailByOrderno(ypd.getOrderno(), memo1);
		}else if ("平整".equals(ypd.getMachine_name())) {
			list = this.getMapper(SlmOrderInfoMapper.class).doQueryPzDetailByOrderno(ypd.getOrderno(), memo1);
		}else if ("分条".equals(ypd.getMachine_name())) {
			list = this.getMapper(SlmOrderInfoMapper.class).doQueryFtDetailByOrderno(ypd.getOrderno(), memo1);
		}else if ("开平".equals(ypd.getMachine_name())) {
			list = this.getMapper(SlmOrderInfoMapper.class).doQueryKpDetailByOrderno(ypd.getOrderno(), memo1);
		}else if ("库存".equals(ypd.getMachine_name())) {
			String condition = " and contract_no||contract_line_seq||order_seq = '"+ypd.getOrderno()+"' and nvl(change_flag,'0') <> '1'";
			List<SlmOrderInfo> soiList = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
			if (CollectionUtils.isNotEmpty(soiList)) {
				SlmOrderInfo soi = soiList.get(0);
				if (StringUtils.isEmpty(soi.getProcess())) {
					//订单进程为null，直接不进行查询
					return null;
				}
				//拆分工艺路径
				List<String> processList = Arrays.asList(soi.getProcess().split("-"));
				String lastProcess = processList.get(processList.size()-1);
				lastProcess = lastProcess.replaceAll("\\d+","");//最后的工艺路径去除数字
				lastProcess = lastProcess.replace("开平", "横剪");
				lastProcess = lastProcess.replace("冷轧", "轧机");
				list = this.getMapper(SlmOrderInfoMapper.class).doQueryKcDetailByOrderno(ypd.getOrderno(), memo1,lastProcess);
			}
		}else if ("综判".equals(ypd.getMachine_name())) {
			
		}else if ("原料".equals(ypd.getMachine_name())) {
			list = this.getMapper(SlmOrderInfoMapper.class).doQueryYlDetailByOrderno(ypd.getOrderno(), memo1);
		}
		rm.setData(list);
		rm.setState("200");
		return rm;
	}
	
	@Transactional(value="tm", rollbackFor=Exception.class)
	public void doJudgeOrderIsOverDelevery() {
		String now = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());		
		String time = now.substring(0,8);
		//一：库存数据处理
		List<SlmOrderInfo> soiList1 = this.getMapper(SlmOrderInfoMapper.class).doQueryKcOrderForJudgeOverDelivery();
		if (CollectionUtils.isNotEmpty(soiList1)) {
			for (SlmOrderInfo soi1 : soiList1) {
				soi1.setIs_over_delivery("1");
				soi1.setDelivery_memo((StringUtils.isEmpty(soi1.getDelivery_memo())?"":soi1.getDelivery_memo())+";"+now+"System自动判定超交货期");
				this.getMapper(SlmOrderInfoMapper.class).update(soi1);
			}
		}
		
		//二：已关闭提单处理
		List<SlmOrderInfo> soiList = this.getMapper(SlmOrderInfoMapper.class).doQueryOrderForJudgeOverDelivery(time);
		if (CollectionUtils.isNotEmpty(soiList)) {
			for (SlmOrderInfo soi : soiList) {
				soi.setIs_over_delivery("1");
				soi.setDelivery_memo((StringUtils.isEmpty(soi.getDelivery_memo())?"":soi.getDelivery_memo())+";"+now+"System自动判定超交货期");
				this.getMapper(SlmOrderInfoMapper.class).update(soi);
			}
		}
	}
	
	/**
	 * 订单超交货期数据:20230511刘侣
	 * */
	public ResultModel queryOrdOverDate(){
		ResultModel rm=new ResultModel();
//		SlmOrderInfo order=sum.getObject();
		try{
			List<SlmOrderInfo> conAvail = this.getMapper(SlmOrderInfoMapper.class).getContractAvail();
			
			String sWhere = "";
			List<SlmOrderInfo> ordAvail = new ArrayList<>();
			if (conAvail.size() > 0) {
//				sWhere += "and soi.CONTRACT_NO in (";
				for(SlmOrderInfo soi : conAvail) {
					// 如果：合同总重90%：TRADE_PRICE > 订单总重：process_price ；那么这个合同没执行完；
					if ((soi.getTrade_price() != null ? soi.getTrade_price() : 0) > (soi.getProcess_price() != null ? soi.getProcess_price() : 0)) {
						sWhere += ("'" + soi.getContract_no() + "',");
					}
				}
				sWhere = sWhere.substring(0, sWhere.length() - 1);
//				sWhere += ") ";
				ordAvail = this.getMapper(SlmOrderInfoMapper.class).getOrdAvail(sWhere);
			}
			
			rm.setState("200");
			rm.setData(ordAvail);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
}

