/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-01-13
 * 描述            ：客户结算单主信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Slm.FundManagement.impl;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import market.Com.pb.DoubleUtil;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Mes.OrderManager.Plan.impl.PlnProdorderStatisticServiceImpl;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillDetailMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillHeatMapper;
import market.Slm.DeliveryManagement.mapper.SlmLadingBillLineMapper;
import market.Slm.DeliveryManagement.vo.SlmLadingBillDetail;
import market.Slm.DeliveryManagement.vo.SlmLadingBillHeat;
import market.Slm.DeliveryManagement.vo.SlmLadingBillLine;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundInvoiceApplyMapper;
import market.Slm.FundManagement.mapper.SlmFundSecondAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleBillInvoiceMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleBillLineMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleBillMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleCarriageMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleGoodMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleOtherMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleWriteDownMapper;
import market.Slm.FundManagement.mapper.SlmFundThirdAccountMapper;
import market.Slm.FundManagement.service.SlmFundSettleBillService;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.FundManagement.vo.SlmFundInvoiceApply;
import market.Slm.FundManagement.vo.SlmFundSecondAccount;
import market.Slm.FundManagement.vo.SlmFundSecondDetail;
import market.Slm.FundManagement.vo.SlmFundSettleBill;
import market.Slm.FundManagement.vo.SlmFundSettleBillInvoice;
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.FundManagement.vo.SlmFundSettleWriteDown;
import market.Slm.FundManagement.vo.SlmFundThirdAccount;
import market.Slm.NcService.MessystemToNC65ServiceLocator;
import market.Slm.NcService.OuterSystemRetVO;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.vo.SlmOrderInfo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

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

@RemoteService(path="SlmFundSettleBillService")
public class SlmFundSettleBillServiceImpl extends BaseServiceImpl<SlmFundSettleBill,Object> implements SlmFundSettleBillService {

