package market.Slm.DeliveryManagement.impl;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import jxl.CellView;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import market.Api.Lms.impl.LmsApiServiceImpl;
import market.Com.mapper.PbModelDbMapper;
import market.Com.pb.DoubleUtil;
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.Slm.ContractManagement.impl.SlmContractHeatInfoServiceImpl;
import market.Slm.ContractManagement.impl.SlmContractLineInfoServiceImpl;
import market.Slm.ContractManagement.impl.SlmContractPaymentServiceImpl;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentMapper;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmContractPayment;
import market.Slm.CustomerInformation.impl.SlmCustomerTransSolutionServiceImpl;
import market.Slm.CustomerInformation.vo.SlmCustomerTransSolution;
import market.Slm.DeliveryManagement.mapper.SlmDeliveryPlanLineMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillDetailMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillLineMapper;
import market.Slm.DeliveryManagement.service.SlmLadingBillHeatService;
import market.Slm.DeliveryManagement.vo.SlmDeliveryPlanLine;
import market.Slm.DeliveryManagement.vo.SlmLadingBillDetail;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.DeliveryManagement.vo.SlmLadingBillLine;
import market.Slm.FundManagement.impl.SlmFundSettleCarriageServiceImpl;
import market.Slm.FundManagement.impl.SlmFundSettleGoodServiceImpl;
import market.Slm.FundManagement.impl.SlmFundSettleOtherServiceImpl;
import market.Slm.FundManagement.mapper.SlmFundBalancePriceApplyMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleBillLineMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleCarriageMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleGoodMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleOtherMapper;
import market.Slm.FundManagement.vo.SlmFundBalancePriceApply;
import market.Slm.FundManagement.vo.SlmFundSettleBillLine;
import market.Slm.FundManagement.vo.SlmFundSettleCarriage;
import market.Slm.FundManagement.vo.SlmFundSettleGood;
import market.Slm.FundManagement.vo.SlmFundSettleOther;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.vo.SlmOrderInfo;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="SlmLadingBillHeatService")
public class SlmLadingBillHeatServiceImpl extends BaseServiceImpl<SlmLadingBillHeat,Object> implements SlmLadingBillHeatService {

	/**
	 * 提单头列表查询 memo1
	 * 1提单审核：待审核  待下发
		2提单下发：待下发 下发
		3提单打印：下发
		4结算-核算界面
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmLadingBillHeat> pm=new PageModel<SlmLadingBillHeat>(pageIndex, pageSize);
		String flag=sum.getMemo1();			//页面区分
		String coilno=sum.getMemo2();			//卷号
		String JY=sum.getMemo3();
		String sType=sum.getMemo6()==null?"":sum.getMemo6(); // 为1则是火运
		//============eason add 2019-08-26================
		boolean isExport=false;
		if(sum.getMemo5()!=null&&"export".equals(sum.getMemo5())){
			isExport=true;
		}
		//================================================
		
		List<SlmLadingBillHeat> list=new ArrayList<SlmLadingBillHeat>();
		long count=0;
		try{
			String sWhere=" 1=1 ";
			String sOrder=" create_time desc,valid_flag desc";
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			if(!"4".equals(flag)&&heat.getEffect_start_time()!=null){
				String timeColumn=isExport==false?"Effect_start_time":"create_time";
				sWhere+=" and '"+sdf.format(heat.getEffect_start_time())+"' <=to_char("+timeColumn+", 'yyyy-mm-dd') ";
				heat.setEffect_start_time(null);
			}
			if(!"4".equals(flag)&&heat.getEffect_end_time()!=null){
				String timeColumn=isExport==false?"Effect_end_time":"create_time";
				sWhere+=" and '"+sdf.format(heat.getEffect_end_time())+"' >=to_char("+timeColumn+", 'yyyy-mm-dd') ";
				heat.setEffect_end_time(null);				
			}
			if(!"4".equals(flag)&&heat.getBill_no()!=null){
				sWhere+=" and bill_no like '%"+heat.getBill_no()+"%' ";
				heat.setBill_no(null);				
			}
			if(!"4".equals(flag)&&heat.getContract_no()!=null){
				sWhere+=" and contract_no like '%"+heat.getContract_no()+"%' ";
				heat.setContract_no(null);				
			}
			if("1".equals(flag)){
				sWhere+=" and valid_status in('2','3')";
			}
			if("2".equals(flag)){
				sWhere+=" and valid_status in('3','4')";
			}
			if("3".equals(flag)){
				sWhere+=" and valid_status in('4')";
				//				sOrder=" issuer_time desc";
			}
			//			if("5".equals(flag)){			//为资金结算-对齐查询
			//				sWhere+=" and valid_status in('12','13')";
			//				sOrder=" valid_status ,update_time desc";
			//			}
			if(JY!=null&&!"".equals(JY)){
				if("J".equals(JY))
					sWhere+=" and bill_no like 'J%'";
				if("Y".equals(JY))
					sWhere+=" and bill_no like 'Y%'";
			}
			if(!"4".equals(flag)&&!"5".equals(flag)){
				if("1".equals(sType)){
					String transWhere=sWhere.replace("1=1","");
					list=this.getMapper(SlmLadingBillHeatMapper.class).doQueryTran(heat, transWhere, sOrder , (pageIndex-1)*pageSize, pageSize);
					count=this.getMapper(SlmLadingBillHeatMapper.class).doQueryTranCount(heat, transWhere);
				}else{
					list=this.getMapper(SlmLadingBillHeatMapper.class).findWithCondition(heat,sWhere,sOrder , (pageIndex-1)*pageSize,pageSize);
					count=this.getMapper(SlmLadingBillHeatMapper.class).countWithCondition(heat, sWhere);
				}
			}
			if("4".equals(flag)){			//为资金结算-核算界面查询
				list=this.getMapper(SlmLadingBillHeatMapper.class).doQueryAdjust(heat,coilno,JY);
			}
			if("5".equals(flag)){			//为资金结算-对齐查询
				list=this.getMapper(SlmLadingBillHeatMapper.class).doQueryAlign(heat,sWhere);
				//================2019-06-28 eason add=========================
				String str="",strProcess="";
				for(SlmLadingBillHeat slh:list){
					str=(slh.getProcess()==null?"":slh.getProcess().trim());
					for(String s:str.split(",")){
						if(strProcess.indexOf(s)<0){
							strProcess+=s+",";
						}
					}
					if(!"".equals(strProcess)){
						slh.setProcess(strProcess.substring(0,strProcess.length()-1));
						strProcess="";
					}
				}
				//================================================================
			}

			pm.setRows(list);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 提单头过期列表查询
	 * */
	public ResultModel doQueryOverTimeWeb(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmLadingBillHeat> pm=new PageModel<SlmLadingBillHeat>(pageIndex, pageSize);
		try{
			String sWhere=" 1=1 and EFFECT_END_TIME<SYSDATE";
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			if(heat.getEffect_start_time()!=null&&!"".equals(heat.getEffect_start_time())){
				sWhere+=" and '"+sdf.format(heat.getEffect_start_time())+"' <=to_char(Effect_start_time, 'yyyy-mm-dd') ";
				heat.setEffect_start_time(null);
			}
			if(heat.getEffect_end_time()!=null&&!"".equals(heat.getEffect_end_time())){
				sWhere+=" and '"+sdf.format(heat.getEffect_end_time())+"' >=to_char(Effect_end_time, 'yyyy-mm-dd') ";
				heat.setEffect_end_time(null);				
			}
			sWhere+=" and valid_status in('1','2','3','4')";
			List<SlmLadingBillHeat> list=this.getMapper(SlmLadingBillHeatMapper.class).findWithCondition(heat,sWhere, " create_time desc,valid_flag desc", (pageIndex-1)*pageSize,pageSize);
			int count=this.getMapper(SlmLadingBillHeatMapper.class).countWithCondition(heat, sWhere);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 主提单新增
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat = sum.getObject();
		String order_nature = sum.getMemo1();
		List<SlmLadingBillLine> lineList = heat.getLineList();
		String allCoils = "";
		try{
			//验证当提单明细仓库为在制品库且运输方案不是到优特则不允许新增
			String solutions_name=heat.getSolutions_name();
			if(solutions_name!=null && solutions_name.contains("到优特")){
				solutions_name="到优特";
			}
			for(SlmLadingBillLine lines:lineList){
				for (YdmProductDetail details : lines.getDetailList()) {
					if("500202".equals(details.getStorageattr())&&!"到优特".equals(solutions_name)){
						rm.setState("500");
						rm.setMsgInfo("在制品库且运输方案不是到优特不允许新增!");
						return rm;
					}
					allCoils = allCoils + details.getCoilno() + ",";
				}
			}
			
			
			String date=new SimpleDateFormat("yyyyMMdd").format(new Date());
			String id=date;
			int count=this.getMapper(SlmLadingBillHeatMapper.class).findMaxId(date);
			count++;
			String seq=String.format("%05d", count);
			id+=seq;
			if(order_nature!=null){
				if("1".equals(order_nature)){
					id="Y"+id;
				}else if("2".equals(order_nature)){
					id="J"+id;
				}else if("4".equals(order_nature)||"5".equals(order_nature)){
					id="L"+id;
				}else if("3".equals(order_nature)){
					//3.非计划订单 N开头 20200330 经营部部长+财务决定
					id="N"+id;
				}
			}

			//一致验证 合同号和订单属性要相同
			List<SlmContractHeatInfo> heat_list=new ArrayList<SlmContractHeatInfo>();
			String contract_no_no="";
			if(lineList!=null){
				boolean in=true;
				String contract_no="";
				String nature="";
				String steel="";
				for(SlmLadingBillLine lines:lineList){
					SlmOrderInfo order=new SlmOrderInfo();
					order.setContract_no(lines.getContract_no());
					order.setContract_line_seq(lines.getContract_line_seq());
					order.setOrder_seq(lines.getOrder_seq());
					List<SlmOrderInfo> order_list = this.getMapper(SlmOrderInfoMapper.class).find(order, 0, 0);
					//运输方案要为该订单号里的运输方案
					if(order_list.size()>0){
						if(in){
							//如果是净重交货 ,需加工订单 (有加工配送费和货款费——去掉 )  设置主键为N开头
							if("102301".equals(order_list.get(0).getWeight_type_no())
									&&"2".equals(order_list.get(0).getOrder_nature())){
								id=id.substring(1);
								id="N"+id;
							}

							steel=order_list.get(0).getSteel_code();
							contract_no=lines.getContract_no();
							contract_no_no=lines.getContract_no();
							nature=lines.getOrder_nature();

							in=false;
						}
						if(!steel.equals(order_list.get(0).getSteel_code())){
							rm.setState("500");
							rm.setMsgInfo("选择的待发确认信息应保证牌号一致");
							return rm;		
						}
						
						//20210601 J的提单，不能带原卷价格
						if (id.contains("J")) {
							if (order_list.get(0).getBalance_price() > 0) {
								rm.setState("500");
								rm.setMsgInfo("需加工且毛重的订单不能含结算价");
								return rm;	
							}
						}
					}
					if(!nature.equals(lines.getOrder_nature())){
						rm.setState("500");
						rm.setMsgInfo("选择的待发确认信息应保证订单属性一致");
						return rm;						
					}
					if(!contract_no.equals(lines.getContract_no())){
						rm.setState("500");
						rm.setMsgInfo("选择的待发确认信息应保证合同号一致");
						return rm;				
					}
					

				}
				//资金占用判断
				if(!"".equals(contract_no_no)){
					heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+contract_no_no+"'", null, 0, 0);
					if(heat_list.size()>0){
						SlmContractHeatInfo contract_heat=heat_list.get(0);
						if("101603".equals(contract_heat.getContract_type_no())){
							rm.setState("500");
							rm.setMsgInfo("厂内合同无需新增提单");
							return rm;
						}
						//20191226 针对新钢销售公司委托加工，不做资金控制
						if (!"101607".equals(contract_heat.getContract_type_no())) {
							rm=this.getBean(SlmContractPaymentServiceImpl.class).doJudgeAccount(contract_heat,lineList);
							if("500".equals(rm.getState())) {
								return rm;							
							}							
						}
					}else{
						rm.setState("500");
						rm.setMsgInfo("未找到对应的合同头信息");
						return rm;
					}
				}
			}else{
				rm.setState("500");
				rm.setMsgInfo("请传入提单子行信息");
				return rm;
			}
			
			heat.setBill_no(id);
			heat.setCreate_man_no(userId);
			heat.setCreate_man_name(userName);
			heat.setCreate_time(new Date());
			heat.setValid_status("1");		//编辑
			heat.setValid_flag("1");
			if (heat_list!=null && heat_list.size()>0) {
				heat.setContract_type_no(heat_list.get(0).getContract_type_no());//合同类型				
			}			
			this.getMapper(SlmLadingBillHeatMapper.class).insert(heat);

			//新增子提单
			if(lineList!=null){
				for(SlmLadingBillLine lines:lineList){
					lines.setBill_no(id);
					CommonPage<SlmLadingBillLine> lineSum=new CommonPage<SlmLadingBillLine>();
					lineSum.setObject(lines);
					ResultModel line_rm=this.getBean(SlmLadingBillLineServiceImpl.class).doAddWeb(lineSum);
					if("500".equals(line_rm.getState()))	throw new  Exception(line_rm.getMsgInfo());

					//20191226 针对新钢销售公司委托加工，不做资金控制
					if (heat_list!=null && heat_list.size()>0 && !"101607".equals(heat_list.get(0).getContract_type_no())) {						
						line_rm=this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(heat_list.get(0), null, lines, "102703","1");
						if("500".equals(line_rm.getState())){						
							throw new  Exception(line_rm.getMsgInfo());
						}	
					}
					
				}
			}
			rm.setState("200");
			
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("提单新增失败"+ex.getMessage());
			ex.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}


	/**
	 * 主提单编辑
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat=sum.getObject();
		try{
			if(true){
				rm.setMsgInfo("修改功能正在完善，请见谅");
				rm.setState("500");
				return rm;
			}
			//判断何种状态可以进行编辑
			SlmLadingBillHeat newheat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
			if(!"1".equals(newheat.getValid_status())){		//只有编辑状态才可修改
				rm.setMsgInfo("当前状态无法编辑");
				rm.setState("500");
				return rm;
			}
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);


			//删除原有子提单
			List<SlmLadingBillLine> org_list=this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(null, " bill_no='"+heat.getBill_no()+"'", null, 0, 0);

			//删除占用
			List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+heat.getContract_no()+"'", null, 0, 0);
			//删除原有明细
			for(SlmLadingBillLine lines:org_list){
				//释放资金占用
				if(heat_list.size()>0){
					this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(heat_list.get(0), null, lines, "102703","2");
				}
				//库存关闭锁定
				this.getBean(SlmLadingBillLineServiceImpl.class).doInvalidDetail(lines.getLine_no());
				this.getMapper(SlmLadingBillLineMapper.class).delete(lines.getLine_no());
			}
			//新增子提单
			List<SlmLadingBillLine> lineList=heat.getLineList();
			if(lineList!=null){
				for(SlmLadingBillLine lines:lineList){
					lines.setBill_no(heat.getBill_no());
					CommonPage<SlmLadingBillLine> lineSum=new CommonPage<SlmLadingBillLine>();
					lineSum.setObject(lines);
					this.getBean(SlmLadingBillLineServiceImpl.class).doAddWeb(lineSum);

					//资金占用
					if(heat_list.size()>0){
						rm=this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(heat_list.get(0), null, lines, "102703","1");
					}
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("编辑失败"+ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 提单头启用停用
	 * 现只允许停用，原停用接口改为批量传参
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSwitchWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			// 既然启用停用都是单挑操作，为了防止多次执行，将for循环去掉20230223刘侣
			SlmLadingBillHeat heat = heatList.get(0);
			String state="1".equals(heat.getValid_flag())?"启用":"停用";
			//判断何种状态可以进行启用停用
			SlmLadingBillHeat newheat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
			// 如果点击停用按钮，判断提单内所有卷是否存在在库状态的：（20220302上午修改treals===）
			if ("停用".equals(state)) {
				String sql = "select count(1) from SLM_LADING_BILL_DETAIL t " 
						+" left join YDM_PRODUCT_DETAIL ypd on t.COILNO = ypd.COILNO"
						+ " where t.BILL_NO = '"+ newheat.getBill_no() +"' and ypd.STATE = '0'";
				int count = this.getMapper(PbModelDbMapper.class).doQueryCount(sql);
				if (count > 0) {
					rm.setState("500");
					rm.setMsgInfo("该提单明细内存在 在库 的卷，无法作废该提单");
					return rm;
				}
			}
			// （20220302上午修改treals===）
			if(!"1".equals(newheat.getValid_status())){		//编辑状态才可 启用停用
				rm.setMsgInfo("当前状态无法"+state);
				rm.setState("500");
				return rm;
			}
			if("0".equals(heat.getValid_flag())){		//停用
				heat.setDelete_man_no(userId);
				heat.setDelete_man_name(userName);
				heat.setDelete_time(new Date());
				//连带行一起停用
				SlmLadingBillLine line=new SlmLadingBillLine();
				line.setBill_no(heat.getBill_no());
				line.setValid_flag("1");
				List<SlmLadingBillLine> lineList=this.getBean(SlmLadingBillLineServiceImpl.class).doQuery(line);
				//删除占用
				for(SlmLadingBillLine lines:lineList){
					lines.setValid_flag("0");
					lines.setDelete_man_no(userId);
					lines.setDelete_man_name(userName);
					lines.setDelete_time(new Date());
					this.getBean(SlmLadingBillLineServiceImpl.class).doUpdate(lines);
					

					//释放资金占用
					List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+lines.getContract_no()+"'", null, 0, 0);
					if(heat_list.size()>0){
						rm = this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(heat_list.get(0), null, lines, "102703","2");
						//====================eason add 2019-06-26 ==========================
						if("500".equals(rm.getState())){
							throw new Exception(rm.getMsgInfo());
						}
						
						//================================================================
					}
					// 在资金释放之后再删除提单明细：20230220刘侣
					this.getBean(SlmLadingBillLineServiceImpl.class).doInvalidDetail(lines.getLine_no());
				}
				this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
			}else{			//启用
				rm.setState("500");
				rm.setMsgInfo("无法启用，请重新新增数据");
				return rm;
				//					heat.setUpdate_man_no(userId);
				//					heat.setUpdate_man_name(userName);
				//					heat.setUpdate_time(new Date());
				//					this.getMapper(SlmLadingBillHeatMapper.class).doEnable(heat);
			}
			// end
			
//			for(SlmLadingBillHeat heat:heatList){
//				String state="1".equals(heat.getValid_flag())?"启用":"停用";
//				//判断何种状态可以进行启用停用
//				SlmLadingBillHeat newheat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
//				// 如果点击停用按钮，判断提单内所有卷是否存在在库状态的：（20220302上午修改treals===）
//				if ("停用".equals(state)) {
//					String sql = "select count(1) from SLM_LADING_BILL_DETAIL t " 
//							+" left join YDM_PRODUCT_DETAIL ypd on t.COILNO = ypd.COILNO"
//							+ " where t.BILL_NO = '"+ newheat.getBill_no() +"' and ypd.STATE = '0'";
//					int count = this.getMapper(PbModelDbMapper.class).doQueryCount(sql);
//					if (count > 0) {
//						rm.setState("500");
//						rm.setMsgInfo("该提单明细内存在 在库 的卷，无法作废该提单");
//						return rm;
//					}
//				}
//				// （20220302上午修改treals===）
//				if(!"1".equals(newheat.getValid_status())){		//编辑状态才可 启用停用
//					rm.setMsgInfo("当前状态无法"+state);
//					rm.setState("500");
//					return rm;
//				}
//				if("0".equals(heat.getValid_flag())){		//停用
//					heat.setDelete_man_no(userId);
//					heat.setDelete_man_name(userName);
//					heat.setDelete_time(new Date());
//					//连带行一起停用
//					SlmLadingBillLine line=new SlmLadingBillLine();
//					line.setBill_no(heat.getBill_no());
//					line.setValid_flag("1");
//					List<SlmLadingBillLine> lineList=this.getBean(SlmLadingBillLineServiceImpl.class).doQuery(line);
//					//删除占用
//					for(SlmLadingBillLine lines:lineList){
//						lines.setValid_flag("0");
//						lines.setDelete_man_no(userId);
//						lines.setDelete_man_name(userName);
//						lines.setDelete_time(new Date());
//						this.getBean(SlmLadingBillLineServiceImpl.class).doUpdate(lines);
//						
//
//						//释放资金占用
//						List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+lines.getContract_no()+"'", null, 0, 0);
//						if(heat_list.size()>0){
//							rm = this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(heat_list.get(0), null, lines, "102703","2");
//							//====================eason add 2019-06-26 ==========================
//							if("500".equals(rm.getState())){
//								throw new Exception(rm.getMsgInfo());
//							}
//							//================================================================
//						}
//						// 在资金释放之后再删除提单明细：20230220刘侣
//						this.getBean(SlmLadingBillLineServiceImpl.class).doInvalidDetail(lines.getLine_no());
//					}
//					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
//				}else{			//启用
//					rm.setState("500");
//					rm.setMsgInfo("无法启用，请重新新增数据");
//					return rm;
//					//					heat.setUpdate_man_no(userId);
//					//					heat.setUpdate_man_name(userName);
//					//					heat.setUpdate_time(new Date());
//					//					this.getMapper(SlmLadingBillHeatMapper.class).doEnable(heat);
//				}
//			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("废除失败"+ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 批量提交
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSubmitWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				//新增判断，有提单行才可提交
				SlmLadingBillLine line=new SlmLadingBillLine();
				line.setBill_no(heat.getBill_no());
				line.setValid_flag("1");
				List<SlmLadingBillLine> lineList=this.getBean(SlmLadingBillLineServiceImpl.class).doQuery(line);
				if("1".equals(heat.getValid_flag())&&"1".equals(heat.getValid_status())&&lineList.size()>0){		//有效的 编辑状态才能提交
					heat.setValid_status("2");		//待审核
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else{
					msg+=heat.getBill_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("提单"+msg.substring(0, msg.length()-1)+"无法提交，原因：非编辑状态或无有效提单行");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 批量撤回
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRollbackWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				if("2".equals(heat.getValid_status())||"3".equals(heat.getValid_status())||"4".equals(heat.getValid_status())){		
					//2：待审核 3：待下发  4：下发 统统能撤回
					heat.setValid_status("1");		//待审核
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else{
					msg+=heat.getBill_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("提单"+msg.substring(0, msg.length()-1)+"无法撤回");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 批量审核
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doPassWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				if("1".equals(heat.getValid_flag())&&"2".equals(heat.getValid_status())){		//有效的 待审核状态才能审核
					heat.setValid_status("3");		//待下发
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else{
					msg+=heat.getBill_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("提单"+msg.substring(0, msg.length()-1)+"无法审核");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 批量反审
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doNotPassWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				if("1".equals(heat.getValid_flag())&&"3".equals(heat.getValid_status())){		//有效的 待下发状态才能反审
					heat.setValid_status("2");		//待审核
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else{
					msg+=heat.getBill_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("提单"+msg.substring(0, msg.length()-1)+"无法反审");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 批量下发
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doIssuerWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				if("1".equals(heat.getValid_flag())&&"3".equals(heat.getValid_status())){		//有效的 待下发状态才能下发
					heat.setValid_status("4");		//4下发
					heat.setIssuer_man_no(userId);
					heat.setIssuer_man_name(userName);
					heat.setIssuer_time(new Date());
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else{
					msg+=heat.getBill_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("提单"+msg.substring(0, msg.length()-1)+"无法撤回");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 批量回收
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRecoveryWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			String msg="";
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				if("1".equals(heat.getValid_flag())&&("4".equals(heat.getValid_status()))){		//有效的 发运状态才能回收
					heat.setValid_status("3");		//待下发
					heat.setRecovery_man_no(userId);
					heat.setRecovery_man_name(userName);
					heat.setRecovery_time(new Date());
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else if ("11".equals(heat.getValid_status())) {
					//这里是处理一次结算异常
					String sql = "delete from spm_delivery_detail t where t.deliveryno = '"+heat.getBill_no()+"'";
					this.getMapper(PbModelDbMapper.class).doDeleteSql(sql);
					
					heat.setValid_status("3");		//待下发
					heat.setRecovery_man_no(userId);
					heat.setRecovery_man_name(userName);
					heat.setRecovery_time(new Date());
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else{
					msg+=heat.getBill_no()+"，";
				}
			}
			rm.setState("200");
			if(!"".equals(msg)){
				rm.setState("500");
				rm.setMsgInfo("提单"+msg.substring(0, msg.length()-1)+"无法撤回");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 接收for物流
	 * @throws Exception 
	 * */
	public ResultModel doReceiveWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat=sum.getObject();
		rm.setState("200");
		heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
		if("1".equals(heat.getValid_flag())&&("4".equals(heat.getValid_status()))){		//有效的 下发状态状态才能接收
			heat.setValid_status("5");		//接收
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
		}else{
			rm.setState("500");
			rm.setMsgInfo("有效的且状态为下发的提单才可接收");
		}
		return rm;
	}