	/**
	 *  结算单 - 新增-编辑
	 *  总金额需前端计算
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddWeb(CommonPage<SlmFundSettleBill> 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);
		SlmFundSettleBill settle=sum.getObject();
		try{
			if(settle.getHeatList()==null||settle.getHeatList().size()<1){
				rm.setState("500");
				rm.setMsgInfo("请至少选择一条提单进行结算");
				return rm;
			}
			boolean in=true;
			String contract_no=null;
			String nature=null;
			int y_sum=0;
			int j_sum=0;
			int l_sum=0;
			int n_sum=0;
			//合同号 提单属性要求一致 牌号一致
			String steel="";
			SlmOrderInfo order=new SlmOrderInfo();
			List<SlmLadingBillLine> line_list=new ArrayList<SlmLadingBillLine>();
			List<SlmOrderInfo> order_list=new ArrayList<SlmOrderInfo>();
			//需加工提单允许同一个客户的新增再一起，即不判断合同号，
			for(SlmLadingBillHeat heats:settle.getHeatList()){
				line_list=this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"' and valid_flag='1'", null, 0, 0);
				if(line_list.size()>0){
					order.setContract_no(line_list.get(0).getContract_no());
					order.setContract_line_seq(line_list.get(0).getContract_line_seq());
					order.setOrder_seq(line_list.get(0).getOrder_seq());
					order_list=this.getMapper(SlmOrderInfoMapper.class).find(order, 0, 0);
					if(order_list.size()>0 && in)
						steel=order_list.get(0).getSteel_code();
				}
				if(in){
					contract_no=heats.getContract_no();
					in=false;
				}else if(!heats.getBill_no().contains("J")){
					//if(contract_no!=null && !contract_no.equals(heats.getContract_no())){
						//rm.setState("500");
						//rm.setMsgInfo("请选择同一个合同下的提单进行结算");
						//return rm;
					//}
					if(order_list.size()>0 && !steel.equals(order_list.get(0).getSteel_code())){
						rm.setState("500");
						rm.setMsgInfo("请选择相同牌号的提单进行结算");
						return rm;
					}
				}
				if(heats.getBill_no().contains("Y")){
					y_sum++;
				}else if(heats.getBill_no().contains("J")){
					j_sum++;
				}else if(heats.getBill_no().contains("L")){
					l_sum++;
				}else if(heats.getBill_no().contains("N")){
					n_sum++;
				}
			}
			int size_sum=settle.getHeatList().size();
			if(y_sum==size_sum){				//全为原卷
				nature="Y";
			}else if(j_sum==size_sum){			//全为加工 
				nature="J";
			}else if(l_sum==size_sum){			//全为加工 
				nature="L";
			}else if(n_sum>0){
				nature="N";
			}else{
				rm.setState("500");
				rm.setMsgInfo("请确保结算单下都为原卷提单、轧机提单或加工提单");
				return rm;
			}

			List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+contract_no+"'", null, 0, 0);
			if(heat_list.size()>0){		//税率
				settle.setTax_rate(heat_list.get(0).getTax_rate());
			}
			settle.setContract_no(contract_no);
			String settle_bill_no="";
			if(settle.getSettle_bill_no() != null && !"".equals(settle.getSettle_bill_no())){ 	//修改
				SlmFundSettleBill check=this.getMapper(SlmFundSettleBillMapper.class).findById(settle.getSettle_bill_no());
				if(!"1".equals(check.getFlag())){
					rm.setState("500");
					rm.setMsgInfo("该结算单状态不为编辑，无法修改");
					return rm;
				}
				settle.setUpdate_man_no(userId);
				settle.setUpdate_man_name(userName);
				settle.setUpdate_time(new Date());
				settle_bill_no=settle.getSettle_bill_no();
				this.getMapper(SlmFundSettleBillMapper.class).update(settle);
				//将之前已编制的提单由结算编制 改为 票据对齐
				SlmFundSettleBillLine line=new SlmFundSettleBillLine();
				line.setSettle_bill_no(settle.getSettle_bill_no());
				List<SlmFundSettleBillLine> lineList=this.getMapper(SlmFundSettleBillLineMapper.class).find(line,0,0);
				for(SlmFundSettleBillLine lines:lineList){
					SlmLadingBillHeat bill_heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(lines.getBill_no());
					if(bill_heat!=null&&"14".equals(bill_heat.getValid_status())){
						bill_heat.setValid_status("13");
						this.getMapper(SlmLadingBillHeatMapper.class).update(bill_heat);
					}
					//并删除子表信息
					this.getMapper(SlmFundSettleBillLineMapper.class).delete(lines.getSettle_bill_line_no());
				}
			}else{		//新增
				//结算单主表
				String id="-"+new SimpleDateFormat("yyyyMM").format(new Date())+"-";
				String maxId=this.getMapper(SlmFundSettleBillMapper.class).findMaxId(id);
				if(maxId!=null&&maxId.length()>4){
					String seq=maxId.substring(maxId.length()-4);
					int iseq=Integer.parseInt(seq)+1;
					id+=String.format("%04d", iseq);
				}else{
					id+="0001";
				}
				settle_bill_no=nature+id;
				settle.setSettle_bill_no(settle_bill_no);
				settle.setFlag("1"); 		//编辑
				settle.setValid_flag("1"); 		//有效
				settle.setCreate_man_no(userId);
				settle.setCreate_man_name(userName);
				settle.setCreate_time(new Date());
				settle.setTax_rate(13d);
				this.getMapper(SlmFundSettleBillMapper.class).insert(settle);
			}
			//结算子表新增-以及提单状态修改  三表
			if(settle.getHeatList()!=null){
				int seq=1;
				for(SlmLadingBillHeat heats:settle.getHeatList()){
					
					// 做提单的验证，验证这个提单是否已经编进一个结算单：防止提单重复进多个结算单的事情发生；20221205刘侣 start
					List<SlmFundSettleBill> settleBills = this.getMapper(SlmFundSettleBillMapper.class).findCountByBillNo(heats.getBill_no());
					if (settleBills != null && settleBills.size() > 0) {
						throw new Exception("提单：" + heats.getBill_no() + " 已经编入了结算单中，请联系管理员");
					}
					// end
					
					// 查询并判断提单的客户名称和传进来的客户名称是否一致：20230406 刘侣
					SlmLadingBillHeat ssb = this.getMapper(SlmLadingBillHeatMapper.class).findById(heats.getBill_no());
					if (!ssb.getCustomer_name().equals(settle.getCustomer_name())) {
						throw new Exception("提单：" + heats.getBill_no() + " 客户名称不一致，请联系管理员；");
					}
					// end
					
					//结算子单新增
					SlmFundSettleBillLine lines=new SlmFundSettleBillLine();
					lines.setSettle_bill_no(settle_bill_no);
					lines.setSettle_bill_line_no(settle_bill_no+"-"+String.format("%03d", seq));
					lines.setBill_no(heats.getBill_no());
					this.getBean(SlmFundSettleBillLineServiceImpl.class).doAddWeb(lines);
					seq++;
					//提单状态修改	
					heats.setValid_status("14");	//结算单编制
					this.getMapper(SlmLadingBillHeatMapper.class).update(heats);
					//订单状态修改
					List<SlmLadingBillLine> lineList=this.getMapper(SlmLadingBillLineMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"' and valid_flag='1'", null, 0, 0);
					for(SlmLadingBillLine bill_lines:lineList){
						order.setContract_no(bill_lines.getContract_no());
						order.setContract_line_seq(bill_lines.getContract_line_seq());
						order.setOrder_seq(bill_lines.getOrder_seq());
						order.setValid_flag("1");
						List<SlmOrderInfo> orderList=this.getMapper(SlmOrderInfoMapper.class).find(order, 0, 0);
						for(SlmOrderInfo orders:orderList){
							if("103410".equals(orders.getOrder_flag_no())){
								orders.setP_order_flag_no(order.getOrder_flag_no());
								orders.setP_order_flag_name(order.getOrder_flag_name());
								orders.setOrder_flag_no("103411");
								orders.setOrder_flag_name("结算");
								this.getMapper(SlmOrderInfoMapper.class).update(orders);
							}
						}
					}
					//三种费用的结算部门修改
					String object_no=settle.getBalance_object_no();
					String object_name=settle.getBalance_object_name();
					List<SlmFundSettleGood> goodList=this.getMapper(SlmFundSettleGoodMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
					for(SlmFundSettleGood goods:goodList){
						goods.setFlag("4");
						goods.setBalance_object_no(object_no);
						goods.setBalance_object_name(object_name);
						this.getMapper(SlmFundSettleGoodMapper.class).update(goods);
					}
					List<SlmFundSettleCarriage> carriageList=this.getMapper(SlmFundSettleCarriageMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
					for(SlmFundSettleCarriage carriages:carriageList){
						carriages.setFlag("3");
						carriages.setBalance_object_no(object_no);
						carriages.setBalance_object_name(object_name);
						this.getMapper(SlmFundSettleCarriageMapper.class).update(carriages);
					}
					List<SlmFundSettleOther> otherList=this.getMapper(SlmFundSettleOtherMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
					for(SlmFundSettleOther others:otherList){
						others.setFlag("3");
						others.setBalance_object_no(object_no);
						others.setBalance_object_name(object_name);
						this.getMapper(SlmFundSettleOtherMapper.class).update(others);
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	
	/**
	 *  查询所有已生成的结算单
	 * */
	public ResultModel doQueryAllSettle(CommonPage<SlmFundSettleBill> sum){
		ResultModel rm=new ResultModel();
//		SlmFundSettleBill bill=sum.getObject();
//		int pageIndex=sum.getPageIndex();
//		int pageSize=sum.getPageSize();
//		PageModel<SlmFundSettleBill> pm=new PageModel<SlmFundSettleBill>(pageIndex, pageSize);
		String startTime=sum.getStartTime() + " 00:00:00";
		String endTime=sum.getEndTime() + " 23:59:59";
//		String startTime2=sum.getStartTime2();
//		String endTime2=sum.getEndTime2();
//		String flag=sum.getMemo1();
		try{
			@SuppressWarnings("rawtypes")
			List<HashMap> allSettles = this.getMapper(SlmFundSettleBillMapper.class).doQueryAllSettle(startTime, endTime);
			rm.setData(allSettles);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	

	/**
	 *  结算单 - 查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmFundSettleBill> sum){
		ResultModel rm=new ResultModel();
		SlmFundSettleBill bill=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmFundSettleBill> pm=new PageModel<SlmFundSettleBill>(pageIndex, pageSize);
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		String startTime2=sum.getStartTime2();
		String endTime2=sum.getEndTime2();
		String flag=sum.getMemo1();
		try{
			String sWhere=" 1=1 ";
			if(startTime!=null&&!"".equals(startTime)){
				if("1".equals(flag)){
					sWhere+=" and to_char(update_time, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
				}else{
					sWhere+=" and to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
				}
			}
			if(endTime!=null&&!"".equals(endTime)){
				if("1".equals(flag)){
					sWhere+=" and to_char(update_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
				}else{
					sWhere+=" and to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
				}
			}
			if(startTime2!=null&&!"".equals(startTime2)){
				sWhere+=" and to_char(check_time, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime2+"'";
			}
			if(endTime2!=null&&!"".equals(endTime2)){
				sWhere+=" and to_char(check_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime2+"'";
			}
			if("1".equals(flag)){
				sWhere+=" and flag in('6','5')";
			}
			List<SlmFundSettleBill> list=this.getMapper(SlmFundSettleBillMapper.class).doQueryWith(bill, startTime,endTime, startTime2,endTime2,flag,(pageIndex-1)*pageSize, pageSize);
			long count=this.getMapper(SlmFundSettleBillMapper.class).countWithCondition(bill, sWhere);
			if("2".equals(flag)){			//冲减页面查询 
				for(SlmFundSettleBill bills:list){
					SlmFundSettleWriteDown down=new SlmFundSettleWriteDown();
					down.setSettle_bill_no(bills.getSettle_bill_no());
					down.setValid_flag("1");
					int d_count=this.getMapper(SlmFundSettleWriteDownMapper.class).count(down);
					if(d_count>0)
						bills.setHave_writeDown("1");		//有冲减信息
					else
						bills.setHave_writeDown("0");

				}
			}else if("3".equals(flag)){ 			//开票申请界面
				for(SlmFundSettleBill bills:list){
					//明细查询
					SlmFundSettleBill param=new SlmFundSettleBill();
					param.setSettle_bill_no(bills.getSettle_bill_no());
					CommonPage<SlmFundSettleBill> param_sum=new CommonPage<SlmFundSettleBill>();
					param_sum.setObject(param);
					ResultModel invoice_rm= doQueryInvoiceWeb(param_sum);
					List<SlmFundSettleBillInvoice> invoice_list=(List<SlmFundSettleBillInvoice>) invoice_rm.getData();
					bills.setDetailList(invoice_list);
				}
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
	/**
	 *  结算单 - 核算
	 *  查看账户金额是否满足结算
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCheckOutWeb(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundSettleBill> billList=sum.getObjectList();
		try{
			if(billList==null||billList.size()<1){
				rm.setState("500");
				rm.setMsgInfo("请选择结算单进行结算");
				return rm;
			}
			for(SlmFundSettleBill bill:billList){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill==null){
					rm.setState("500");
					rm.setMsgInfo("结算单数据丢失，请联系管理员");
					return rm;
				}
				List<SlmFundFirstAccount> f_account_list=this.getMapper(SlmFundFirstAccountMapper.class).findWithCondition(null, " customer_no='"+bill.getCustomer_no()+"'", null, 0, 0);
				List<SlmFundSecondAccount> s_account_list=this.getMapper(SlmFundSecondAccountMapper.class).findWithCondition(null, " first_account_no='"+f_account_list.get(0).getFirst_account_no()+"'", null, 0, 0);
				//对应的合同号		加工结算单允许多个合同号不一样的提单新增到一起，所以结算需要分开结算
				List<SlmLadingBillHeat> bill_list=this.getMapper(SlmLadingBillHeatMapper.class).findContractNo(bill.getSettle_bill_no());
				//==================eason 2019-07-06 add ===============================
				List<SlmFundSettleWriteDown> downList=this.getMapper(SlmFundSettleWriteDownMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"' and valid_flag='1' and flag in ('3','4','5')", null,0,0);		
				double down_money=0;
				if(downList.size()>0){
					for(SlmFundSettleWriteDown downs:downList){
						if("1".equals(downs.getSettle_write_down_type())){ 		//冲减
							down_money=DoubleUtil.sub(down_money, downs.getSettle_write_down_fund());
						}else{
							down_money=DoubleUtil.add(down_money, downs.getSettle_write_down_fund());
						}
					}
				}
				int icount=0;
				//======================================================================
				for(SlmLadingBillHeat heats:bill_list){
					String contract_no=heats.getContract_no(); 			//合同账户
					//=================eason 2019-07-05 add=======================
					String sBillNo="";
					List<SlmLadingBillHeat> lslbh=this.getMapper(SlmLadingBillHeatMapper.class).getBillNo(bill.getSettle_bill_no());
					for(SlmLadingBillHeat slbh:lslbh){
						if(contract_no.equals(slbh.getContract_no())){
							sBillNo+="'"+slbh.getBill_no()+"',";
						}
					}
					if(!"".equals(sBillNo)){
						sBillNo=sBillNo.substring(0,sBillNo.length()-1);
					}
					// 该结算单下的合同账户对应的所有提单金额数据
					double money = this.getMapper(SlmLadingBillHeatMapper.class).getMoney(sBillNo,contract_no);
					if(icount==0){
						money=DoubleUtil.add(money, down_money);
					}
					icount++;
					//============================================================
					
					SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contract_no);
					//如果没有合同账户则自动新增
					if(t_account==null){	
						if(f_account_list.size()>0){		//有客户账户，再查找产线账户
							if(s_account_list.size()==1){			//只有一条产线账户
								t_account=new SlmFundThirdAccount();			//生成合同账户
								t_account.setFirst_account_no(f_account_list.get(0).getFirst_account_no());
								t_account.setFirst_account_name(f_account_list.get(0).getFirst_account_name());
								t_account.setSecond_account_no(s_account_list.get(0).getSecond_account_no());
								t_account.setSecond_account_name(s_account_list.get(0).getSecond_account_name());
								t_account.setBalance_object_no(f_account_list.get(0).getBalance_object_no());
								t_account.setBalance_object_name(f_account_list.get(0).getBalance_object_name());
								t_account.setCustomer_no(f_account_list.get(0).getCustomer_no());
								t_account.setCustomer_name(f_account_list.get(0).getCustomer_name());
								t_account.setThird_account_no(contract_no);
								t_account.setThird_account_name(contract_no);
								t_account.setInit_fund(0d);
								this.getBean(SlmFundThirdAccountServiceImpl.class).doAddWeb(t_account);
							}else{
								rm.setState("500");
								rm.setMsgInfo("请手动添加合同账户");
								return rm;
							}
						}else{
							rm.setState("500");
							rm.setMsgInfo("请先添加客户账户和产线账户以便结算");
							return rm;
						}
					}
					if("1".equals(t_account.getLock_flag())){
						throw new Exception("对应的合同账户已经结转，如须结算请解锁");
					}
					//释放占用金额
					rm=this.getBean(SlmFundThirdAccountUsedServiceImpl.class).doReleaseFund(contract_no,null,null,bill);
					if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
					//该金额需要计算冲减金额否？yao计算
					t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contract_no);
					SlmFundSecondAccount s_account=this.getMapper(SlmFundSecondAccountMapper.class).findById(t_account.getSecond_account_no());
					SlmFundFirstAccount f_account=this.getMapper(SlmFundFirstAccountMapper.class).findById(t_account.getFirst_account_no());
					if(s_account!=null&&f_account!=null){
						double t_money=t_account.getUse_fund();
						double s_money=s_account.getUse_fund();
						//==================eason add 2019-06-30 一级可拨+二级可用+三级可用=================
						double total_haves=DoubleUtil.add(DoubleUtil.add(f_account.getFinal_fund(),t_money),s_money);
						//double total_have=f_account.getUse_fund();		//总共拥有的可用金额
						//if(money>total_have){
						if(money>total_haves){	
						//================================================================================
							rm.setState("500");
							if(icount==1){
								rm.setMsgInfo("结算单["+bill.getSettle_bill_no()+"]的合同["+contract_no+"]中的提单["+sBillNo+"]结算金额-冲减金额+补收金额["+money+"]超过客户["+f_account.getCustomer_name()+"]的账户可拨金额+产线可用金额+合同可用金额金额["+total_haves+"]");
							}else{
								rm.setMsgInfo("结算单["+bill.getSettle_bill_no()+"]的合同["+contract_no+"]中的提单["+sBillNo+"]结算金额["+money+"]超过客户["+f_account.getCustomer_name()+"]的账户可拨金额+产线可用金额+合同可用金额金额["+total_haves+"]");
							}
							//rm.setMsgInfo(bill.getSettle_bill_no()+"结算金额["+money+"]超过客户账户"+f_account.getCustomer_name()+"的可用金额["+total_have+"]");
							return rm;
						}else{
							//合同账户的金额不够，但是加上产线账户的金额就足够，则自动调拨
							if(money>t_money&&money<=(t_money+s_money)){		
								SlmFundSecondDetail inOut=new SlmFundSecondDetail();
								inOut.setSecond_account_no(s_account.getSecond_account_no());
								inOut.setSecond_account_name(s_account.getSecond_account_name());
								inOut.setOther_account_no(t_account.getThird_account_no());
								inOut.setOther_account_name(t_account.getThird_account_name());
								inOut.setBalance_object_no(t_account.getBalance_object_no());
								inOut.setBalance_object_name(t_account.getBalance_object_name());
								inOut.setCustomer_no(t_account.getCustomer_no());
								inOut.setCustomer_name(t_account.getCustomer_name());
								inOut.setIn_out_fund(DoubleUtil.sub(money,t_money));
								inOut.setTrans_class("3");		//二级到三级
								this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(inOut);
							}else if(money>(t_money+s_money)){		//金额已超过二三级账户的总金额了，从客户账户里拨款
								double cha=DoubleUtil.sub(money,DoubleUtil.add(t_money,s_money));
								//从一级到二级
								SlmFundSecondDetail inOut=new SlmFundSecondDetail();
								inOut.setSecond_account_no(s_account.getSecond_account_no());
								inOut.setSecond_account_name(s_account.getSecond_account_name());
								inOut.setOther_account_no(f_account.getFirst_account_no());
								inOut.setOther_account_name(f_account.getFirst_account_name());
								inOut.setBalance_object_no(f_account.getBalance_object_no());
								inOut.setBalance_object_name(f_account.getBalance_object_name());
								inOut.setCustomer_no(f_account.getCustomer_no());
								inOut.setCustomer_name(f_account.getCustomer_name());
								inOut.setIn_out_fund(cha);
								inOut.setTrans_class("1");		//一级到二级
								this.getBean(SlmFundSecondDetailServiceImpl.class).doAddInWeb(inOut);
								//二级到三级
								inOut.setOther_account_no(t_account.getThird_account_no());
								inOut.setOther_account_name(t_account.getThird_account_name());
								inOut.setIn_out_fund(DoubleUtil.add(cha,s_money));
								inOut.setTrans_class("3");		//二级到三级
								this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(inOut);
							}
						}
					}else{
						rm.setState("500");
						rm.setMsgInfo("产线账户数据丢失，请联系管理员");
						return rm;
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 *  结算单 - 结算
	 *  去合同账户进行扣款
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSettleWeb(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
//		this.getSession().setAttribute(HomeService.SESSION_USER_ID, "admin");
//		this.getSession().setAttribute(HomeService.SESSION_USER_NAME, "管理员");
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			rm=doCheckOutWeb(sum);
			if("500".equals(rm.getState())){
				throw new Exception(rm.getMsgInfo());
			}
			for(SlmFundSettleBill bill:sum.getObjectList()){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill!=null&&"5".equals(bill.getFlag())){
					
					//============eason add 2019-07-19 增加生产接口调用=================
					String sBill="";
					//=================================================================
					
					bill.setFlag("6"); 		//使用
					bill.setCheck_man_no(userId);
					bill.setCheck_man_name(userName);
					bill.setCheck_time(new Date());
					this.getMapper(SlmFundSettleBillMapper.class).update(bill);

					//将提货单状态改为结算
					List<SlmFundSettleBillLine> line_list=this.getMapper(SlmFundSettleBillLineMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"'", null, 0, 0);
					List<String> lcontractNo=new ArrayList<String>();
					for(SlmFundSettleBillLine lines:line_list){
						SlmLadingBillHeat heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(lines.getBill_no());
						if(heat!=null){
							//============eason add 2019-07-19 增加生产接口调用=================
							sBill+="'"+lines.getBill_no()+"',";
							//=================================================================
							
							//=================eason add 2019-07-08===================
							boolean flag=false;
							for(String str:lcontractNo){
								if(str.equals(heat.getContract_no())){
									flag=true;
									break;
								}
							}
							if(!flag){
								lcontractNo.add(heat.getContract_no());
							}
							//========================================================
							if("1".equals(heat.getBill_type())){
								heat.setValid_status("9"); 		//实际结算
							}
							if("2".equals(heat.getBill_type())){
								heat.setValid_status("8"); 		//虚拟结算
							}
							this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
						}
					}
					
					//double money=bill.getBalance_amount();			//结算金额
					double down_money=0;
					//计算冲减信息
					List<SlmFundSettleWriteDown> downList=this.getMapper(SlmFundSettleWriteDownMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"' and valid_flag='1' and flag in ('3','4','5')", null,0,0);		
					if(downList.size()>0){
						for(SlmFundSettleWriteDown downs:downList){
							if("1".equals(downs.getSettle_write_down_type())){ 		//冲减
								down_money=DoubleUtil.sub(down_money, downs.getSettle_write_down_fund());
							}else{
								down_money=DoubleUtil.add(down_money, downs.getSettle_write_down_fund());
							}
						}
					}
					//===========================eason add 2019-07-08=================
					int icount=0;
					for(String contractNo:lcontractNo){
						//=================eason 2019-07-05 add=======================
						String sBillNo="";
						List<String> billsInContract = new ArrayList<>();
						List<SlmLadingBillHeat> lslbh=this.getMapper(SlmLadingBillHeatMapper.class).getBillNo(bill.getSettle_bill_no());
						for(SlmLadingBillHeat slbh:lslbh){
							if(contractNo.equals(slbh.getContract_no())){
								sBillNo+="'"+slbh.getBill_no()+"',";
								billsInContract.add(slbh.getBill_no());
							}
						}
						if(!"".equals(sBillNo)){
							sBillNo=sBillNo.substring(0,sBillNo.length()-1);
						}
						// 该结算单下的合同账户对应的所有提单金额数据
						double money = this.getMapper(SlmLadingBillHeatMapper.class).getMoney(sBillNo,contractNo);
						
						// 计算 当前结算单下的所有提单中符合当前合同的提单的 额外金额：转库费和资金占用费；20230218刘侣
						double contractExtraMoney = 0d;
						for(String billNo : billsInContract) {
							// 符合合同号条件的每个提单：计算该提单下的所有提单明细的额外加价总和；
							List<SlmLadingBillDetail> details = this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, " bill_no='"+billNo+"'", null, 0, 0);
							for(SlmLadingBillDetail slbd : details) {
								contractExtraMoney = DoubleUtil.add(contractExtraMoney, slbd.getExtra_money());
							}
						}
						money=DoubleUtil.add(money, contractExtraMoney);
						//end
						
						if(icount==0){
							money=DoubleUtil.add(money, down_money);
						}
						//============================================================
						//====eason edit 2019-07-08这个里面的代码是原有代码，我丢到这个循环里面了======
						SlmFundThirdAccount account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contractNo);
						if(account!=null&&account.getFirst_account_no()!=null){
							SlmFundFirstAccount f_account=this.getMapper(SlmFundFirstAccountMapper.class).findById(account.getFirst_account_no());
							if(f_account!=null){
								//扣款操作
								account.setUse_fund(DoubleUtil.sub(account.getUse_fund(),money));				//三级 可用金额-money
								account.setSettlement_fund(DoubleUtil.add(account.getSettlement_fund(),money));     		//三级 结算金额+money
								f_account.setUse_fund(DoubleUtil.sub(f_account.getUse_fund(),money));				//一级 可用金额-money
								f_account.setSettlement_fund(DoubleUtil.add(f_account.getSettlement_fund(),money));     		//一级 结算金额+money
								f_account.setBalance_fund(DoubleUtil.sub(f_account.getBalance_fund(),money));     		//一级 账期财务余额-money

								if(icount==0){
									f_account.setWrite_down_fund(DoubleUtil.sub(f_account.getWrite_down_fund(), down_money));		//冲减总额 - 冲减金额
								}
								icount++;
								
								this.getMapper(SlmFundFirstAccountMapper.class).update(f_account);
								this.getMapper(SlmFundThirdAccountMapper.class).update(account);
								if(account.getUse_fund()<0){
									this.getBean(SlmFundSecondDetailServiceImpl.class).doAuto(f_account,account);
								}
							}
						}
						//===========================================================
					}
					
					//============eason add 2019-07-19 增加生产接口调用=================
					/*
					try{
						if(!"".equals(sBill)){
							sBill=sBill.substring(0,sBill.length()-1);
							List<SlmLadingBillDetail> lsbd=this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, " bill_no in("+sBill+") ", "", 0, 0);
							for(SlmLadingBillDetail detail: lsbd){
								this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(detail.getCoilno(), 4, true);
							}
						}
					}catch( Exception ex){ } //此处错误不管
					//*/
					//=================================================================
				}else{
					rm.setState("500");
					rm.setMsgInfo("结算单状态为票据勾稽才能进行结算");
					return rm;
				}
			}

			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			e.printStackTrace();
			throw e;
		}
		return rm;
	}

	/**
	 * 资金结算 - 撤销
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRepealWeb(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		try{
			List<SlmFundSettleBill> bill_list=sum.getObjectList();
			for(SlmFundSettleBill bill:bill_list){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill==null){
					rm.setState("500");
					rm.setMsgInfo("结算单数据丢失，请联系管理员");
					return rm;
				}
				if(!"6".equals(bill.getFlag())){
					rm.setState("500");
					rm.setMsgInfo("结算单状态不为使用，无法撤销");
					return rm;
				}
				
				//============eason add 2019-07-19 增加生产接口调用=================
				String sBill="";
				//=================================================================
				
				bill.setFlag("5"); 		//票据勾稽
				this.getMapper(SlmFundSettleBillMapper.class).update(bill);

				List<String> lcontractNo=new ArrayList<String>();
				//将提货单状态改为结算
				List<SlmFundSettleBillLine> line_list=this.getMapper(SlmFundSettleBillLineMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"'", null, 0, 0);
				for(SlmFundSettleBillLine lines:line_list){
					SlmLadingBillHeat heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(lines.getBill_no());
					if(heat!=null){
						//============eason add 2019-07-19 增加生产接口调用=================
						sBill+="'"+lines.getBill_no()+"',";
						//=================================================================
						
						//=================eason add 2019-07-08===================
						boolean flag=false;
						for(String str:lcontractNo){
							if(str.equals(heat.getContract_no())){
								flag=true;
								break;
							}
						}
						if(!flag){
							lcontractNo.add(heat.getContract_no());
						}
						//========================================================
						if("8".equals(heat.getValid_status())||"9".equals(heat.getValid_status())){
							heat.setValid_status("14"); 		//结算单编制
							this.getMapper(SlmLadingBillHeatMapper.class).update(heat);
						}
					}
				}
				int icount = 0;
				double money=-bill.getBalance_amount(); 		//负的结算金额
				double down_money=0;
				//再添加冲减信息
				List<SlmFundSettleWriteDown> downList=this.getMapper(SlmFundSettleWriteDownMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"' and valid_flag='1' and flag in ('3','4','5')", null,0,0);		
				if(downList.size()>0){
					for(SlmFundSettleWriteDown downs:downList){
						if("2".equals(downs.getSettle_write_down_type())){ 		//补收
							down_money=DoubleUtil.sub(down_money, downs.getSettle_write_down_fund());
						}else{
							down_money=DoubleUtil.add(down_money, downs.getSettle_write_down_fund());
						}
					}
				}
				
				//=================eason add 2019-07-08===================
				for(String contractNo:lcontractNo){
					//====eason edit 2019-07-08这个里面的代码是原有代码，我丢到这个循环里面了======
					//三级账户 + 结算金额
					SlmFundThirdAccount account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contractNo);
					if(account!=null&&account.getFirst_account_no()!=null){
						SlmFundFirstAccount f_account=this.getMapper(SlmFundFirstAccountMapper.class).findById(account.getFirst_account_no());
						if(f_account!=null){
							//扣款操作
							account.setUse_fund(DoubleUtil.sub(account.getUse_fund(),money));				//三级 可用金额-money
							account.setSettlement_fund(DoubleUtil.add(account.getSettlement_fund(),money));     		//三级 结算金额+money
							f_account.setUse_fund(DoubleUtil.sub(f_account.getUse_fund(),money));				//一级 可用金额-money
							f_account.setSettlement_fund(DoubleUtil.add(f_account.getSettlement_fund(),money));     		//三级 结算金额+money
							f_account.setBalance_fund(DoubleUtil.sub(f_account.getBalance_fund(),money));     		//三级 账期财务余额-money
							this.getMapper(SlmFundThirdAccountMapper.class).update(account);
							//

							//再添加冲减信息
							if (icount==0&&down_money>0){
								f_account.setUse_fund(DoubleUtil.sub(f_account.getUse_fund(), down_money));		//可用金额 - 冲减金额
								f_account.setBalance_fund(DoubleUtil.sub(f_account.getBalance_fund(), down_money));		//财务余额- 冲减金额
								f_account.setWrite_down_fund(DoubleUtil.sub(f_account.getWrite_down_fund(), down_money));		//冲减总额 - 冲减金额
								f_account.setSettlement_fund(DoubleUtil.add(f_account.getSettlement_fund(), down_money)); 		//结算金额 + 冲减金额
								this.getMapper(SlmFundFirstAccountMapper.class).update(f_account);
							}
							icount++;
							this.getMapper(SlmFundFirstAccountMapper.class).update(f_account);
						}
					}
					//==========================================================================
				}
				//========================================================
				
				//============eason add 2019-07-19 增加生产接口调用=================
				try{
					if(!"".equals(sBill)){
						sBill=sBill.substring(0,sBill.length()-1);
						List<SlmLadingBillDetail> lsbd=this.getMapper(SlmLadingBillDetailMapper.class).findWithCondition(null, " bill_no in("+sBill+") ", "", 0, 0);
						for(SlmLadingBillDetail detail: lsbd){
							this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(detail.getCoilno(), 4, false);
						}
					}
				}catch( Exception ex){ } //此处错误不管
				//=================================================================
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 *  结算单 - 删除
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteWeb(CommonPage<SlmFundSettleBill> 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<SlmFundSettleBill> billList=sum.getObjectList();
		try{
			for(SlmFundSettleBill bill:billList){
				SlmFundSettleBill check=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(!"1".equals(check.getFlag())){
					rm.setState("500");
					rm.setMsgInfo("该结算单状态不为编辑，无法修改");
					return rm;
				}
				//将之前已编制的提单由结算编制 改为 票据对齐
				SlmFundSettleBillLine line=new SlmFundSettleBillLine();
				line.setSettle_bill_no(bill.getSettle_bill_no());
				List<SlmFundSettleBillLine> lineList=this.getMapper(SlmFundSettleBillLineMapper.class).find(line,0,0);
				for(SlmFundSettleBillLine lines:lineList){
					SlmLadingBillHeat bill_heat=this.getMapper(SlmLadingBillHeatMapper.class).findById(lines.getBill_no());
					if(bill_heat!=null){
						bill_heat.setValid_status("13");
						this.getMapper(SlmLadingBillHeatMapper.class).update(bill_heat);

						List<SlmFundSettleGood> goodList=this.getMapper(SlmFundSettleGoodMapper.class).findWithCondition(null, " bill_no='"+bill_heat.getBill_no()+"'", null, 0, 0);
						for(SlmFundSettleGood goods:goodList){
							goods.setFlag("3");
							this.getMapper(SlmFundSettleGoodMapper.class).update(goods);
						}
						List<SlmFundSettleCarriage> carriageList=this.getMapper(SlmFundSettleCarriageMapper.class).findWithCondition(null, " bill_no='"+bill_heat.getBill_no()+"'", null, 0, 0);
						for(SlmFundSettleCarriage carriages:carriageList){
							carriages.setFlag("2");
							this.getMapper(SlmFundSettleCarriageMapper.class).update(carriages);
						}
						List<SlmFundSettleOther> otherList=this.getMapper(SlmFundSettleOtherMapper.class).findWithCondition(null, " bill_no='"+bill_heat.getBill_no()+"'", null, 0, 0);
						for(SlmFundSettleOther others:otherList){
							others.setFlag("2");
							this.getMapper(SlmFundSettleOtherMapper.class).update(others);
						}
					}
				}
				bill.setDelete_man_no(userId);
				bill.setDelete_man_name(userName);
				bill.setDelete_time(new Date());
				bill.setValid_flag("0"); 		//无效
				this.getMapper(SlmFundSettleBillMapper.class).update(bill);
				//删除冲减单
				List<SlmFundSettleWriteDown> down_list=this.getMapper(SlmFundSettleWriteDownMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"'", null, 0, 0);
				for(SlmFundSettleWriteDown downs:down_list){
					this.getMapper(SlmFundSettleWriteDownMapper.class).delete(downs.getSeq());
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 * 提交
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSubmitWeb(CommonPage<SlmFundSettleBill> 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<SlmFundSettleBill> billList=sum.getObjectList();
		try{
			for(SlmFundSettleBill bill:billList){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill!=null&&"1".equals(bill.getFlag())){
					bill.setUpdate_man_no(userId);
					bill.setUpdate_man_name(userName);
					bill.setUpdate_time(new Date());
					bill.setFlag("2");		//待确认
					this.getMapper(SlmFundSettleBillMapper.class).update(bill);
				}else{
					rm.setState("500");
					rm.setMsgInfo("状态为编辑的数据才能提交");
					return rm;
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 * 撤回
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRollbackWeb(CommonPage<SlmFundSettleBill> 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<SlmFundSettleBill> billList=sum.getObjectList();
		try{
			for(SlmFundSettleBill bill:billList){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill!=null&&"2".equals(bill.getFlag())){
					bill.setUpdate_man_no(userId);
					bill.setUpdate_man_name(userName);
					bill.setUpdate_time(new Date());
					bill.setFlag("1");   		//编辑
					this.getMapper(SlmFundSettleBillMapper.class).update(bill);
				}else{
					rm.setState("500");
					rm.setMsgInfo("状态为待确认的数据才能撤回");
					return rm;
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 * 审核通过
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doPassWeb(CommonPage<SlmFundSettleBill> 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<SlmFundSettleBill> billList=sum.getObjectList();
		try{
			for(SlmFundSettleBill bill:billList){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill!=null&&("2".equals(bill.getFlag())||"1".equals(bill.getFlag()))){
					bill.setCheck_man_no(userId);
					bill.setCheck_man_name(userName);
					bill.setCheck_time(new Date());
					bill.setFlag("3");   		//确认
					this.getMapper(SlmFundSettleBillMapper.class).update(bill);
				}else{
					rm.setState("500");
					rm.setMsgInfo("状态为待确认的数据才能审核");
					return rm;
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 * 反审 确认改成待确认
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doNotPassWeb(CommonPage<SlmFundSettleBill> 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<SlmFundSettleBill> billList=sum.getObjectList();
		try{
			for(SlmFundSettleBill bill:billList){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill!=null&&"3".equals(bill.getFlag())){
					bill.setUpdate_man_no(userId);
					bill.setUpdate_man_name(userName);
					bill.setUpdate_time(new Date());
					bill.setFlag("1");   		//待确认
					this.getMapper(SlmFundSettleBillMapper.class).update(bill);
				}else{
					rm.setState("500");
					rm.setMsgInfo("状态为确认的数据才能反审");
					return rm;
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 * 查询出开票信息
	 * */
	public ResultModel doQueryInvoiceWeb(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmFundSettleBill bill=sum.getObject();
		List<SlmFundSettleBillInvoice> list=new ArrayList<SlmFundSettleBillInvoice>();
		try{
			bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
			if(bill!=null){
				List<SlmFundSettleBillLine> lineList=this.getMapper(SlmFundSettleBillLineMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"'", null, 0, 0);
				for(SlmFundSettleBillLine lines:lineList){
					List<SlmFundSettleBillInvoice> tlist=this.getMapper(SlmFundSettleBillInvoiceMapper.class).doQueryInvoice(lines.getBill_no());
					//排除重量为0的
					List<SlmFundSettleBillInvoice> temp_list=new ArrayList<SlmFundSettleBillInvoice>();
					for(SlmFundSettleBillInvoice invoices:tlist){
						if(invoices.getWeight()==0){
							
						}else{
							temp_list.add(invoices);
						}
					}
					tlist=temp_list;
					list.addAll(tlist);
				}
			}
			for(SlmFundSettleBillInvoice invoices:list){
				invoices.setSettle_bill_no(bill.getSettle_bill_no());
				if(invoices.getAmount()!=null)
					invoices.setAmount(DoubleUtil.round(invoices.getAmount(),2));
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	
	/**
	 * 查询出开票信息(由于打印)20230218刘侣
	 * */
	public ResultModel doQueryInvoiceWebPrint(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmFundSettleBill bill=sum.getObject();
		List<SlmFundSettleBillInvoice> list=new ArrayList<SlmFundSettleBillInvoice>();
		try{
			bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
			if(bill!=null){
				List<SlmFundSettleBillLine> lineList=this.getMapper(SlmFundSettleBillLineMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"'", null, 0, 0);
				for(SlmFundSettleBillLine lines:lineList){
					List<SlmFundSettleBillInvoice> tlist=this.getMapper(SlmFundSettleBillInvoiceMapper.class).doQueryInvoicePrint(lines.getBill_no());
					//排除重量为0的
					List<SlmFundSettleBillInvoice> temp_list=new ArrayList<SlmFundSettleBillInvoice>();
					for(SlmFundSettleBillInvoice invoices:tlist){
						if(invoices.getWeight()==0){
							
						}else{
							temp_list.add(invoices);
						}
					}
					tlist=temp_list;
					list.addAll(tlist);
				}
			}
			for(SlmFundSettleBillInvoice invoices:list){
				invoices.setSettle_bill_no(bill.getSettle_bill_no());
				if(invoices.getAmount()!=null)
					invoices.setAmount(DoubleUtil.round(invoices.getAmount(),2));
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	
	/**
	 * 查询出开票信息
	 * */
	public ResultModel doQuerySettleDetailWeb(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmFundSettleBill bill=sum.getObject();
		List<SlmFundSettleBillInvoice> list=new ArrayList<SlmFundSettleBillInvoice>();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		String have_plan=sum.getMemo1();		//0:查询全部 1查询原料卷 2查询需加工 
		try{
			if("1".equals(have_plan)){		//查原料卷
				have_plan=" and o.order_nature='1'";
			}else if("2".equals(have_plan)){
				have_plan=" and o.order_nature='2'";
			}else if("0".equals(have_plan)){
				have_plan=null;
			}
			list=this.getMapper(SlmFundSettleBillInvoiceMapper.class).doQuerySettle(bill,startTime,endTime,have_plan);//返回的数据
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	/**
	 * 打印查询出的开票信息
	 * */
	public ResultModel doExportExcel(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmFundSettleBill bill=sum.getObject();
		List<SlmFundSettleBillInvoice> list=new ArrayList<SlmFundSettleBillInvoice>();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		String have_plan=sum.getMemo1();
		try{
			if("1".equals(have_plan)){		//查原料卷
				have_plan=" and o.order_nature='1'";
			}else if("2".equals(have_plan)){
				have_plan=" and o.order_nature='2'";
			}else if("0".equals(have_plan)){
				have_plan=null;
			}
			if(!startTime.contains(":")){}
			list=this.getMapper(SlmFundSettleBillInvoiceMapper.class).doQuerySettle(bill,startTime,endTime,have_plan);
			for(SlmFundSettleBillInvoice invoice:list){
				if(invoice.getContract_price()==0){
					invoice.setTrade_price(0d);
				}
			}
			List<SlmFundSettleBillInvoice> list2=this.getMapper(SlmFundSettleBillInvoiceMapper.class).findScour(bill, startTime, endTime, have_plan);
			double total_write_down_fund=0;
			if(list2.size()>0){
				for (SlmFundSettleBillInvoice sfsb : list2) {
					if(sfsb.getSettle_write_down_type()!=null){
						if("1".equals(sfsb.getSettle_write_down_type())){ 		//统计冲减
							total_write_down_fund=DoubleUtil.sub(total_write_down_fund, sfsb.getSettle_write_down_fund());
						}else{
							total_write_down_fund=DoubleUtil.add(total_write_down_fund, sfsb.getSettle_write_down_fund());
						}
					}
				}
			}
			//			// 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();
			}
			generateExcel(rm, list, path,total_write_down_fund);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	/**
	 *
	 * 报表打印
	 * **/
	private void generateExcel(ResultModel rm, List<SlmFundSettleBillInvoice> list, String path,Double total_write_down_fund)
			throws IOException, WriteException, RowsExceededException {
		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 + "结算明细报表";
		WritableWorkbook workbook;
		String file=filename+".xls";  //文件名
		//3. 操作EXCEL文件
		workbook = Workbook.createWorkbook(new File(path+file));
		WritableSheet sheet = workbook.createSheet("结算明细报表", 1);
		//行高
		sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.CENTRE);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		//
		jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##"); //设置数字格式
		jxl.write.WritableCellFormat wcfN = new WritableCellFormat(nf); //设置表单格式
		wcfN.setAlignment(Alignment.CENTRE);
		wcfN.setVerticalAlignment(VerticalAlignment.CENTRE);
		//表头
		sheet.mergeCells(0, 0, 0, 1);
		sheet.addCell(new Label(0,0,"结算编号",cellFormat1));

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

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

		sheet.mergeCells(3, 0, 3, 1);
		sheet.addCell(new Label(3,0,"交货状态",cellFormat1));

		sheet.mergeCells(4, 0, 4, 1);
		sheet.addCell(new Label(4,0,"产品名称",cellFormat1));

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

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

		sheet.mergeCells(7, 0, 7, 1);
		sheet.addCell(new Label(7,0,"重量（吨）",cellFormat1));

		sheet.mergeCells(8, 0, 8, 1);
		sheet.addCell(new Label(8,0,"原料卷号",cellFormat1));

		sheet.mergeCells(9, 0, 9, 1);
		sheet.addCell(new Label(9,0,"钢卷号",cellFormat1));

		sheet.mergeCells(10, 0, 10, 1);
		sheet.addCell(new Label(10,0,"卸货地点",cellFormat1));

		sheet.mergeCells(11, 0, 11, 1);
		sheet.addCell(new Label(11,0,"合同单价",cellFormat1));

		sheet.mergeCells(12, 0, 12, 1);
		sheet.addCell(new Label(12,0,"运费",cellFormat1));

		sheet.mergeCells(13, 0, 13, 1);
		sheet.addCell(new Label(13,0,"加工配送费",cellFormat1));

		sheet.mergeCells(14, 0, 14, 1);
		sheet.addCell(new Label(14,0,"结算单价",cellFormat1));

		sheet.mergeCells(15, 0, 15, 1);
		sheet.addCell(new Label(15,0,"总金额（元）",cellFormat1));

		sheet.mergeCells(16, 0, 16, 1);
		sheet.addCell(new Label(16,0,"冲减金额",cellFormat1));

		sheet.mergeCells(17, 0, 17, 1);
		sheet.addCell(new Label(17,0,"冲减类型",cellFormat1));		

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

		double totalTheoryWeight = 0d, totalBalance_price=0d,totalAmount = 0d;
		for(int i = 0; i < list.size(); i++) {
			//结算编号
			if(list.get(i).getSettle_bill_no() != null && !"".equals(list.get(i).getSettle_bill_no())) {
				sheet.addCell(new Label(0,i+2,list.get(i).getSettle_bill_no(),cellFormat));
			}
			//客户名称
			if(list.get(i).getCustomer_name() != null && !"".equals(list.get(i).getCustomer_name())) {
				sheet.addCell(new Label(1,i+2,list.get(i).getCustomer_name(),cellFormat));
			}
			//合同号
			if(list.get(i).getContract_no() != null && !"".equals(list.get(i).getContract_no())) {
				sheet.addCell(new Label(2,i+2,list.get(i).getContract_no(),cellFormat));
			}
			//交货状态
			if(list.get(i).getDelivery_state_desc() != null && !"".equals(list.get(i).getDelivery_state_desc())) {
				sheet.addCell(new Label(3,i+2,list.get(i).getDelivery_state_desc(),cellFormat));
			}
			//产品名称
			if(list.get(i).getProd_name() != null && !"".equals(list.get(i).getProd_name())) {
				sheet.addCell(new Label(4,i+2,list.get(i).getProd_name(),cellFormat));
			}
			//牌号
			if(list.get(i).getSteel_name() != null) {
				sheet.addCell(new Label(5,i+2,""+list.get(i).getSteel_name(),cellFormat));
			}
			//规格     
			if(list.get(i).getWidth() != null &&list.get(i).getThick()!=null) {
				String specification=""+list.get(i).getWidth()+"*"+list.get(i).getThick();
				sheet.addCell(new Label(6,i+2,specification,cellFormat));
			}
			//重量（吨）
			if(list.get(i).getWeight() != null) {
				sheet.addCell(new Label(7,i+2,""+list.get(i).getWeight(),wcfN));
				totalTheoryWeight = DoubleUtil.add(totalTheoryWeight, list.get(i).getWeight());
			}
			//原料卷号
			if(list.get(i).getMaterailcoilno() != null && !"".equals(list.get(i).getMaterailcoilno())) {
				sheet.addCell(new Label(8,i+2,list.get(i).getMaterailcoilno(),cellFormat));
			}
			//钢卷号
			if(list.get(i).getCoilno() != null && !"".equals(list.get(i).getCoilno())) {
				sheet.addCell(new Label(9,i+2,list.get(i).getCoilno(),cellFormat));
			}
			//卸货地点
			if(list.get(i).getReciver_address() != null && !"".equals(list.get(i).getReciver_address())) {
				sheet.addCell(new Label(10,i+2,list.get(i).getReciver_address(),cellFormat));
			}
			//合同
			if(list.get(i).getContract_price() != null && !"".equals(list.get(i).getContract_price())) {
				String contract_pricce=""+list.get(i).getContract_price();
				sheet.addCell(new Label(11,i+2,contract_pricce,cellFormat));
			}
			//运费
			if(list.get(i).getTrade_price() != null && !"".equals(list.get(i).getTrade_price())) {
				String trade_price=""+list.get(i).getTrade_price();
				sheet.addCell(new Label(12,i+2,trade_price,wcfN));
			}
			//加工配送
			if(list.get(i).getWork_price() != null && !"".equals(list.get(i).getWork_price())) {
				String work_price=""+list.get(i).getWork_price();
				sheet.addCell(new Label(13,i+2,work_price,wcfN));
			}
			//结算单价
			if(list.get(i).getBalance_price() != null && !"".equals(list.get(i).getBalance_price())) {
				totalBalance_price+=list.get(i).getBalance_price();
				String balance_price=""+list.get(i).getBalance_price();
				sheet.addCell(new Label(14,i+2,balance_price,wcfN));
			}
			//总金额（元）
			if(list.get(i).getAmount() != null && !"".equals(list.get(i).getAmount())) {
				totalAmount =DoubleUtil.add(totalAmount, list.get(i).getAmount());
				sheet.addCell(new Label(15,i+2,""+list.get(i).getAmount(),wcfN));
			}			
			//冲减金额
			if(list.get(i).getSettle_write_down_fund() != null && !"".equals(list.get(i).getSettle_write_down_fund())) {
				if(i==0||!list.get(i).getSettle_bill_no().equals(list.get(i-1).getSettle_bill_no())){
					String settle_write_down_fund=""+list.get(i).getSettle_write_down_fund();
					sheet.addCell(new Label(16,i+2,settle_write_down_fund,wcfN));
				}else{
					sheet.addCell(new Label(16,i+2,"",wcfN));
				}
			}
			//冲减类型
			if(list.get(i).getSettle_write_down_type() != null && !"".equals(list.get(i).getSettle_write_down_type())) {
				if(i==0||!list.get(i).getSettle_bill_no().equals(list.get(i-1).getSettle_bill_no())){
					if("1".equals(list.get(i).getSettle_write_down_type())){
						sheet.addCell(new Label(17,i+2,"冲减",cellFormat));
					}else{
						sheet.addCell(new Label(17,i+2,"补收",cellFormat));
					}
				}else{
					sheet.addCell(new Label(17,i+2,"",cellFormat));
				}
			}

		}

		sheet.addCell(new Label(0,list.size()+2,"总计",cellFormat));
		WritableCellFormat cellFormat2 = new WritableCellFormat(font); 
		cellFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
		DecimalFormat df=new DecimalFormat("0.00");
		sheet.addCell(new Label(1,list.size()+2,""+list.size(),cellFormat2));//统计总条数
		//		sheet.addCell(new Label(7,list.size()+2,""+df.format((float)totalTheoryWeight),cellFormat2));//统计总重	
		sheet.addCell(new Label(7,list.size()+2,""+DoubleUtil.round(totalTheoryWeight,2),cellFormat2));//统计总重	
		//		sheet.addCell(new Label(14,list.size()+2,""+df.format((float)totalAmount/totalTheoryWeight),cellFormat2));//统计结算单价
		sheet.addCell(new Label(14,list.size()+2,""+DoubleUtil.round(totalAmount/totalTheoryWeight,2),cellFormat2));//统计结算单价
		//		sheet.addCell(new Label(15,list.size()+2,""+df.format((float)totalAmount),cellFormat2));//统计总金额
		sheet.addCell(new Label(15,list.size()+2,""+df.format(DoubleUtil.round(totalAmount,2)),cellFormat2));//统计总金额
		//		sheet.addCell(new Label(16,list.size()+2,""+df.format(total_write_down_fund),cellFormat2));//合计冲减金额
		sheet.addCell(new Label(16,list.size()+2,""+DoubleUtil.round(total_write_down_fund,2),cellFormat2));//合计冲减金额
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		sheet.getSettings().setVerticalFreeze(2);
		//关闭
		workbook.write();
		workbook.close();

		rm.setData("/download?filename="+file);
	}
	/**
	 * 结算单 - 结转
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCarryoverWeb(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		List<SlmFundSettleBill> list=sum.getObjectList();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			for(SlmFundSettleBill bill:list){
				bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
				if(bill==null){
					rm.setState("500");
					rm.setMsgInfo("数据丢失，请联系管理员");
					return rm;
				}
				if(!"6".equals(bill.getFlag())){
					rm.setState("500");
					rm.setMsgInfo("只有使用状态的结算单才能结转，不符合条件数据：["+bill.getSettle_bill_no()+"]");
					return rm;
				}
				int count=this.getMapper(SlmFundSettleBillMapper.class).countWithCondition(null, " flag='7'");
				bill.setCarryover_seq(String.valueOf(count));		//结转序列？
				bill.setCarryover_man_no(userId);
				bill.setCarryover_man_name(userName);
				bill.setCarryover_time(new Date());
				bill.setFlag("7"); 		//结转
				this.getMapper(SlmFundSettleBillMapper.class).update(bill);
				//修改三种费用的状态
				SlmFundSettleBillLine line=new SlmFundSettleBillLine();
				line.setSettle_bill_no(bill.getSettle_bill_no());
				List<SlmFundSettleBillLine> lineList=this.getMapper(SlmFundSettleBillLineMapper.class).find(line,0,0);
				for(SlmFundSettleBillLine lines:lineList){
					SlmLadingBillHeat heats=this.getMapper(SlmLadingBillHeatMapper.class).findById(lines.getBill_no());
					List<SlmFundSettleGood> goodList=this.getMapper(SlmFundSettleGoodMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
					for(SlmFundSettleGood goods:goodList){
						goods.setCarryover_man_no(userId);
						goods.setCarryover_man_name(userName);
						goods.setCarryover_time(new Date());
						goods.setFlag("6");		//结转
						this.getMapper(SlmFundSettleGoodMapper.class).update(goods);
					}
					List<SlmFundSettleCarriage> carriageList=this.getMapper(SlmFundSettleCarriageMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
					for(SlmFundSettleCarriage carriages:carriageList){
						carriages.setCarryover_man_no(userId);
						carriages.setCarryover_man_name(userName);
						carriages.setCarryover_time(new Date());
						carriages.setFlag("5");			//结转
						this.getMapper(SlmFundSettleCarriageMapper.class).update(carriages);
					}
					List<SlmFundSettleOther> otherList=this.getMapper(SlmFundSettleOtherMapper.class).findWithCondition(null, " bill_no='"+heats.getBill_no()+"'", null, 0, 0);
					for(SlmFundSettleOther others:otherList){
						others.setCarryover_man_no(userId);
						others.setCarryover_man_name(userName);
						others.setCarryover_time(new Date());
						others.setFlag("5");		//结转
						this.getMapper(SlmFundSettleOtherMapper.class).update(others);
					}
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	/**
	 * 查询某段时间 原料卷  提单状态信息
	 * */
	public ResultModel doQueryStatusWeb(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmFundSettleBill bill=sum.getObject();
		List<SlmFundSettleBillInvoice> list=new ArrayList<SlmFundSettleBillInvoice>();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();		
		try{		
			list=this.getMapper(SlmFundSettleBillInvoiceMapper.class).doQueryStatus(bill,startTime,endTime);
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	/**
	 * 打印查询到的某段时间 原料卷  提单状态信息
	 * */
	public ResultModel doExportExcelStatus(CommonPage<SlmFundSettleBill> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmFundSettleBill bill=sum.getObject();
		List<SlmFundSettleBillInvoice> list=new ArrayList<SlmFundSettleBillInvoice>();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();		
		try{		
			list=this.getMapper(SlmFundSettleBillInvoiceMapper.class).doQueryStatus(bill,startTime,endTime);
			// 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();
			}
			generateExcelStatus(rm, list, path);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	/**
	 *原料卷进程查询
	 *  报表打印
	 * **/
	private void generateExcelStatus(ResultModel rm, List<SlmFundSettleBillInvoice> list, String path)
			throws IOException, WriteException, RowsExceededException {
		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 + "原料卷进程查询";
		WritableWorkbook workbook;
		String file=filename+".xls";  //文件名
		//3. 操作EXCEL文件
		workbook = Workbook.createWorkbook(new File(path+file));
		WritableSheet sheet = workbook.createSheet("原料卷进程查询", 1);
		//行高
		sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.CENTRE);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		//
		jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##"); //设置数字格式
		jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); //设置表单格式
		wcfN.setAlignment(Alignment.CENTRE);
		wcfN.setVerticalAlignment(VerticalAlignment.CENTRE);
		//表头
		sheet.mergeCells(0, 0, 0, 1);
		sheet.addCell(new Label(0,0,"序号",cellFormat1));

		sheet.mergeCells(1, 0, 1, 1);
		sheet.addCell(new Label(1,0,"原料卷号",cellFormat1));

		sheet.mergeCells(2, 0, 2, 1);
		sheet.addCell(new Label(2,0,"牌号",cellFormat1));

		sheet.mergeCells(3, 0, 3, 1);
		sheet.addCell(new Label(3,0,"原料卷规格（厚度*宽度）",cellFormat1));

		sheet.mergeCells(4, 0, 4, 1);
		sheet.addCell(new Label(4,0,"理重",cellFormat1));

		sheet.mergeCells(5, 0, 5, 1);
		sheet.addCell(new Label(5,0,"实重",cellFormat1));

		sheet.mergeCells(6, 0, 6, 1);
		sheet.addCell(new Label(6,0,"卷号",cellFormat1));

		sheet.mergeCells(7, 0, 7, 1);
		sheet.addCell(new Label(7,0,"交货状态",cellFormat1));

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

		sheet.mergeCells(9, 0, 9, 1);
		sheet.addCell(new Label(9,0,"销售合同号",cellFormat1));

		sheet.mergeCells(10, 0, 10, 1);
		sheet.addCell(new Label(10,0,"销售订单号",cellFormat1));

		sheet.mergeCells(11, 0, 11, 1);
		sheet.addCell(new Label(11,0,"提单号",cellFormat1));

		sheet.mergeCells(12, 0, 12, 1);
		sheet.addCell(new Label(12,0,"提单子编号",cellFormat1));

		sheet.mergeCells(13, 0, 13, 1);
		sheet.addCell(new Label(13,0,"提单状态",cellFormat1));

		sheet.mergeCells(14, 0, 14, 1);
		sheet.addCell(new Label(14,0,"结算编号",cellFormat1));

		sheet.mergeCells(15, 0, 15, 1);
		sheet.addCell(new Label(15,0,"结算状态",cellFormat1));

		WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat = new WritableCellFormat(font); 
		cellFormat.setAlignment(Alignment.CENTRE);
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		//时间转字符串的格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		double totalTheoryWeight = 0,totalFactweight=0, totalBalance_price=0,totalAmount = 0;
		for(int i = 0; i < list.size(); i++) {
			//序号
			sheet.addCell(new Label(0,i+2,""+(i+1),cellFormat));
			//原料卷号
			if(list.get(i).getMaterailcoilno() != null && !"".equals(list.get(i).getMaterailcoilno())) {
				sheet.addCell(new Label(1,i+2,list.get(i).getMaterailcoilno(),cellFormat));
			}
			//牌号
			if(list.get(i).getSteel_name() != null) {
				sheet.addCell(new Label(2,i+2,""+list.get(i).getSteel_name(),cellFormat));
			}else{
				sheet.addCell(new Label(2,i+2,"",cellFormat));
			}
			//原料卷号规格     
			if(list.get(i).getWidth() != null &&list.get(i).getThick()!=null) {
				String specification=""+list.get(i).getWidth()+"*"+list.get(i).getThick();
				sheet.addCell(new Label(3,i+2,specification,cellFormat));
			}			
			//理重
			if(list.get(i).getTheoryweight()!=null){
				sheet.addCell(new Label(4,i+2,""+list.get(i).getTheoryweight(),wcfN));
				totalTheoryWeight += list.get(i).getTheoryweight();
			}
			//实重
			if(list.get(i).getFactweight()!=null){
				sheet.addCell(new Label(5,i+2,""+list.get(i).getFactweight(),wcfN));		
				totalFactweight += (list.get(i).getFactweight());
			}
			//卷号
			if(list.get(i).getCoilno() != null && !"".equals(list.get(i).getCoilno())) {
				sheet.addCell(new Label(6,i+2,list.get(i).getCoilno(),cellFormat));
			}
			//交货状态
			if(list.get(i).getDelivery_state_desc() != null && !"".equals(list.get(i).getDelivery_state_desc())) {
				sheet.addCell(new Label(7,i+2,list.get(i).getDelivery_state_desc(),cellFormat));
			}else {
				sheet.addCell(new Label(7,i+2,"",cellFormat));
			}
			//客户名称
			if(list.get(i).getCustomer_name() != null && !"".equals(list.get(i).getCustomer_name())) {
				sheet.addCell(new Label(8,i+2,list.get(i).getCustomer_name(),cellFormat));
			}else {
				sheet.addCell(new Label(8,i+2,"",cellFormat));
			}
			//销售合同号
			if(list.get(i).getContract_no() != null && !"".equals(list.get(i).getContract_no())) {
				sheet.addCell(new Label(9,i+2,list.get(i).getContract_no(),cellFormat));
			}else {
				sheet.addCell(new Label(9,i+2,"",cellFormat));
			}
			//销售订单号
			if(list.get(i).getOrder_no() != null && !"".equals(list.get(i).getOrder_no())) {
				sheet.addCell(new Label(10,i+2,list.get(i).getOrder_no(),cellFormat));
			}else {
				sheet.addCell(new Label(10,i+2,"",cellFormat));
			}
			//提单号
			if(list.get(i).getBill_no()!= null && !"".equals(list.get(i).getBill_no())) {
				sheet.addCell(new Label(11,i+2,list.get(i).getBill_no(),cellFormat));
			}else {
				sheet.addCell(new Label(11,i+2,"",cellFormat));
			}
			//提单子编号
			if(list.get(i).getLine_no() != null && !"".equals(list.get(i).getLine_no())) {
				sheet.addCell(new Label(12,i+2,list.get(i).getLine_no(),cellFormat));
			}else {
				sheet.addCell(new Label(12,i+2,"",cellFormat));
			}
			//提单状态
			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(13,i+2,validStatus,cellFormat));
			}else {
				sheet.addCell(new Label(13,i+2,"",cellFormat));
			}
			//结算编号
			if(list.get(i).getSettle_bill_no() != null && !"".equals(list.get(i).getSettle_bill_no())) {
				sheet.addCell(new Label(14,i+2,list.get(i).getSettle_bill_no(),cellFormat));
			}else {
				sheet.addCell(new Label(14,i+2,"",cellFormat));
			}
			//结算状态
			if(list.get(i).getFlag() != null && !"".equals(list.get(i).getFlag())) {
				String  Flag="";
				if(list.get(i).getFlag().equals("1")){
					Flag="编辑";
				}else if(list.get(i).getFlag().equals("2")){
					Flag="待确认";
				}else if(list.get(i).getFlag().equals("3")){
					Flag="确认";
				}else if(list.get(i).getFlag().equals("4")){
					Flag="开票申请";
				}else if(list.get(i).getFlag().equals("5")){
					Flag="票据勾稽";
				}else if(list.get(i).getFlag().equals("6")){
					Flag="使用";
				}else if(list.get(i).getFlag().equals("7")){
					Flag="结转";
				}
				sheet.addCell(new Label(15,i+2,Flag,cellFormat));
			}else {
				sheet.addCell(new Label(15,i+2,"",cellFormat));
			}

		}
		sheet.addCell(new Label(0,list.size()+2,"总计",cellFormat));
		WritableCellFormat cellFormat2 = new WritableCellFormat(font); 
		cellFormat2.setVerticalAlignment(VerticalAlignment.CENTRE);
		DecimalFormat df=new DecimalFormat("0.000");
		sheet.addCell(new Label(1,list.size()+2,""+list.size(),cellFormat2));//统计总条数
		sheet.addCell(new Label(4,list.size()+2,""+df.format(totalTheoryWeight),cellFormat2));//统计总理重
		sheet.addCell(new Label(5,list.size()+2,""+df.format(totalFactweight),cellFormat2));//统计总实重
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		sheet.getSettings().setVerticalFreeze(2);
		//关闭
		workbook.write();
		workbook.close();

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

	private final static Log logger = LogFactory.getLog(SlmFundSettleBillServiceImpl.class); 
	/**
	 * 调用用友NC接口，发送结算单数据，
	 * 并获取结算单对应的发票编号
	 * 表头：编号、合同号、结算单位、日期、标识（判断是加工配送（J）还是原料卷（Y））、总金额、总重量；
	 *	表体：序号、交货状态、牌号、订单规格、重量、结算单价、金额、psc 产品规范码 (物料编码) 、产品编码、产品名称
	 * */
	@SuppressWarnings("unchecked")
	public ResultModel sendSettleBillToNc(SlmFundSettleBill bill) throws Exception{
		ResultModel rm=new ResultModel();
		String re_start=bill.getHave_writeDown();
		String apply_no=bill.getMemo();		//开票申请编号--传给NC的参数应该以这个编号为主键，待与NC对接
		try{
			if(bill==null||bill.getSettle_bill_no()==null){
				return rm;
			}
			bill=this.getMapper(SlmFundSettleBillMapper.class).findById(bill.getSettle_bill_no());
			if(bill==null){
				return rm;
			}
			String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bill.getCreate_time());
			//组合参数
			String param="[{";
			//param+="\"primarykey\":\""+apply_no+"\",";				//编号
			param+="\"primarykey\":\""+bill.getSettle_bill_no()+"\",";				//编号
			param+="\"customername\":\""+bill.getCustomer_name()+"\","; 			//结算单位
			param+="\"ts\":\""+date+"\",";			//日期
			param+="\"note\":\""+bill.getSettle_bill_no()+"\",";				//结算单号

			CommonPage<SlmFundSettleBill> sum=new CommonPage<SlmFundSettleBill>();
			sum.setObject(bill);
			List<SlmFundSettleBillInvoice> line_list=(List<SlmFundSettleBillInvoice>) doQueryInvoiceWeb(sum).getData();
			//标识位
			List<SlmFundSettleBillLine> billline_list=this.getMapper(SlmFundSettleBillLineMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"'", null, 0, 0);
			if(billline_list.size()>0&&billline_list.get(0).getBill_no()!=null){
				if(billline_list.get(0).getBill_no().contains("J"))
					param+="\"flag\":\"J\",";			//标识（判断是加工配送（J）还是原料卷（Y））；
				else if(billline_list.get(0).getBill_no().contains("Y"))
					param+="\"flag\":\"Y\",";			//标识（判断是加工配送（J）还是原料卷（Y））；
				else if(billline_list.get(0).getBill_no().contains("N"))
					param+="\"flag\":\"N\",";			//标识（判断是加工配送（J）还是原料卷（Y））还是N；
				else if(billline_list.get(0).getBill_no().contains("L"))//L:冷轧提货单 20191123
					param+="\"flag\":\"L\",";			//标识（判断是加工配送（J）还是原料卷（Y））还是N：；
			}

			double total_weight=0d;
			double total_amount=0d;
			if(line_list!=null){
				boolean in=true;
				//红字发票，负数金额
				SlmFundInvoiceApply apply=this.getMapper(SlmFundInvoiceApplyMapper.class).findById(apply_no);
				if(apply!=null && apply.getInvoice_fund()!=null && apply.getInvoice_fund()<0){
					in=false;
				}
				for(SlmFundSettleBillInvoice lines:line_list){
					if(in){
						total_weight=DoubleUtil.add(total_weight,lines.getWeight());
						total_amount=DoubleUtil.add(total_amount,lines.getAmount());
					}else{
						total_weight=DoubleUtil.sub(total_weight,lines.getWeight());
						total_amount=DoubleUtil.sub(total_amount,lines.getAmount());
					}
				}
			}
			//开票金额计算（有冲减信息）
			double down_money=0;
			List<SlmFundSettleWriteDown> downList=this.getMapper(SlmFundSettleWriteDownMapper.class).findWithCondition(null, " settle_bill_no='"+bill.getSettle_bill_no()+"' and valid_flag='1' and flag in ('3','4','5')", null,0,0);		
			for(SlmFundSettleWriteDown downs:downList){
				if("1".equals(downs.getSettle_write_down_type())){ 		//冲减
					down_money=DoubleUtil.sub(down_money, downs.getSettle_write_down_fund());
				}else{
					down_money=DoubleUtil.add(down_money, downs.getSettle_write_down_fund());
				}
			}
			total_amount=DoubleUtil.add(total_amount, down_money);
			total_amount=DoubleUtil.round(total_amount, 2);
			param+="\"total_weight\":\""+total_weight+"\",";	
			param+="\"total_amount\":\""+total_amount+"\",";	
			param+="\"rowcounts\":\""+line_list.size()+"\"";
			if(line_list.size()>0){
				int seq=1;
				param+=",";
				for(SlmFundSettleBillInvoice lines:line_list){
					SlmContractLineInfo c_line=new SlmContractLineInfo();
					c_line.setContract_line_no(lines.getContract_line_no());
					c_line.setContract_line_seq(lines.getContract_line_seq());
					List<SlmContractLineInfo> c_line_list=this.getMapper(SlmContractLineInfoMapper.class).find(c_line,0,0);
					if(c_line_list.size()>0){
						c_line=c_line_list.get(0);
						//20200729 交货状态SB转CR传送到NC
						String delivery_state_desc = c_line.getDelivery_state_desc();
						if ("SB".equals(c_line.getDelivery_state_desc())) {
							delivery_state_desc = "CR";
						}
						param+="\"delivery_state_desc"+seq+"\":\""+delivery_state_desc+"\","; 		//交货状态
						param+="\"steel_name"+seq+"\":\""+c_line.getSteel_name()+"\","; 			//牌号
						param+="\"spec"+seq+"\":\""+c_line.getThick()+"*"+c_line.getWidth()+"\","; 			//规格
						param+="\"number"+seq+"\":\""+lines.getWeight()+"\","; 			//重量
						param+="\"nqtorigtaxprice"+seq+"\":\""+lines.getBalance_price()+"\",";		//结算单价
						param+="\"ntotalorigmny"+seq+"\":\""+lines.getAmount()+"\",";				//金额
						param+="\"psc"+seq+"\":\""+c_line.getPsc()+"\","; 			//产品规范码
						param+="\"psc_desc"+seq+"\":\""+c_line.getPsc_desc()+"\","; 			//产品规范码名称
						//param+="\"itemkey"+seq+"\":\""+lines.getDetail_no()+"\",";		//明细编号
						//明细编号取申请单号+明细编号的后6位 20191231丁跃提出
						String detailno = apply_no+lines.getDetail_no().substring(lines.getDetail_no().length()-6);
						param+="\"itemkey"+seq+"\":\""+detailno+"\",";		//明细编号
						param+="\"material"+seq+"\":\""+lines.getProd_name()+"\",";		//产品名称
						param+="\"material_code"+seq+"\":\""+lines.getProd_code()+"\",";		//产品编号
						param+="\"cqtunitid"+seq+"\":\"吨\",";
						seq++;
					}
				}
			}
			param=param.substring(0,param.length()-1);
			param+="}]";

			logger.error(param);
			System.out.println("======================------------------");
			System.out.println(param);
			//调用用友接口传参
			MessystemToNC65ServiceLocator locator=new MessystemToNC65ServiceLocator();
			OuterSystemRetVO result=locator.getMessystemToNC65ServiceSOAP11port_http().distributeMd("be02","q02","ADD", param);
			if(result!=null){
				if(!"yes".equals(re_start)&&"2".equals(result.getDataState())){
					bill.setHave_writeDown("yes");
					sendSettleBillToNc(bill);
				}
				System.out.println(result.getErrorMsg());
				String re_invoice_no=result.getErrorMsg();
				if(re_invoice_no.contains("=")){
					re_invoice_no=re_invoice_no.split("=")[1];
					re_invoice_no=re_invoice_no.substring(0,re_invoice_no.length()-2);
					bill.setInvoice_no(re_invoice_no);
					//this.getMapper(SlmFundSettleBillMapper.class).update(bill);
					rm.setData(re_invoice_no);
					List<SlmFundInvoiceApply> apply_list=this.getMapper(SlmFundInvoiceApplyMapper.class).findWithCondition(null, " apply_flag='3' and settle_bill_no='"+bill.getSettle_bill_no()+"' and valid_flag='1'", null, 0, 0);
					if(apply_list.size()>0){			//备注里表示，已发送给NC
						SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String memo=apply_list.get(0).getMemo();
						if(memo==null) memo="";
						memo=memo+sdf.format(new Date())+"发送给NC";
						apply_list.get(0).setMemo(memo);
						apply_list.get(0).setSend_time(new Date());
						this.getMapper(SlmFundInvoiceApplyMapper.class).update(apply_list.get(0));
					}
				}
				rm.setMsgInfo(result.getErrorMsg());
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}


}