	/**
	 * 发运for物流
	 * @throws Exception 
	 * */
	public ResultModel doDeliverWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat=sum.getObject();
		rm.setState("200");
		heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
		if("1".equals(heat.getValid_flag())&&("4".equals(heat.getValid_status())||"5".equals(heat.getValid_status()))){		//有效的 接收状态状态才能发运
			if("1".equals(heat.getBill_type()))
				heat.setValid_status("7");		//实际发运
			else
				heat.setValid_status("6");		//虚拟发运
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);

			//修改订单状态
			SlmLadingBillLine line=new SlmLadingBillLine();
			line.setValid_flag("1");
			line.setBill_no(heat.getBill_no());
			List<SlmLadingBillLine> lineList=this.getBean(SlmLadingBillLineServiceImpl.class).doQuery(line);
			for(SlmLadingBillLine lines:lineList){
				SlmOrderInfo order=new SlmOrderInfo();
				order.setContract_no(lines.getContract_no());
				order.setContract_line_seq(lines.getContract_line_seq());
				order.setOrder_seq(lines.getOrder_seq());
				List<SlmOrderInfo> order_list=this.getMapper(SlmOrderInfoMapper.class).find(order,0,0);
				if(order_list.size()>0){
					order=order_list.get(0);
					if(order!=null&&("103409".equals(order.getOrder_flag_no())||"103408".equals(order.getOrder_flag_no()))){
						order.setP_order_flag_no(order.getOrder_flag_no());
						order.setP_order_flag_name(order.getOrder_flag_name());
						order.setOrder_flag_no("103410");
						order.setOrder_flag_name("发货");
						this.getMapper(SlmOrderInfoMapper.class).update(order);
					}
				}
			}
		}else{
			rm.setState("500");
			rm.setMsgInfo("有效的且状态为下发的提单才可接收");
		}
		return rm;
	}

	/**
	 * 撤销接收for物流
	 * @throws Exception 
	 * */
	public ResultModel doCancelReceiveWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat=sum.getObject();
		rm.setState("200");
		heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
		if("1".equals(heat.getValid_flag())&&("5".equals(heat.getValid_status())||"6".equals(heat.getValid_status())||"7".equals(heat.getValid_status()))){		//有效的 接收状态才可取消接收
			heat.setValid_status("4");		//下发
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);

		}else{
			rm.setState("500");
			rm.setMsgInfo("有效的且状态为接收的提单才可撤销接收");
		}
		return rm;
	}

	/**
	 * 虚拟关闭for物流
	 * @throws Exception 
	 * */
	public ResultModel doSimulateCloseWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat=sum.getObject();
		rm.setState("200");
		heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
		if("1".equals(heat.getValid_flag())&&("5".equals(heat.getValid_status())||"6".equals(heat.getValid_status())||"7".equals(heat.getValid_status()))){		//有效的
			heat.setValid_status("10");		//虚拟关闭
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
		}else{
			rm.setState("500");
			rm.setMsgInfo("有效的且状态为接收发运的提单才可关闭");
		}
		return rm;
	}

	/**
	 * 实际关闭for物流
	 * @throws Exception 
	 * */
	public ResultModel doActualCloseWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat=sum.getObject();
		rm.setState("200");
		heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
		if("1".equals(heat.getValid_flag())&&("5".equals(heat.getValid_status())||"6".equals(heat.getValid_status())||"7".equals(heat.getValid_status()))){		//有效的
			heat.setValid_status("11");		//实际关闭
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
		}else{
			rm.setState("500");
			rm.setMsgInfo("有效的且状态为接收发运的提单才可关闭");
		}
		return rm;
	}

	/**
	 * 取消实际关闭for物流
	 * @throws Exception 
	 * */
	public ResultModel doCancelCloseWeb(CommonPage<SlmLadingBillHeat> 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);
		SlmLadingBillHeat heat=sum.getObject();
		rm.setState("200");
		heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
		if("1".equals(heat.getValid_flag())&&("10".equals(heat.getValid_status())||"11".equals(heat.getValid_status()))){		//有效的,为关闭的
			heat.setValid_status("10".equals(heat.getValid_status())?"6":"7");		//虚拟or实际发运
			heat.setUpdate_man_no(userId);
			heat.setUpdate_man_name(userName);
			heat.setUpdate_time(new Date());
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
		}else{
			rm.setState("500");
			rm.setMsgInfo("状态为关闭的提单才可撤销关闭");
		}
		return rm;
	}

	/**
	 * 详情
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat heat=sum.getObject();
		try{
			heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
			rm.setData(heat);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 查询打印时需要的数据
	 * */
	public ResultModel doQueryPrintWeb(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat one_heat=sum.getObject();
		List<SlmLadingBillHeat> list=sum.getObjectList();
		List<SlmLadingBillHeat> re_list=new ArrayList<SlmLadingBillHeat>();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			if(list==null){
				list=new ArrayList<SlmLadingBillHeat>();
				list.add(one_heat);
			}
			SlmLadingBillLine line=new SlmLadingBillLine();
			for(SlmLadingBillHeat heat:list){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				if(heat!=null){
//					SlmCustomerTransSolution solution=this.getBean(SlmCustomerTransSolutionServiceImpl.class).doQueryOne(heat.getSolutions_no());
//					if(solution!=null){
//						heat.setConsignee_name(solution.getConsignee_name());		//收货地址 联系人 联系电话
//						heat.setPhone(solution.getPhone());
//					}
					
					// 都从提单内取联系人和联系电话：20231128刘侣
					if (heat.getPlan_no() != null) {
						// 格式：联系人；联系电话
						String[] arr = heat.getPlan_no().split("；");
						heat.setConsignee_name(arr.length > 0 ? arr[0] : null);		//收货地址 联系人 联系电话
						heat.setPhone(arr.length > 1 ? arr[1] : null);
					}
					

					line.setBill_no(heat.getBill_no());
					List<SlmLadingBillLine> lineList=this.getBean(SlmLadingBillLineServiceImpl.class).doQuery(line);
					SlmLadingBillDetail detail=new SlmLadingBillDetail();
					double mao_weight=0d;  		//毛重
					double jing_weight=0d;
					for(SlmLadingBillLine lines:lineList){
						double weight=0d;
						detail.setLine_no(lines.getLine_no());
						List<SlmLadingBillDetail> detailList=this.getBean(SlmLadingBillDetailServiceImpl.class).doQuery(detail);
						for(SlmLadingBillDetail details:detailList){
							weight=DoubleUtil.add(weight,details.getTheoryweight() == null ? 0 : details.getTheoryweight());
							mao_weight=DoubleUtil.add(mao_weight, details.getFactweight());
							String lastChar = details.getCoilno().substring(details.getCoilno().length()-1);
							//if(details.getCoilno()!=null &&!"B".equals(lastChar))
							if(details.getCoilno()!=null)
								jing_weight=DoubleUtil.add(jing_weight, details.getFactweight());
							if(details.getButtressname()==null)
								details.setButtressname("");
						}
						lines.setBillweightsum(weight);
						lines.setBillList(detailList);
						SlmContractLineInfo contractLine=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryById(lines.getContract_line_no());
						if(contractLine!=null){
							lines.setThick(contractLine.getThick());			//厚
							lines.setWidth(contractLine.getWidth());		//宽
							heat.setStd_name(contractLine.getStd_name());     //标准名称
							SlmContractHeatInfo contractHeat=this.getBean(SlmContractHeatInfoServiceImpl.class).doQueryOne(contractLine.getContract_pk());
							if(contractHeat!=null)
								heat.setTax_registra_number(contractHeat.getTax_registra_number());		//税号
						}
					}
					heat.setFact_weight(String.valueOf(jing_weight));
					heat.setBillweightsum(String.valueOf(mao_weight));
					heat.setLineList(lineList);
					re_list.add(heat);
					heat.setPrint_man_no(userId);
					heat.setPrint_man_name(userName);
					heat.setPrint_time(new Date());
					heat.setPrint_num(heat.getPrint_num()+1);
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}
			}
			rm.setData(re_list);
			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 doCloseWeb(CommonPage<SlmLadingBillHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat heat=sum.getObject();
		try{
			if(heat.getValid_status()==null||"".equals(heat.getValid_status()))
				heat.setValid_status("10");		//关闭
			this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("关闭失败");
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 提单&结算单-核算
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAdjustWeb(CommonPage<SlmLadingBillHeat> 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<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				//实际发运&虚拟发运 才可进行核算,已核算的可重新进行核算
				if(heat!=null&&("10".equals(heat.getValid_status())||"11".equals(heat.getValid_status())||"12".equals(heat.getValid_status()))&&"1".equals(heat.getValid_flag())){
					if("12".equals(heat.getValid_status())){	//如果是重新核算，需将原来的三种费用清空
						rm=this.getBean(SlmFundSettleCarriageServiceImpl.class).doDelete(heat.getBill_no());
						if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
						rm=this.getBean(SlmFundSettleGoodServiceImpl.class).doDelete(heat.getBill_no());
						if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
						rm=this.getBean(SlmFundSettleOtherServiceImpl.class).doDelete(heat.getBill_no());
						if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
					}
					SlmLadingBillLine line=new SlmLadingBillLine();
					line.setBill_no(heat.getBill_no());
					line.setValid_flag("1");
					List<SlmLadingBillLine> lineList=this.getBean(SlmLadingBillLineServiceImpl.class).doQuery(line);
					for(SlmLadingBillLine lines:lineList){		//子提单下的费用核算
						//三种费用 新增
						rm=this.getBean(SlmLadingBillLineServiceImpl.class).doAddFund(heat,lines);	
						if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
					}
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					heat.setValid_status("12"); 	//票据核算
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 提单&结算单-取消核算
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelAdjustWeb(CommonPage<SlmLadingBillHeat> 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);
		List<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				//实际发运&虚拟发运 才可进行核算,已核算的可重新进行核算
				if(heat!=null&&"12".equals(heat.getValid_status())&&"1".equals(heat.getValid_flag())){
					//需将原来的三种费用清空
					rm=this.getBean(SlmFundSettleCarriageServiceImpl.class).doDelete(heat.getBill_no());
					if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
					rm=this.getBean(SlmFundSettleGoodServiceImpl.class).doDelete(heat.getBill_no());
					if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
					rm=this.getBean(SlmFundSettleOtherServiceImpl.class).doDelete(heat.getBill_no());
					if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					heat.setValid_status("11"); 	//实际关闭
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				}else{
					rm.setState("500");
					rm.setMsgInfo("提单["+heat.getBill_no()+"]状态不为票据核算，无法删除");
					return rm;
				}
			}
			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 doAlignWeb(CommonPage<SlmLadingBillHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			// =============eason add 2019-06-22===================
			String id="";
			for(SlmLadingBillHeat heat:heatList){
				id+="'"+heat.getBill_no()+"',";
			}
			if(!"".equals(id)){
				id=id.substring(0,id.length()-1);
				List<SlmFundBalancePriceApply> ls=this.getMapper(SlmFundBalancePriceApplyMapper.class).findWithCondition(null, " bill_no in ("+id+") and valid_flag not in ('3','4')", "", 0, 0);
				if(ls!=null&&ls.size()>0){
					String msg="";
					for(SlmFundBalancePriceApply sfba:ls){
						if(msg.indexOf(sfba.getBill_no())<0){
							msg+=sfba.getBill_no()+",";
						}
					}
					rm.setState("500");
					rm.setMsgInfo("提单："+msg+"存在结算单价申报且未完成处理的信息！");
					return rm;
				}
			}
			// ====================================================
			
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				//核算状态的方可对齐
				if(heat!=null&&"12".equals(heat.getValid_status())&&"1".equals(heat.getValid_flag())){
					heat.setValid_status("13"); 	//票据对齐
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
					//其下对应三种费用，改为对齐状态
					doChangeFundFlag(heat,1);
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	/**
	 * 提单&结算单-对齐 判断加工费运费 结算价 为  0，可隐藏
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInvalid(CommonPage<SlmLadingBillHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				//对齐状态后，判断隐藏
				if(heat!=null&&("13".equals(heat.getValid_status())||"12".equals(heat.getValid_status()))&&"1".equals(heat.getValid_flag())){
					SlmLadingBillLine line=new SlmLadingBillLine();
					line.setBill_no(heat.getBill_no());
					List<SlmLadingBillLine> list=this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(line,null, " valid_flag desc,create_time desc",0,0);
					for(SlmLadingBillLine lines:list){				
						SlmContractLineInfo contract_line=new SlmContractLineInfo();
						contract_line.setContract_no(lines.getContract_no());
						contract_line.setContract_line_seq(lines.getContract_line_seq());
						List<SlmContractLineInfo> lineList=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryWithCondition(contract_line, null, null, 0, 0);
						SlmOrderInfo order=new SlmOrderInfo();
						order.setContract_no(lines.getContract_no());
						order.setContract_line_seq(lines.getContract_line_seq());
						order.setOrder_seq(lines.getOrder_seq());
						//===============eason edit 2019-07-31 注释一行，新增一行=================
						//List<SlmOrderInfo> orderList = this.getBean(SlmOrderInfoServiceImpl.class).doQuery(order);
						
						List<SlmOrderInfo> orderList = this.getMapper(SlmOrderInfoMapper.class).findWithCondition(order, " (change_flag is null or change_flag != '1') ", "create_time desc", 0, 0);
						//=====================================================
						if(orderList.size()>0){
							lines.setWork_price(orderList.get(0).getWork_price());
							lines.setBalance_price(orderList.get(0).getBalance_price());
						}
						if(lineList.size()>0){
							lines.setTrade_price(lineList.get(0).getTrade_price());
							if(lines.getBalance_price()==0){
								lines.setTrade_price(0d);
							}
						}
						//带入申报过后的价格
						SlmFundBalancePriceApply apply=new SlmFundBalancePriceApply();
						apply.setBill_no(lines.getBill_no());
						apply.setLine_no(lines.getLine_no());
						apply.setValid_flag("3");
						List<SlmFundBalancePriceApply> apply_list=this.getMapper(SlmFundBalancePriceApplyMapper.class).find(apply,0,0);
						for(SlmFundBalancePriceApply applys:apply_list){
							SlmFundSettleCarriage carriage=this.getMapper(SlmFundSettleCarriageMapper.class).findById(applys.getObject_no());
							if(carriage!=null){
								lines.setTrade_price(applys.getNew_balance_price());
							}else{
								SlmFundSettleOther other=this.getMapper(SlmFundSettleOtherMapper.class).findById(applys.getObject_no());
								if(other!=null){
									lines.setWork_price(applys.getNew_balance_price());
								}else{
									SlmFundSettleGood good=this.getMapper(SlmFundSettleGoodMapper.class).findById(applys.getObject_no());
									if(good!=null){
										lines.setBalance_price(applys.getNew_balance_price());
									}
								}
							}
						}
						if(lines.getTrade_price()!=0||lines.getWork_price()!=0||lines.getBalance_price()!=0){
							rm.setState("500");
							rm.setMsgInfo("存在加工费，结算价，运费不全为0，操作失败");
							return rm;
						}
						//设置资金释放 slm_fund_third_account_used 的 flg = '1'
						
						//释放资金占用
						List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+lines.getContract_no()+"'", null, 0, 0);
						if(heat_list.size()>0){
							rm = this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(heat_list.get(0), null, lines, "102703","2");
							//====================eason add 2019-06-26 ==========================
							if("500".equals(rm.getState())){
								throw new Exception(rm.getMsgInfo());
							}
							//================================================================
						}
					}
					heat.setValid_status("15"); 	//票据隐藏状态
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
				
				}else{
					rm.setState("500");
					rm.setMsgInfo("提单["+heat.getBill_no()+"]状态不为票据对齐，无法隐藏");
					return rm;
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("加工费，结算价，运费不全为0，操作失败"+e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	/**
	 * 提单&结算单-取消对齐
	 * @throws Exception 
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doCancelAlignWeb(CommonPage<SlmLadingBillHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmLadingBillHeat> heatList=sum.getObjectList();
		try{
			for(SlmLadingBillHeat heat:heatList){
				heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(heat.getBill_no());
				//对齐状态的方可撤回
				if(heat!=null&&"13".equals(heat.getValid_status())&&"1".equals(heat.getValid_flag())){
					heat.setValid_status("12"); 	//核算
					this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
					//其下对应三种费用，改为编辑状态
					doChangeFundFlag(heat,2);
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	public ResultModel doChangeFundFlag(SlmLadingBillHeat heat,int version){
		ResultModel rm=new ResultModel();
		try{
			String flag="";
			String goods_flag="";
			switch(version){
			case 1:		//从 编辑  到 票据对齐
				flag="2";
				goods_flag="3";
				break;
			case 2:		//从 票据对齐 到 编辑 
				flag="1";
				goods_flag="1";
				break;
			default:break;
			}

			List<SlmFundSettleGood> goodList=this.getMapper(SlmFundSettleGoodMapper.class).findWithCondition(null, " bill_no='"+heat.getBill_no()+"'", null, 0, 0);
			for(SlmFundSettleGood goods:goodList){
				goods.setFlag(goods_flag);
				this.getMapper(SlmFundSettleGoodMapper.class).update(goods);
			}
			List<SlmFundSettleCarriage> carriageList=this.getMapper(SlmFundSettleCarriageMapper.class).findWithCondition(null, " bill_no='"+heat.getBill_no()+"'", null, 0, 0);
			for(SlmFundSettleCarriage carriages:carriageList){
				carriages.setFlag(flag);
				this.getMapper(SlmFundSettleCarriageMapper.class).update(carriages);
			}
			List<SlmFundSettleOther> otherList=this.getMapper(SlmFundSettleOtherMapper.class).findWithCondition(null, " bill_no='"+heat.getBill_no()+"'", null, 0, 0);
			for(SlmFundSettleOther others:otherList){
				others.setFlag(flag);
				this.getMapper(SlmFundSettleOtherMapper.class).update(others);
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 点击结算单 查询下面的提单，子提单和三种费用
	 * */
	public ResultModel doQueryBillWeb(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat param_heat=sum.getObject();
		String settle_no=sum.getMemo1();
		String flag=sum.getMemo2();		//1查看用 2新增用 3编辑用
		try{
			List<SlmLadingBillHeat> heatList=new ArrayList<SlmLadingBillHeat>();
			SlmFundSettleBillLine line=new SlmFundSettleBillLine();
			line.setSettle_bill_no(settle_no);
			List<SlmFundSettleBillLine> lineList=this.getMapper(SlmFundSettleBillLineMapper.class).find(line, 0, 0);
			if(param_heat==null) param_heat=new SlmLadingBillHeat();
			String sWhere=" valid_status='13' and valid_flag='1'";
			if(param_heat.getContract_no()!=null&&!"".equals(param_heat.getContract_no())){
				sWhere+=" and contract_no like concat(CONCAT('%','"+param_heat.getContract_no()+"'),'%')";
				param_heat.setContract_no(null);
			}
			List<SlmLadingBillHeat> bill_list=this.getMapper(SlmLadingBillHeatMapper.class).findWithCondition(param_heat,sWhere , " create_time desc,contract_no desc", 0, 0);
			if("1".equals(flag)||"3".equals(flag)){
				for(SlmFundSettleBillLine lines:lineList){
					SlmLadingBillHeat heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(lines.getBill_no());
					heatList.add(heat);
				}
				if("3".equals(flag))
					heatList.addAll(bill_list);
			}
			if("2".equals(flag)){
				heatList.addAll(bill_list);
			}
			for(SlmLadingBillHeat heats:heatList){
				Double total=0d;
				//三种费用
				List<SlmFundSettleGood> goodList=this.getMapper(SlmFundSettleGoodMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
				for(SlmFundSettleGood goods:goodList){
					total=DoubleUtil.add(total, goods.getBalance_amount());
				}
				List<SlmFundSettleCarriage> carriageList=this.getMapper(SlmFundSettleCarriageMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
				for(SlmFundSettleCarriage carriages:carriageList){
					total=DoubleUtil.add(total, carriages.getSettle_carriage_fund());
				}
				List<SlmFundSettleOther> otherList=this.getMapper(SlmFundSettleOtherMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
				for(SlmFundSettleOther others:otherList){
					total=DoubleUtil.add(total, others.getSettle_other_fund());
				}
				heats.setCarriageList(carriageList);
				heats.setGoodList(goodList);
				heats.setOtherList(otherList);
				heats.setTotal_fund(total);
			}
			rm.setData(heatList);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 回款管理
	 * 查询 当月未结算量
	 * */
	public ResultModel doQueryMonthSettle(CommonPage<SlmLadingBillHeat> sum) {
		ResultModel rm=new ResultModel();
		if(sum==null) sum=new CommonPage<SlmLadingBillHeat>();
		String date=sum.getMemo1();
		ArrayList<SlmLadingBillHeat> return_list=new ArrayList<SlmLadingBillHeat>();
		try{
			if(date==null||"".equals(date)){
				date=new SimpleDateFormat("yyyyMM").format(new Date());
			}
			SlmLadingBillHeat one=new SlmLadingBillHeat();
			SlmLadingBillHeat two=new SlmLadingBillHeat();
			double one_weight=0d;
			double one_money=0d;
			double two_weight=0d;
			double two_money=0d;
			List<SlmLadingBillHeat> list=this.getMapper(SlmLadingBillHeatMapper.class).doQueryMonthSettle(date);
			for(SlmLadingBillHeat heats:list){
				if(heats.getSettle_flag()==null){
					one_weight=DoubleUtil.add(one_weight, heats.getWeight());
					one_money=DoubleUtil.add(one_money, heats.getTotal_fund());
				}else if(heats.getSettle_flag()!=null&&Integer.parseInt(heats.getSettle_flag())<5){
					two_weight=DoubleUtil.add(two_weight, heats.getWeight());
					two_money=DoubleUtil.add(two_money, heats.getTotal_fund());
				}
			}
			one.setWeight(one_weight);
			one.setTotal_fund(one_money);
			two.setWeight(two_weight);
			two.setTotal_fund(two_money);
			return_list.add(one);
			return_list.add(two);
			rm.setData(return_list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	public SlmLadingBillHeat doQueryOne(String planNo) {
		return this.getMapper(SlmLadingBillHeatMapper.class).findById(planNo);
	}

	@SuppressWarnings("unchecked")
	public ResultModel doExportExcel(CommonPage<SlmLadingBillHeat> sum){
		
		ResultModel rm = new ResultModel();
		try {
			int rowindex = 1;
			ArrayList<Integer> rowlist = new ArrayList<Integer>();
			rm = this.getBean(LmsApiServiceImpl.class).BillHeat_doQueryWeb(sum);
			List<SlmLadingBillHeat> list = ((PageModel<SlmLadingBillHeat>)rm.getData()).getRows();
			// 1，创建一个webbook，对应一个Excel文件
			WritableWorkbook workbook;
			//2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator;  //临时保存路径
			File dir = new File(path);
			if(!dir.exists()) {
				new File(path).mkdir();
			}
			Calendar cal = Calendar.getInstance();
			String year=cal.get(Calendar.YEAR)+"年";
			String month=(cal.get(Calendar.MONTH)+1)+"月";
			String dept=cal.get(Calendar.DATE)+"日";
			String filename = year + month + dept + "提货单跟踪报表";
			String file=filename+".xls";  //文件名
			//3. 操作EXCEL文件
			workbook = Workbook.createWorkbook(new File(path+file));
			WritableSheet sheet = workbook.createSheet("提货单跟踪报表", 1);
			//行高
			sheet.getSettings().setDefaultRowHeight(300);
			//列宽 
			sheet.getSettings().setDefaultColumnWidth(3000);
			CellView cellview =new CellView();
			cellview.setAutosize(true);
			cellview.setSize(2500);
			//字体  参数可自行配置
			WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
			WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
			cellFormat1.setAlignment(Alignment.CENTRE);
			cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
			
			WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
			WritableCellFormat cellFormat = new WritableCellFormat(font); 
			cellFormat.setAlignment(Alignment.CENTRE);
			cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
			//时间转字符串的格式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			//提货单表头
			sheet.mergeCells(0, 0, 0, 1);
			sheet.addCell(new Label(0, 0,"序号",cellFormat1));
			sheet.mergeCells(1, 0, 1, 1);
			sheet.addCell(new Label(1,0,"提单编号",cellFormat1));
			sheet.mergeCells(2, 0, 2, 1);
			sheet.addCell(new Label(2,0,"合同号",cellFormat1));
			sheet.mergeCells(3, 0, 3, 1);
			sheet.addCell(new Label(3,0,"客户名称",cellFormat1));
			sheet.mergeCells(4, 0, 4, 1);
			sheet.addCell(new Label(4,0,"收货单位",cellFormat1));
			sheet.mergeCells(5, 0, 5, 1);
			sheet.addCell(new Label(5,0,"收货地址",cellFormat1));
			sheet.mergeCells(6, 0, 6, 1);
			sheet.addCell(new Label(6,0,"理重",cellFormat1));
			sheet.mergeCells(7, 0, 7, 1);
			sheet.addCell(new Label(7,0,"实重",cellFormat1));
			sheet.mergeCells(8, 0, 8, 1);
			sheet.addCell(new Label(8,0,"供货单位",cellFormat1));
			sheet.mergeCells(9, 0, 9, 1);
			sheet.addCell(new Label(9,0,"供货地址",cellFormat1));
			sheet.mergeCells(10, 0, 10, 1);
			sheet.addCell(new Label(10,0,"承运单位",cellFormat1));
			sheet.mergeCells(11, 0, 11, 1);
			sheet.addCell(new Label(11,0,"运输方案",cellFormat1));
			sheet.mergeCells(12, 0, 12, 1);
			sheet.addCell(new Label(12,0,"提单类型",cellFormat1));
			sheet.mergeCells(13, 0, 14, 0);
			sheet.addCell(new Label(13,0,"有效期",cellFormat1));
			sheet.addCell(new Label(13,1,"开始时间",cellFormat1));
			sheet.addCell(new Label(14,1,"结束时间",cellFormat1));
			sheet.mergeCells(15, 0, 16, 0);
			sheet.addCell(new Label(15,0,"创建",cellFormat1));
			sheet.addCell(new Label(15,1,"创建人",cellFormat1));
			sheet.addCell(new Label(16,1,"时间",cellFormat1));
			sheet.mergeCells(17, 0, 18, 0);
			sheet.addCell(new Label(17,0,"修改",cellFormat1));
			sheet.addCell(new Label(17,1,"修改人",cellFormat1));
			sheet.addCell(new Label(18,1,"时间",cellFormat1));
			sheet.mergeCells(19, 0, 20, 0);
			sheet.addCell(new Label(19,0,"废除",cellFormat1));
			sheet.addCell(new Label(19,1,"废除人",cellFormat1));
			sheet.addCell(new Label(20,1,"时间",cellFormat1));
			sheet.mergeCells(21, 0, 22, 0);
			sheet.addCell(new Label(21,0,"下发",cellFormat1));
			sheet.addCell(new Label(21,1,"下发人",cellFormat1));
			sheet.addCell(new Label(22,1,"时间",cellFormat1));
			sheet.mergeCells(23, 0, 23, 1);
			sheet.addCell(new Label(23,0,"备注",cellFormat1));
			sheet.mergeCells(24, 0, 24, 1);
			sheet.addCell(new Label(24,0,"提单状态",cellFormat1));
			sheet.mergeCells(25, 0, 25, 1);
			sheet.addCell(new Label(25,0,"有效标志",cellFormat1));
			
			for(int i = 0; i < list.size(); i++) {
				rowindex++;
				//序号
				sheet.addCell(new Label(0,rowindex,""+(i+1),cellFormat));
				if(list.get(i).getBill_no() != null && !"".equals(list.get(i).getBill_no())) {
					sheet.addCell(new Label(1,rowindex,list.get(i).getBill_no(),cellFormat));
					sheet.setColumnView(1,list.get(i).getBill_no().getBytes().length+6);
				}
				if(list.get(i).getContract_no() != null && !"".equals(list.get(i).getContract_no())) {
					sheet.addCell(new Label(2,rowindex,list.get(i).getContract_no(),cellFormat));
				}
				if(list.get(i).getCustomer_name() != null && !"".equals(list.get(i).getCustomer_name())) {
					sheet.addCell(new Label(3,rowindex,list.get(i).getCustomer_name(),cellFormat));
					sheet.setColumnView(3,list.get(i).getCustomer_name().getBytes().length+2);
				}
				if(list.get(i).getReciver_unit_name() != null && !"".equals(list.get(i).getReciver_unit_name())) {
					sheet.addCell(new Label(4,rowindex,list.get(i).getReciver_unit_name(),cellFormat));
					sheet.setColumnView(4,list.get(i).getReciver_unit_name().getBytes().length+2);
				}
				if(list.get(i).getReciver_address() != null && !"".equals(list.get(i).getReciver_address())) {
					sheet.addCell(new Label(5,rowindex,list.get(i).getReciver_address(),cellFormat));
					sheet.setColumnView(5,list.get(i).getReciver_address().getBytes().length+2);
				}
				if(list.get(i).getAll_fact_weight() != null && !"".equals(list.get(i).getAll_fact_weight())) {
					sheet.addCell(new Label(6,rowindex,list.get(i).getAll_fact_weight(),cellFormat));
				}
				if(list.get(i).getAll_theory_weight() != null && !"".equals(list.get(i).getAll_theory_weight())) {
					sheet.addCell(new Label(7,rowindex,list.get(i).getAll_theory_weight(),cellFormat));
				}
				if(list.get(i).getSupplier_unit_name() != null && !"".equals(list.get(i).getSupplier_unit_name())) {
					sheet.addCell(new Label(8,rowindex,list.get(i).getSupplier_unit_name(),cellFormat));
					sheet.setColumnView(8,list.get(i).getSupplier_unit_name().getBytes().length+2);
				}
				if(list.get(i).getSupplier_address() != null && !"".equals(list.get(i).getSupplier_address())) {
					sheet.addCell(new Label(9,rowindex,list.get(i).getSupplier_address(),cellFormat));
					sheet.setColumnView(9,list.get(i).getSupplier_address().getBytes().length+2);
				}
				if(list.get(i).getTrans_unit_name() != null && !"".equals(list.get(i).getTrans_unit_name())) {
					sheet.addCell(new Label(10,rowindex,list.get(i).getTrans_unit_name(),cellFormat));
					sheet.setColumnView(10,list.get(i).getTrans_unit_name().getBytes().length+2);
				}
				if(list.get(i).getSolutions_name() != null && !"".equals(list.get(i).getSolutions_name())) {
					sheet.addCell(new Label(11,rowindex,list.get(i).getSolutions_name(),cellFormat));
					sheet.setColumnView(11,list.get(i).getSolutions_name().getBytes().length+2);
				}
				if(list.get(i).getBill_type() != null && !"".equals(list.get(i).getBill_type())) {
					String billType = "";
					if(list.get(i).getBill_type().equals("1")) {
						billType = "实际提单";
					} else if (list.get(i).getBill_type().equals("2")) {
						billType = "虚拟提单";
					}
					sheet.addCell(new Label(12,rowindex,billType,cellFormat));
					sheet.setColumnView(12, billType.getBytes().length+2);
				}
				SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
				if(list.get(i).getEffect_start_time() != null) {
					sheet.addCell(new Label(13,rowindex,sdf1.format(list.get(i).getEffect_start_time()),cellFormat));
					sheet.setColumnView(13,cellview);
				}
				if(list.get(i).getEffect_end_time() != null) {
					sheet.addCell(new Label(14,rowindex,sdf1.format(list.get(i).getEffect_end_time()),cellFormat));
					sheet.setColumnView(14,cellview);
				}
				if(list.get(i).getCreate_man_name() != null && !"".equals(list.get(i).getCreate_man_name())) {
					sheet.addCell(new Label(15,rowindex,list.get(i).getCreate_man_name(),cellFormat));
					sheet.setColumnView(15, list.get(i).getCreate_man_name().getBytes().length+2);
				}
				if(list.get(i).getCreate_time() != null) {
					sheet.addCell(new Label(16,rowindex,sdf.format(list.get(i).getCreate_time()),cellFormat));
					sheet.setColumnView(16,cellview);
				}
				if(list.get(i).getUpdate_man_name() != null && !"".equals(list.get(i).getUpdate_man_name())) {
					sheet.addCell(new Label(17,rowindex,list.get(i).getUpdate_man_name(),cellFormat));
					sheet.setColumnView(17, list.get(i).getUpdate_man_name().getBytes().length+2);
				}
				if(list.get(i).getUpdate_time() != null) {
					sheet.addCell(new Label(18,rowindex,sdf.format(list.get(i).getUpdate_time()),cellFormat));
					sheet.setColumnView(18,cellview);
				}
				if(list.get(i).getDelete_man_name() != null && !"".equals(list.get(i).getDelete_man_name())) {
					sheet.addCell(new Label(19,rowindex,list.get(i).getDelete_man_name(),cellFormat));
					sheet.setColumnView(19, list.get(i).getDelete_man_name().getBytes().length+2);
				}
				if(list.get(i).getDelete_time() != null) {
					sheet.addCell(new Label(20,rowindex,sdf.format(list.get(i).getDelete_time()),cellFormat));
					sheet.setColumnView(20,cellview);
				}
				if(list.get(i).getIssuer_man_name() != null && !"".equals(list.get(i).getIssuer_man_name())) {
					sheet.addCell(new Label(21,rowindex,list.get(i).getIssuer_man_name(),cellFormat));
					sheet.setColumnView(21,list.get(i).getIssuer_man_name().getBytes().length+2);
				}
				if(list.get(i).getIssuer_time() != null) {
					sheet.addCell(new Label(22,rowindex,sdf.format(list.get(i).getIssuer_time()),cellFormat));
					sheet.setColumnView(22,cellview);
				}
				if(list.get(i).getMemo() != null && !"".equals(list.get(i).getMemo())) {
					sheet.addCell(new Label(23,rowindex,list.get(i).getMemo(),cellFormat));
					sheet.setColumnView(23,list.get(i).getMemo().getBytes().length+2);
				}
				if(list.get(i).getValid_status() != null && !"".equals(list.get(i).getValid_status())) {
					String validStatus = "";
					if(list.get(i).getValid_status().equals("1")) {
						validStatus = "编辑";
					} else if (list.get(i).getValid_status().equals("2")) {
						validStatus = "待审核";
					} else if (list.get(i).getValid_status().equals("3")) {
						validStatus = "待下发";
					} else if (list.get(i).getValid_status().equals("4")) {
						validStatus = "下发";
					} else if (list.get(i).getValid_status().equals("5")) {
						validStatus = "接收";
					} else if (list.get(i).getValid_status().equals("6")) {
						validStatus = "虚拟发运";
					} else if (list.get(i).getValid_status().equals("7")) {
						validStatus = "实际发运";
					} else if (list.get(i).getValid_status().equals("8")) {
						validStatus = "虚拟结算";
					} else if (list.get(i).getValid_status().equals("9")) {
						validStatus = "实际结算";
					} else if (list.get(i).getValid_status().equals("10")) {
						validStatus = "虚拟关闭";
					} else if (list.get(i).getValid_status().equals("11")) {
						validStatus = "实际关闭";
					} else if (list.get(i).getValid_status().equals("12")) {
						validStatus = "票据核算";
					} else if (list.get(i).getValid_status().equals("13")) {
						validStatus = "票据对齐";
					} else if (list.get(i).getValid_status().equals("14")) {
						validStatus = "结算编制";
					}
					sheet.addCell(new Label(24,rowindex,validStatus,cellFormat));
					sheet.setColumnView(24, validStatus.getBytes().length+2);
				}
				if(list.get(i).getValid_flag() != null && !"".equals(list.get(i).getValid_flag())) {
					String validFlag = "";
					if(list.get(i).getValid_flag().equals("1")) {
						validFlag = "有效";
					} else if(list.get(i).getValid_flag().equals("0")) {
						validFlag = "无效";
					}
					sheet.addCell(new Label(25,rowindex,validFlag,cellFormat));
					sheet.setColumnView(25,validFlag.getBytes().length+2);
				}
				
				List<SlmLadingBillLine> list2 = new ArrayList<SlmLadingBillLine>();
				List<SlmLadingBillDetail> list3 = new ArrayList<SlmLadingBillDetail>();
				SlmLadingBillLine lines = new SlmLadingBillLine();
				lines.setBill_no(list.get(i).getBill_no());
				list2.addAll(this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(lines,
								null, " valid_flag desc,create_time desc",(1 - 1) * 100000, 100000));
				if(list2 != null){
					for(int j = 0; j < list2.size(); j++){
						SlmLadingBillDetail details = new SlmLadingBillDetail();
						details.setLine_no(list2.get(j).getLine_no());
						list3.addAll(this.getMapper(SlmLadingBillDetailMapper.class).findBillDetail(details));
					}
					if(list3 != null){
						rowindex++;
						rowlist.add(rowindex);
						//提货单明细表头
						sheet.mergeCells(1, rowindex, 1, rowindex+1);
						sheet.addCell(new Label(1,rowindex,"序号",cellFormat1));
						sheet.mergeCells(2, rowindex, 2, rowindex+1);
						sheet.addCell(new Label(2,rowindex,"明细编号",cellFormat1));
						sheet.mergeCells(3, rowindex, 3, rowindex+1);
						sheet.addCell(new Label(3,rowindex,"原料卷号",cellFormat1));
						sheet.mergeCells(4, rowindex, 4, rowindex+1);
						sheet.addCell(new Label(4,rowindex,"卷号",cellFormat1));
						sheet.mergeCells(5, rowindex, 5, rowindex+1);
						sheet.addCell(new Label(5,rowindex,"标准号",cellFormat1));
						sheet.mergeCells(6, rowindex, 6, rowindex+1);
						sheet.addCell(new Label(6,rowindex,"产品名称",cellFormat1));
						sheet.mergeCells(7, rowindex, 7, rowindex+1);
						sheet.addCell(new Label(7,rowindex,"厚",cellFormat1));
						sheet.mergeCells(8, rowindex, 8, rowindex+1);
						sheet.addCell(new Label(8,rowindex,"宽",cellFormat1));
						sheet.mergeCells(9, rowindex, 9, rowindex+1);
						sheet.addCell(new Label(9,rowindex,"长度",cellFormat1));
						sheet.mergeCells(10, rowindex, 10, rowindex+1);
						sheet.addCell(new Label(10,rowindex,"块数",cellFormat1));
						sheet.mergeCells(11, rowindex, 11, rowindex+1);
						sheet.addCell(new Label(11,rowindex,"实重",cellFormat1));
						sheet.mergeCells(12, rowindex, 12, rowindex+1);
						sheet.addCell(new Label(12,rowindex,"理重",cellFormat1));
						sheet.mergeCells(13, rowindex, 14, rowindex);
						sheet.addCell(new Label(13,rowindex,"创建",cellFormat1));
						sheet.addCell(new Label(13,rowindex+1,"创建人",cellFormat1));
						sheet.addCell(new Label(14,rowindex+1,"时间",cellFormat1));
						rowindex++;
						
						for(int k = 0; k < list3.size(); k++){
							
							rowindex++;
							sheet.addCell(new Label(1,rowindex,""+(k+1),cellFormat));
							if(list3.get(k).getDetail_no() != null && !"".equals(list3.get(k).getDetail_no())) {
								sheet.addCell(new Label(2,rowindex,list3.get(k).getDetail_no(),cellFormat));
								sheet.setColumnView(2,list3.get(k).getDetail_no().getBytes().length+6);
							}
							if(list3.get(k).getMaterailcoilno() != null && !"".equals(list3.get(k).getMaterailcoilno())) {
								sheet.addCell(new Label(3,rowindex,list3.get(k).getMaterailcoilno(),cellFormat));
							}
							if(list3.get(k).getCoilno() != null && !"".equals(list3.get(k).getCoilno())) {
								sheet.addCell(new Label(4,rowindex,list3.get(k).getCoilno(),cellFormat));
							}
							if(list3.get(k).getStd_code() != null && !"".equals(list3.get(k).getStd_code())) {
								sheet.addCell(new Label(5,rowindex,list3.get(k).getStd_code(),cellFormat));
							}
							if(list3.get(k).getProd_name() != null && !"".equals(list3.get(k).getProd_name())) {
								sheet.addCell(new Label(6,rowindex,list3.get(k).getProd_name(),cellFormat));
								sheet.setColumnView(6,list3.get(k).getProd_name().getBytes().length+2);
							}
							if(list3.get(k).getThick() != null && !"".equals(list3.get(k).getThick())) {
								sheet.addCell(new Label(7,rowindex,String.valueOf(list3.get(k).getThick()),cellFormat));
							}
							if(list3.get(k).getWidth() != null && !"".equals(list3.get(k).getWidth())) {
								sheet.addCell(new Label(8,rowindex,String.valueOf(list3.get(k).getWidth()),cellFormat));
							}
							if(list3.get(k).getLen() != null && !"".equals(list3.get(k).getLen())) {
								sheet.addCell(new Label(9,rowindex,String.valueOf(list3.get(k).getLen()),cellFormat));
							}
							if(list3.get(k).getBlock_num() != null && !"".equals(list3.get(k).getBlock_num())) {
								sheet.addCell(new Label(10,rowindex,String.valueOf(list3.get(k).getBlock_num()),cellFormat));
							}
							if(list3.get(k).getFactweight() != null && !"".equals(list3.get(k).getFactweight())) {
								sheet.addCell(new Label(11,rowindex,String.valueOf(list3.get(k).getFactweight()),cellFormat));
							}
							if(list3.get(k).getTheoryweight() != null && !"".equals(list3.get(k).getTheoryweight())) {
								sheet.addCell(new Label(12,rowindex,String.valueOf(list3.get(k).getTheoryweight()),cellFormat));
							}
							if(list3.get(k).getCreate_man_name() != null && !"".equals(list3.get(k).getCreate_man_name())) {
								sheet.addCell(new Label(13,rowindex,list3.get(k).getCreate_man_name(),cellFormat));
							}
							if(list3.get(k).getCreate_time() != null) {
								sheet.addCell(new Label(14,rowindex,sdf.format(list3.get(k).getCreate_time()),cellFormat));
							}
						}
						rowlist.add(rowindex);
					}
				}
			}
			for(int l = 0;l < rowlist.size(); ){
				sheet.setRowGroup(rowlist.get(l), rowlist.get(l+1), false);
				l+=2;
			}
			sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
			sheet.getSettings().setVerticalFreeze(2);
			//关闭
			workbook.write();
			workbook.close();

			rm.setData("/download?filename="+file);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 2019-09-02 eason add
	 * 火运主提单新增
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddTranWeb(CommonPage<SlmLadingBillHeat> sum) throws Exception{
		ResultModel rm=new ResultModel();
//		this.getSession().setAttribute(HomeService.SESSION_USER_ID,"admin");
//		this.getSession().setAttribute(HomeService.SESSION_USER_NAME,"admin");
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		SlmLadingBillHeat heat = sum.getObject();
		SlmDeliveryPlanLine line = new SlmDeliveryPlanLine();
		String order_nature=sum.getMemo1();
		try{
			String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
			String id = date;
			int count=this.getMapper(SlmLadingBillHeatMapper.class).findMaxId(date);
			count++;
			String seq=String.format("%05d", count);
			id+=seq;
			if(order_nature!=null){
				if("1".equals(order_nature)){
					id="Y"+id;
				}else if("2".equals(order_nature)){
					id="J"+id;
				}else if("4".equals(order_nature)||"5".equals(order_nature)){
					id="L"+id;
				}
			}
			line.setPlan_no(sum.getObject().getPlan_no());
			List<SlmDeliveryPlanLine> list2 = this.getMapper(SlmDeliveryPlanLineMapper.class).findWithCondition(line, null, "create_time desc,valid_flag desc", (1-1)*100000,100000);
			if(list2!=null){
				heat.setBill_no(id);
				heat.setContract_no(list2.get(0).getContract_no());
				heat.setCreate_man_no(userId);
				heat.setCreate_man_name(userName);
				heat.setCreate_time(new Date());
				heat.setValid_status("1");		//编辑
				heat.setValid_flag("1");
				heat.setPrint_num(sum.getObject().getPrint_num());
				this.getMapper(SlmLadingBillHeatMapper.class).insert(heat);
				
				rm.setState("200");
			}
			else{
				rm.setState("500");
				rm.setMsgInfo("发运计划无发运行信息，无法添加提货单");
				return rm;				
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("提单新增失败"+ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	/**
	 * 2019-09-12 query
	 * 票据对齐的查询
	 * @throws Exception 
	 * */
	public ResultModel doQueryFundWeb(CommonPage<SlmLadingBillHeat> sum){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat heat=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmLadingBillHeat> pm=new PageModel<SlmLadingBillHeat>(pageIndex, pageSize);
		String flag=sum.getMemo1();			//页面区分
		String coilno=sum.getMemo2();		//卷号
		String JY=sum.getMemo3();
		List<SlmLadingBillHeat> list=new ArrayList<SlmLadingBillHeat>();
		long count=0;
		try{
			String sWhere=" 1=1 ";
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			if(!"5".equals(flag)&&!"4".equals(flag)&&heat.getEffect_start_time()!=null){
				String timeColumn="Effect_start_time";
				sWhere+=" and '"+sdf.format(heat.getEffect_start_time())+"' <=to_char("+timeColumn+", 'yyyy-mm-dd') ";
				heat.setEffect_start_time(null);
			}
			if(!"5".equals(flag)&&!"4".equals(flag)&&heat.getEffect_end_time()!=null){
				String timeColumn="Effect_end_time";
				sWhere+=" and '"+sdf.format(heat.getEffect_end_time())+"' >=to_char("+timeColumn+", 'yyyy-mm-dd') ";
				heat.setEffect_end_time(null);				
			}
			if(!"5".equals(flag)&&!"4".equals(flag)&&heat.getBill_no()!=null){
				sWhere+=" and bill_no like '%"+heat.getBill_no()+"%' ";
				heat.setBill_no(null);				
			}
			if(!"5".equals(flag)&&!"4".equals(flag)&&heat.getContract_no()!=null){
				sWhere+=" and contract_no like '%"+heat.getContract_no()+"%' ";
				heat.setContract_no(null);				
			}
			if("1".equals(flag)){
				sWhere+=" and valid_status in('2','3')";
			}
			if("2".equals(flag)){
				sWhere+=" and valid_status in('3','4')";
			}
			if("3".equals(flag)){
				sWhere+=" and valid_status in('4')";
				//sOrder=" issuer_time desc";
			}
			if(JY!=null&&!"".equals(JY)){
				if("J".equals(JY))
					sWhere+=" and bill_no like 'J%'";
				if("Y".equals(JY))
					sWhere+=" and bill_no like 'Y%'";
			}
			
			if("4".equals(flag)){			//为资金结算-核算界面查询
				list=this.getMapper(SlmLadingBillHeatMapper.class).doQueryAdjust(heat,coilno,JY);
			}
			if("5".equals(flag)){			//为资金结算-对齐查询
				if (StringUtils.isNotEmpty(sum.getMemo2()) && "1".equals(sum.getMemo2())) { //查询【价格为0】
					sWhere += " and (sg.balance_good_price + cg.carriage_price + og.other_price) = 0";
				}
				list=this.getMapper(SlmLadingBillHeatMapper.class).doQueryAlign(heat,sWhere);
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 冲减头尾卷（冷轧订单，分条出来的头尾卷）
	 * @param sum
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddLadingBillDetail_H(CommonPage<SlmLadingBillHeat> cp) 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);
		Date now = new Date();
		SlmLadingBillHeat heat = cp.getObject();				
		try{
			//TODO 头尾卷的理重为null,在票据核算界面没法显示
			
			//1.1 判断订单属性
			List<SlmOrderInfo> soiList = this.getMapper(SlmLadingBillHeatMapper.class).doQuaryOrderNatureByBillno(heat.getBill_no());
			if (soiList!=null & soiList.size()>0) {
				for (SlmOrderInfo soi : soiList) {
					if (!"4".equals(soi.getOrder_nature())) {
						rm.setState("500");
						rm.setMsgInfo("只有冷轧订单才能进行头尾卷冲减！");
						return rm;
					}
				}
			}
			
			//1.2 判断当前冲减是新增还是删除
			String condition = " bill_no = '"+heat.getBill_no()+"' and coilno like '%H'";
			List<SlmLadingBillDetail> list= this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, condition, null, 0, 0);
			if (list!=null && list.size()>0) {
				//执行删除边丝冲减信息操作
				for (SlmLadingBillDetail bd : list) {
					this.getMapper(SlmLadingBillDetailMapper.class).delete(bd.getDetail_no() );
				}
				rm.setMsgInfo("冲减头尾卷，删除头尾卷成功！");
			}else {
				//执行新增边丝冲减信息操作
				//1.获取当前提货单下的所有提单明细，来确定机台。只有分条出来的头尾卷才能进行冲减
				List<SlmLadingBillDetail> slbdList = this.getMapper(SlmLadingBillHeatMapper.class).doQuaryYpdHInfo(heat);
				if (slbdList==null || slbdList.size()<=0) {
					throw new Exception("当前提单下的原料卷不存在头尾卷信息，无法冲减！");
				}
				for (SlmLadingBillDetail bd : slbdList) {
					if (!"M0001".equals(bd.getMachine_code()) && !"M0002".equals(bd.getMachine_code())) {
						throw new Exception("原料卷【"+bd.getMaterailcoilno()+"】的头尾卷不属于分条，无法冲减!");
					}
					//2.新增提单明细
					SlmLadingBillDetail slbd = new SlmLadingBillDetail();
					int count1 = this.getMapper(SlmLadingBillDetailMapper.class).countWithCondition(null," LINE_NO like concat('"+bd.getLine_no()+"','%')")+1;				
					slbd.setDetail_no(bd.getLine_no()+String.format("%03d", count1));//Id
					slbd.setLine_no(bd.getLine_no());
					slbd.setBill_no(bd.getBill_no());
					slbd.setOrder_no(bd.getOrder_no());
					slbd.setOrder_seq(bd.getOrder_seq());
					slbd.setContract_no(bd.getContract_no());
					slbd.setContract_pk(bd.getContract_pk());
					slbd.setContract_line_no(bd.getContract_line_no());
					slbd.setContract_line_seq(bd.getContract_line_seq());
					slbd.setCustomer_no(bd.getCustomer_no());
					slbd.setCustomer_name(bd.getCustomer_name());
					slbd.setReciver_unit_no(bd.getReciver_unit_no());
					slbd.setReciver_unit_name(bd.getReciver_unit_name());
					slbd.setCoilno(bd.getCoilno());
					slbd.setBoxno(bd.getBoxno());
					slbd.setStd_code(bd.getStd_code());
					slbd.setStd_name(bd.getStd_name());
					slbd.setJudgesteelcode(bd.getJudgesteelcode());
					slbd.setJudgesteelcname(bd.getSteel_name());
					slbd.setProd_code(bd.getProd_code());
					slbd.setProd_name(bd.getProd_name());
					slbd.setThick(bd.getThick());
					slbd.setWidth(bd.getWidth());
					slbd.setLen(bd.getLen());
					slbd.setMaterailcoilno(bd.getMaterailcoilno());
					slbd.setCreate_man_no(userId);
					slbd.setCreate_man_name(userName);
					slbd.setCreate_time(now);
					slbd.setFactweight(-1 * (bd.getFactweight()==null?0:bd.getFactweight()) / 1000);
					slbd.setTheoryweight(slbd.getFactweight());
					// 转库费单价和资金占用费单价：
					slbd.setZkf_u_price(bd.getZkf_u_price());
					slbd.setZj_u_price(bd.getZj_u_price());
					this.getMapper(SlmLadingBillDetailMapper.class).insert(slbd);
				}
				rm.setMsgInfo("冲减头尾卷，新增头尾卷成功！");
			}	
			
			//调整客户结算货款信息表的重量SLM_FUND_SETTLE_GOOD
			//调整客户结算运费信息表的重量SLM_FUND_SETTLE_CARRIAGE
			//调整客户结算出库费信息表的重量 SLM_FUND_SETTLE_OTHER
			
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("头尾卷冲减失败:"+ex.getMessage());
			ex.printStackTrace();
			throw new Exception(rm.getMsgInfo());
		}
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 结算单新增（单用）
	 * @param sum
	 * @return
	 */
	public ResultModel doQueryBillWebNew(CommonPage<SlmLadingBillHeat> cp){
		ResultModel rm=new ResultModel();
		SlmLadingBillHeat param_heat=cp.getObject();		
		String flag=cp.getMemo2();		//1查看用 2新增用 3编辑用
		try{			
			String sWhere=" and t.valid_status='13' and t.valid_flag='1'";
			if(param_heat.getContract_no()!=null&&!"".equals(param_heat.getContract_no())){ //合同号
				sWhere+=" and t.contract_no like '%"+param_heat.getContract_no()+"%'";
			}
			if (param_heat.getCustomer_no()!=null && !"".equals(param_heat.getCustomer_no())) {//客户
				sWhere += " and t.customer_no = '"+param_heat.getCustomer_no()+"'";
			}
			if("2".equals(flag)){
				if (StringUtils.isNotEmpty(cp.getMemo3())) {//交货状态
					sWhere += " and soi.delivery_state_desc = '"+cp.getMemo3()+"' ";
				}
				if (StringUtils.isNotEmpty(param_heat.getSteel_name())) {
					sWhere += " and soi.steel_name like '%"+param_heat.getSteel_name()+"%'";
				}
				List<SlmLadingBillHeat> heatList = this.getMapper(SlmLadingBillHeatMapper.class).doQueryBillWebNew(sWhere);	
				if (heatList!=null && heatList.size()>0) {					 
					for(SlmLadingBillHeat heats:heatList){
						Double total=0d;
						//三种费用
						List<SlmFundSettleGood> goodList=this.getMapper(SlmFundSettleGoodMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
						for(SlmFundSettleGood goods:goodList){
							total=DoubleUtil.add(total, goods.getBalance_amount());
						}
						List<SlmFundSettleCarriage> carriageList=this.getMapper(SlmFundSettleCarriageMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
						for(SlmFundSettleCarriage carriages:carriageList){
							total=DoubleUtil.add(total, carriages.getSettle_carriage_fund());
						}
						List<SlmFundSettleOther> otherList=this.getMapper(SlmFundSettleOtherMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
						for(SlmFundSettleOther others:otherList){
							total=DoubleUtil.add(total, others.getSettle_other_fund());
						}
						
						// 加上每个提单的提单明细的转库费和资金占用费：20230218刘侣
						
						List<SlmLadingBillDetail> details = this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
						double coilExtraMoney = 0d; // 提单所有卷应该缴纳的额外的钱  += (转库费单价 + 资金占用费单价) * 单卷的实重 * 税率；
						for(SlmLadingBillDetail sd:details){
							coilExtraMoney += (sd.getExtra_money());
						}
						total=DoubleUtil.add(total, coilExtraMoney);
						// end
						
						heats.setCarriageList(carriageList);
						heats.setGoodList(goodList);
						heats.setOtherList(otherList);
						heats.setTotal_fund(total);
					}
				}
				rm.setData(heatList);
				rm.setState("200");
			}			
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 未结算提单明细报表
	 * @param sum
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryUnSettleFundDetail(CommonPage<SlmLadingBillDetail> cp){
		ResultModel rm=new ResultModel();
		SlmLadingBillDetail slbd=cp.getObject();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<HashMap> pm = new PageModel<HashMap>(pageIndex,pageSize);
		try{			
			String sWhere=" and slbh.valid_status <> '9' and slbh.valid_flag='1'";
			if(slbd.getOrder_no()!=null && !"".equals(slbd.getOrder_no())){ //订单号
				sWhere+=" and slbd.order_no like '%"+slbd.getOrder_no()+"%'";
			}
			if (slbd.getCustomer_no()!=null && !"".equals(slbd.getCustomer_no())) {//客户
				sWhere += " and slbd.customer_no = '"+slbd.getCustomer_no()+"'";
			}
			if (slbd.getCoilno()!=null && !"".equals(slbd.getCoilno())) {//卷号
				sWhere += " and slbd.coilno = '"+slbd.getCoilno()+"'";
			}
			if (slbd.getMaterailcoilno()!=null && !"".equals(slbd.getMaterailcoilno())) {//原料卷号
				sWhere += " and slbd.materailcoilno = '"+slbd.getMaterailcoilno()+"'";
			}
			if (slbd.getBill_no()!=null && !"".equals(slbd.getBill_no())) {//提货单号
				sWhere += " and slbd.bill_no = '"+slbd.getBill_no()+"'";
			}
			if (cp.getMemo1()!=null && !"".equals(cp.getMemo1())) {//提单状态
				sWhere += " and slbh.valid_status = '"+cp.getMemo1()+"'";
			}
			if (cp.getStartTime()!=null && !"".equals(cp.getStartTime())) {//开始时间
				sWhere += " and slbh.create_time >= to_date('"+cp.getStartTime()+" 00:00:00','yyyy-MM-dd HH24:mi:ss')";
			}
			if (cp.getEndTime()!=null && !"".equals(cp.getEndTime())) {//结束时间
				sWhere += " and slbh.create_time <= to_date('"+cp.getEndTime()+" 23:59:59','yyyy-MM-dd HH24:mi:ss')";
			}
			List<HashMap> hmList = this.getMapper(SlmLadingBillHeatMapper.class).doQueryUnSettleFundDetail(slbd,sWhere,(pageIndex-1)*pageSize, pageIndex*pageSize);	
			int count = this.getMapper(SlmLadingBillHeatMapper.class).doQueryUnSettleFundDetailCount(slbd,sWhere);
			pm.setRows(hmList);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	//测试专用
	public ResultModel doAddSSSS(CommonPage<SlmLadingBillHeat> cp){
		ResultModel rm=new ResultModel();
		String order_no =cp.getMemo1();
		String flag = cp.getMemo2();
		String bill_no = cp.getMemo3();
		try{
			System.out.println(order_no.substring(0, order_no.length()-6));
			List<SlmContractHeatInfo> schiList = this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, "contract_no = '"+order_no.substring(0, order_no.length()-6)+"' and valid_flag = '1'", "create_time desc", 0, 0);
			if (CollectionUtils.isEmpty(schiList)) {
				return rm;
			}
			
			String condition = "1=1";
			if (StringUtils.isNotEmpty(order_no)) {
				condition += " and order_no = '"+order_no+"'";
			}
			if (StringUtils.isNotEmpty(bill_no)) {
				condition += " and bill_no = '"+bill_no+"'";
			}
			List<SlmLadingBillLine> slblList = this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(null, condition, "line_no", 0, 0);			 			
			if (CollectionUtils.isNotEmpty(slblList)) {
				for (SlmLadingBillLine slbl : slblList) {
					this.getBean(SlmContractPaymentServiceImpl.class).doAddOccupy(schiList.get(0), null, slbl, "102703",flag);
				}
			}
			if ("1".equals(flag)) {				
				rm.setMsgInfo("占用资金成功");
			}else if ("2".equals(flag)) {
				rm.setMsgInfo("释放资金成功");
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
}
