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

import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javassist.bytecode.SignatureAttribute.ObjectType;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.mapper.ComPscMapper;
import market.Com.mapper.PbModelDbMapper;
import market.Com.pb.DoubleUtil;
import market.Com.pb.PbMethod;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.ComPsc;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.impl.IfRawMtrCoilPfmcServiceImpl;
import market.Lms.Warehouse.mapper.YdmBaseButtressconfigMapper;
import market.Lms.Warehouse.vo.ComPageIfRawMtrCoilPfmc;
import market.Lms.Warehouse.vo.YdmBaseButtressconfig;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Pms.Util.ImportUtil;
import market.Qms.com.mapper.BaseDeliverystateMapper;
import market.Qms.com.vo.BaseDeliverystate;
import market.Qms.metallurgy.mapper.ComMscMapper;
import market.Qms.metallurgy.vo.ComMsc;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractIdenOrgMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractPscOrgMapper;
import market.Slm.ContractManagement.service.SlmContractLineInfoService;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractIdenOrg;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmContractLineLv;
import market.Slm.ContractManagement.vo.SlmContractPscOrg;
import market.Slm.ContractManagement.vo.SlmCustomerContractCensus;
import market.Slm.ContractManagement.vo.SlmCustomerContractCensusSum;
import market.Slm.CustomerInformation.mapper.SlmCustomerAccountMapper;
import market.Slm.CustomerInformation.mapper.SlmCustomerInfoMapper;
import market.Slm.CustomerInformation.mapper.SlmCustomerObruInfoMapper;
import market.Slm.CustomerInformation.mapper.SlmCustomerTransSolutionMapper;
import market.Slm.CustomerInformation.vo.SlmCustomerAccount;
import market.Slm.CustomerInformation.vo.SlmCustomerInfo;
import market.Slm.CustomerInformation.vo.SlmCustomerObruInfo;
import market.Slm.CustomerInformation.vo.SlmCustomerTransSolution;
import market.Slm.FundManagement.impl.SlmFundThirdAccountServiceImpl;
import market.Slm.FundManagement.impl.SlmFundThirdAccountUsedServiceImpl;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundSecondAccountMapper;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.FundManagement.vo.SlmFundSecondAccount;
import market.Slm.FundManagement.vo.SlmFundThirdAccount;
import market.Slm.OrderManagement.impl.SlmOrderInfoServiceImpl;
import market.Slm.OrderManagement.mapper.SlmOrderInfoMapper;
import market.Slm.OrderManagement.vo.SlmOrderInfo;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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="SlmContractLineInfoService")
public class SlmContractLineInfoServiceImpl extends BaseServiceImpl<SlmContractLineInfo,Object> implements SlmContractLineInfoService {
	/**
	 * 点击头表查询所有行
	 * (contract_pk)
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmContractLineInfo> sum){
		ResultModel rm=new ResultModel();
		SlmContractLineInfo line=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmContractLineInfo> pm=new PageModel<SlmContractLineInfo>(pageIndex, pageSize);
		String order_flag=sum.getMemo1();
		try{
			String sOrder=" create_time";
			if("1".equals(order_flag))
				sOrder=" create_time desc";
			List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).findWithCondition(line,null, sOrder, (pageIndex-1)*pageSize,pageSize);
			int count=this.getMapper(SlmContractLineInfoMapper.class).countWithCondition(line, null);
			for(SlmContractLineInfo lines:lineList){
				SlmOrderInfo order=new SlmOrderInfo();
				order.setContract_pk(lines.getContract_pk());
				order.setContract_line_seq(lines.getContract_line_seq());
				List<SlmOrderInfo> orderlist=this.getMapper(SlmOrderInfoMapper.class).find(order,0,0);
				if(orderlist.size()>0){
					Double total_weight=lines.getEstimate_weight();
					Double material_total=0d;		//原料卷总重
					Double work_total=0d;		//加工总重
					Double unplan_total=0d;		//非计划总重
					Double cool_weight=0d;      //冷轧重量
					
					List<String> ordernatureList = new ArrayList<String>();
					for(SlmOrderInfo orders:orderlist){
						if("1".equals(orders.getOrder_nature())){		//原料卷
							material_total+=orders.getEstimate_weight();
							ordernatureList.add("1");
						}
						if("2".equals(orders.getOrder_nature())){		//需加工
							work_total+=orders.getEstimate_weight();
							ordernatureList.add("2");
						}
						if("3".equals(orders.getOrder_nature())){		//非计划
							unplan_total+=orders.getEstimate_weight();
							ordernatureList.add("3");
						}
						if("4".equals(orders.getOrder_nature())){		//冷轧
							cool_weight+=orders.getEstimate_weight();
							ordernatureList.add("4");
						}
						if("5".equals(orders.getOrder_nature())){		//酸洗
							cool_weight+=orders.getEstimate_weight();
							ordernatureList.add("5");
						}
					}
					/*合同行颜色标识处理，一条合同行不允许同时下发酸洗订单5、冷轧订单4、原料卷订单1；这三个订单可以做同一颜色处理，
					三个订单后下发后还可以下发需加工订单，需加工订单2和非计划订单3另外一种颜色*/
					if (ordernatureList.contains("1")||ordernatureList.contains("4")||ordernatureList.contains("5")) {
						lines.setIs_order("1");
					}
					if (ordernatureList.contains("2")||ordernatureList.contains("3")) {
						lines.setIs_order("2");
					}
					if (!(ordernatureList.contains("1")||ordernatureList.contains("4")||ordernatureList.contains("5")) 
							&& !(ordernatureList.contains("2")||ordernatureList.contains("3"))) {
						lines.setIs_order("3");
					}
					if ((ordernatureList.contains("1")||ordernatureList.contains("4")||ordernatureList.contains("5")) 
							&& (ordernatureList.contains("2")||ordernatureList.contains("3"))) {
						lines.setIs_order("4");
					}
					if (line.getIs_order()==null || "".equals(lines.getIs_order())) {
						line.setIs_order("3");
					}
					lines.setFinish_status("0");
//					绿色：原料卷 + 非计划重量>=合同行重量  或 冷轧 + 非计划重量=合同行重量
//					黄色：需加工重量>=合同行重量 
//					红色： 需加工重量 + 非计划重量>=合同行重量 且 (原料卷 + 非计划重量>=合同行重量 或 冷轧 + 非计划重量>=合同行重量）
					if(DoubleUtil.round((material_total+unplan_total)-total_weight, 4)>=0||DoubleUtil.round((cool_weight+unplan_total)-total_weight, 4)>=0){
						lines.setFinish_status("1");			//原料卷 + 非计划重量>=合同行重量 绿色
					}
					if(DoubleUtil.round(work_total-total_weight, 4)>=0){
						lines.setFinish_status("2");			//需加工重量>=合同行重量 黄色
					}
					if(DoubleUtil.round((unplan_total+work_total)-total_weight, 4)>=0&&(DoubleUtil.round((unplan_total+material_total)-total_weight, 4)>=0||DoubleUtil.round((cool_weight+material_total)-total_weight, 4)>=0)){
						lines.setFinish_status("3");			//重量已全部用完 橙色
					}
//					if(total_weight.equals(material_total+unplan_total)||total_weight.equals(cool_weight+unplan_total)){
//						lines.setFinish_status("1");			//原料卷 + 非计划重量>=合同行重量 绿色
//					}
//					if(total_weight.equals(work_total)){
//						lines.setFinish_status("2");			//需加工重量>=合同行重量 黄色
//					}
//					if(total_weight.equals(unplan_total+work_total)&&(total_weight.equals(unplan_total+material_total)||total_weight.equals(cool_weight+material_total))){
//						lines.setFinish_status("3");			//重量已全部用完 橙色
//					}
					lines.setHave_order("1"); 		//有订单
				}else{  
					lines.setHave_order("0");
				}
			}
			pm.setRows(lineList);
			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<SlmContractLineInfo> 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);
		SlmContractLineInfo line=sum.getObject();
		try{
			//合同生效后不允许新增合同行 add in 2018 11.15
			SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(line.getContract_pk());
			if(heat!=null){
				if(heat.getContract_no()!=null&&!"".equals(heat.getContract_no())){
					rm.setState("500");
					rm.setMsgInfo("合同生效之后不允许新增合同行");
					return rm;
				}
			}
			
			if(line.getWeight_type_no()==null||"102303".equals(line.getWeight_type_no())){
				rm.setState("500");
				rm.setMsgInfo("该计重方式暂无对应流程，请更换计重方式");
				return rm;
			}
			if (StringUtils.isEmpty(line.getDelivery_state_code())) {
				rm.setState("500");
				rm.setMsgInfo("交货状态为空，请确认");
				return rm;
			}
/**			//统一计重方式
			SlmContractLineInfo param=new SlmContractLineInfo();
			param.setContract_pk(line.getContract_pk());
			param.setValid_flag("1");
			List<SlmContractLineInfo> line_list=this.getMapper(SlmContractLineInfoMapper.class).find(param, 0, 0);
			for(SlmContractLineInfo lines:line_list){
				if(!lines.getWeight_type_no().equals(line.getWeight_type_no())){
					rm.setState("500");
					rm.setMsgInfo("该合同下的合同行计重方式为["+lines.getWeight_type_name()+"]，请保持一致");
					return rm;
				}
			}
*/
			SlmContractHeatInfo schi=new SlmContractHeatInfo();
			schi.setContract_pk(line.getContract_pk());
			schi.setContract_flag_no(sum.getMemo1());

			//需传入唯一键及状态编码，只有合同为什么状态才能新增
			int slm=this.getMapper(SlmContractHeatInfoMapper.class).count(schi);
			if(slm>0){
				int count=this.getMapper(SlmContractLineInfoMapper.class).countWithCondition(null, " contract_pk='"+line.getContract_pk()+"'")+1;
				line.setContract_line_seq(String.format("%03d", count));
				line.setContract_line_no(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
				line.setCreate_man_no(userId);
				line.setCreate_man_name(userName);
				line.setCreate_time(new Date());
				line.setValid_flag("1");
				line.setLine_flag_no("102601");
				line.setLine_flag_name("编辑");
				if(heat!=null){
					line.setContract_no(heat.getContract_no());

					//修改合同头的金额
					heat.setTax_total_price(DoubleUtil.round(heat.getTax_total_price()==null?0:heat.getTax_total_price(),DoubleUtil.SCALE_PRICE));
					heat.setNot_tax_total_price(DoubleUtil.round(heat.getNot_tax_total_price()==null?0:heat.getNot_tax_total_price(),DoubleUtil.SCALE_PRICE));
					if(line.getOrder_price1()!=null)
						heat.setTax_total_price(DoubleUtil.round(heat.getTax_total_price()+(line.getOrder_price1()*line.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
					if(line.getOrder_price2()!=null)
						heat.setNot_tax_total_price(DoubleUtil.round(heat.getNot_tax_total_price()+(line.getOrder_price2()*line.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
					this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
				}
				this.getMapper(SlmContractLineInfoMapper.class).insert(line);
				
				// 检测刚刚新增的这条合同行的序号是不是以及存在：20230306刘侣
				SlmContractLineInfo lineJC= new SlmContractLineInfo();
				lineJC.setContract_pk(line.getContract_pk());
				lineJC.setContract_line_seq(line.getContract_line_seq());
				int seqNum=this.getMapper(SlmContractLineInfoMapper.class).countWithCondition(lineJC, null);
				if (seqNum > 1) {
					throw new Exception("合同主键：" + line.getContract_pk() + " 下的合同行序号：" + line.getContract_line_seq() + " 已存在，请联系管理员处理；");
				}
				// end

				//根据默认的配置新增认证机构
				SlmContractPscOrg po=new SlmContractPscOrg();
				po.setPsc(line.getPsc());
				List<SlmContractPscOrg> po_list=this.getMapper(SlmContractPscOrgMapper.class).find(po,0,0);
				for(SlmContractPscOrg pos:po_list){
					SlmContractIdenOrg org=new SlmContractIdenOrg();
					String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3);
					org.setSeq(id);
					org.setOrg_code(pos.getOrg_code());
					org.setOrg_name(pos.getOrg_name());
					org.setPsc(pos.getPsc());
					org.setPsc_desc(pos.getPsc_desc());
					org.setContract_line_no(line.getContract_line_no());
					this.getMapper(SlmContractIdenOrgMapper.class).insert(org);
				}
				//新增精度等级
				if(line.getLv_list()!=null){
					for(SlmContractLineLv lvs:line.getLv_list()){
						lvs.setContract_line_no(line.getContract_line_no());
						lvs.setContract_line_seq(line.getContract_line_seq());
						lvs.setContract_pk(line.getContract_pk());
					}
					if(line.getLv_list().size()>0){
						CommonPage<SlmContractLineLv> lv_sum=new CommonPage<SlmContractLineLv>();
						lv_sum.setObjectList(line.getLv_list());
						this.getBean(SlmContractLineLvServiceImpl.class).doSaveWeb(lv_sum);
					}
				}
			}else{
				rm.setState("500");
				rm.setMsgInfo("该合同无法新增行信息!");
			}
			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 doDeleteWeb(CommonPage<SlmContractLineInfo> 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);
		try{
			SlmContractLineInfo newLine=this.getMapper(SlmContractLineInfoMapper.class).findById(sum.getObject().getContract_line_no());
			if(newLine!=null&&"102601".equals(newLine.getLine_flag_no())){		//能否操作
				SlmOrderInfo order=new SlmOrderInfo();
				order.setContract_pk(sum.getObject().getContract_pk());
				order.setContract_line_no(sum.getObject().getContract_line_no());
				order.setValid_flag("1");
				boolean judge=true;
				if("0".equals(sum.getObject().getValid_flag())){		//若停用 则判断其下订单状态
					List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(order,null,null,0,0);
					for(SlmOrderInfo orders:orderList){
						if(!"103401".equals(orders.getOrder_flag_no())){
							rm.setState("500");
							rm.setMsgInfo("该合同下有已"+orders.getOrder_flag_name()+"订单，无法停用");
							return rm;
						}
					}
					judge=false;
				}
				if("1".equals(sum.getObject().getValid_flag())){		//若启用 判断计重方式
					//统一计重方式
					SlmContractLineInfo param=new SlmContractLineInfo();
					param.setContract_pk(newLine.getContract_pk());
					param.setValid_flag("1");
					List<SlmContractLineInfo> line_list=this.getMapper(SlmContractLineInfoMapper.class).find(param, 0, 0);
					for(SlmContractLineInfo lines:line_list){
						if(!lines.getWeight_type_no().equals(newLine.getWeight_type_no())&&!lines.getContract_line_no().equals(newLine.getContract_line_no())){
							rm.setState("500");
							rm.setMsgInfo("该合同下的合同行计重方式为["+lines.getWeight_type_name()+"]，请保持一致");
							return rm;
						}
					}
				}

				//修改合同头的金额
				SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(sum.getObject().getContract_pk());
				if(heat!=null){
					heat.setTax_total_price(heat.getTax_total_price()==null?0:heat.getTax_total_price());
					heat.setNot_tax_total_price(heat.getNot_tax_total_price()==null?0:heat.getNot_tax_total_price());
					if(judge==true){
						if(newLine.getOrder_price1()!=null)
							heat.setTax_total_price(DoubleUtil.round(heat.getTax_total_price()+(newLine.getOrder_price1()*newLine.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
						if(newLine.getOrder_price2()!=null)
							heat.setNot_tax_total_price(DoubleUtil.round(heat.getNot_tax_total_price()+(newLine.getOrder_price2()*newLine.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
					}else{
						if(newLine.getOrder_price1()!=null)
							heat.setTax_total_price(DoubleUtil.round(heat.getTax_total_price()-(newLine.getOrder_price1()*newLine.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
						if(newLine.getOrder_price2()!=null)
							heat.setNot_tax_total_price(DoubleUtil.round(heat.getNot_tax_total_price()-(newLine.getOrder_price2()*newLine.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
					}
					this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
				}
				//修改合同行状态
				sum.getObject().setUpdate_man_no(userId);
				sum.getObject().setUpdate_man_name(userName);
				sum.getObject().setUpdate_time(new Date());
				if("0".equals(sum.getObject().getValid_flag())){		//停用
					sum.getObject().setDelete_man_no(userId);
					sum.getObject().setDelete_man_name(userName);
					sum.getObject().setDelete_time(new Date());
					sum.getObject().setValid_flag(sum.getObject().getValid_flag());
					this.getMapper(SlmContractLineInfoMapper.class).update(sum.getObject());
				}else{
					this.getMapper(SlmContractLineInfoMapper.class).doEnable(sum.getObject());
				}
				//修改订单状态
				order.setValid_flag(sum.getObject().getValid_flag());
				order.setDelete_man_no(userId);
				order.setDelete_man_name(userName);
				order.setDelete_time(new Date());
				this.getMapper(SlmOrderInfoMapper.class).doUpdate(order);
				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("该合同无法该操作!");
			}
		}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 doActualDeleteWeb(CommonPage<SlmContractLineInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		try{
			SlmContractLineInfo newLine=this.getMapper(SlmContractLineInfoMapper.class).findById(sum.getObject().getContract_line_no());
			if(newLine!=null&&"102601".equals(newLine.getLine_flag_no())){		//设定为编辑状态方可删除
				SlmOrderInfo order=new SlmOrderInfo();
				order.setContract_pk(sum.getObject().getContract_pk());
				order.setContract_line_no(sum.getObject().getContract_line_no());
				order.setValid_flag("1");
				List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(order,null,null,0,0);
				if(orderList.size()>0){
					rm.setState("500");
					rm.setMsgInfo("该合同下存在有效订单，无法删除");
					return rm;
				}
				//修改合同头的金额
				SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(sum.getObject().getContract_pk());
				if(heat!=null){
					heat.setTax_total_price(heat.getTax_total_price()==null?0:heat.getTax_total_price());
					heat.setNot_tax_total_price(heat.getNot_tax_total_price()==null?0:heat.getNot_tax_total_price());
					if(newLine.getOrder_price1()!=null)
						heat.setTax_total_price(DoubleUtil.round(heat.getTax_total_price()-(newLine.getOrder_price1()*newLine.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
					if(newLine.getOrder_price2()!=null)
						heat.setNot_tax_total_price(DoubleUtil.round(heat.getNot_tax_total_price()-(newLine.getOrder_price2()*newLine.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
					this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
				}
				//删除合同行
				this.getMapper(SlmContractLineInfoMapper.class).delete(sum.getObject().getContract_line_no());
				//删除订单
				rm=this.getBean(SlmOrderInfoServiceImpl.class).doDelete(order);
				if("500".equals(rm.getState()))	throw new Exception();
				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("该合同行无法该操作!");
			}
		}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 doUpdateWeb(CommonPage<SlmContractLineInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmContractLineInfo line=sum.getObject();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			SlmContractHeatInfo schi=new SlmContractHeatInfo();
			schi.setContract_pk(line.getContract_pk());
			schi.setContract_flag_no(sum.getMemo1());
			//若其下存在有效订单 ，则无法修改
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_line_no(line.getContract_line_no());
			order.setValid_flag("1");
			int count=this.getMapper(SlmOrderInfoMapper.class).count(order);
			if(count>0){
				rm.setState("500");
				rm.setMsgInfo("该合同行下存在有效订单，无法修改");
				return rm;
			}
			//统一计重方式
//			SlmContractLineInfo param=new SlmContractLineInfo();
//			param.setContract_pk(line.getContract_pk());
//			param.setValid_flag("1");
//			List<SlmContractLineInfo> line_list=this.getMapper(SlmContractLineInfoMapper.class).find(param, 0, 0);
//			for(SlmContractLineInfo lines:line_list){
//				if(!lines.getWeight_type_no().equals(line.getWeight_type_no())&&!lines.getContract_line_no().equals(line.getContract_line_no())){
//					rm.setState("500");
//					rm.setMsgInfo("该合同下的合同行计重方式为["+lines.getWeight_type_name()+"]，请保持一致");
//					return rm;
//				}
//			}

			//需传入唯一键及状态编码，只有合同为什么状态才能编辑
			int slm=this.getMapper(SlmContractHeatInfoMapper.class).count(schi);
			if(slm>0){
				//修改合同头金额
				SlmContractLineInfo newLine=this.getMapper(SlmContractLineInfoMapper.class).findById(line.getContract_line_no());
				SlmContractHeatInfo heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(line.getContract_pk());
				if(heat!=null&&newLine!=null){
					heat.setTax_total_price(heat.getTax_total_price()==null?0:heat.getTax_total_price());
					heat.setNot_tax_total_price(heat.getNot_tax_total_price()==null?0:heat.getNot_tax_total_price());
					if(line.getOrder_price1()!=null){
						Double new1=newLine.getOrder_price1()==null?0:newLine.getOrder_price1();
						Double tax=heat.getTax_total_price()-(new1*newLine.getEstimate_weight())+(line.getOrder_price1()*line.getEstimate_weight());
						heat.setTax_total_price(DoubleUtil.round(tax,DoubleUtil.SCALE_PRICE));
					}
					if(line.getOrder_price2()!=null){
						Double new2=newLine.getOrder_price2()==null?0:newLine.getOrder_price2();
						Double no_tax=heat.getTax_total_price()-(new2*newLine.getEstimate_weight())+(line.getOrder_price2()*line.getEstimate_weight());
						heat.setNot_tax_total_price(DoubleUtil.round(no_tax,DoubleUtil.SCALE_PRICE));
					}
					this.getMapper(SlmContractHeatInfoMapper.class).update(heat);

					if(line.getPsc()!=null&&!newLine.getPsc().equals(line.getPsc())){			//修改过产品
						//删除原有的
						SlmContractIdenOrg org_param=new SlmContractIdenOrg();
						org_param.setContract_line_no(line.getContract_line_no());
						List<SlmContractIdenOrg> org_list=this.getMapper(SlmContractIdenOrgMapper.class).find(org_param, 0, 0);
						for(SlmContractIdenOrg orgs:org_list){
							this.getMapper(SlmContractIdenOrgMapper.class).delete(orgs.getSeq());
						}
						//根据默认的配置新增认证机构
						SlmContractPscOrg po=new SlmContractPscOrg();
						po.setPsc(line.getPsc());
						List<SlmContractPscOrg> po_list=this.getMapper(SlmContractPscOrgMapper.class).find(po,0,0);
						for(SlmContractPscOrg pos:po_list){
							SlmContractIdenOrg org=new SlmContractIdenOrg();
							String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3);
							org.setSeq(id);
							org.setOrg_code(pos.getOrg_code());
							org.setOrg_name(pos.getOrg_name());
							org.setPsc(pos.getPsc());
							org.setPsc_desc(pos.getPsc_desc());
							org.setContract_line_no(line.getContract_line_no());
							this.getMapper(SlmContractIdenOrgMapper.class).insert(org);
						}
					}
				}
				line.setUpdate_man_no(userId);
				line.setUpdate_man_name(userName);
				line.setUpdate_time(new Date());
				this.getMapper(SlmContractLineInfoMapper.class).update(line);
				//新增精度等级
				if(line.getLv_list()!=null){
					for(SlmContractLineLv lvs:line.getLv_list()){
						lvs.setContract_line_no(line.getContract_line_no());
						lvs.setContract_line_seq(line.getContract_line_seq());
						lvs.setContract_pk(line.getContract_pk());
					}
					if(line.getLv_list().size()>0){
						CommonPage<SlmContractLineLv> lv_sum=new CommonPage<SlmContractLineLv>();
						lv_sum.setObjectList(line.getLv_list());
						lv_sum.setMemo2(line.getContract_line_no());
						this.getBean(SlmContractLineLvServiceImpl.class).doSaveWeb(lv_sum);
					}
				}
				
				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("该合同无法修改行信息!");
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 合同行 -详情
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<SlmContractLineInfo> sum){
		ResultModel rm=new ResultModel();
		SlmContractLineInfo line=sum.getObject();
		try{
			line=this.getMapper(SlmContractLineInfoMapper.class).findById(line.getContract_line_no());
			rm.setData(line);
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 合同行信息 - 提交
	 * 实现合同行提交评审，合同行状态变为待评审状态
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSubmitWeb(CommonPage<SlmContractLineInfo> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmContractLineInfo line=sum.getObject();
		rm.setState("200");
		try{
			SlmContractLineInfo scli=this.getMapper(SlmContractLineInfoMapper.class).findById(sum.getObject().getContract_line_no());
			//存在数据，且传过来的需修改的状态与数据表中的一致，那么修改为当前实体类中的状态
			if(scli!=null &&"102601".equals(scli.getLine_flag_no())){
				line.setP_line_flag_no(scli.getLine_flag_no());
				line.setP_line_flag_name(scli.getLine_flag_name());
				//				line.setLine_flag_no("102602");	//待评审
				//				line.setLine_flag_name("待评审");
				line.setLine_flag_no("102604");	//update in 2018.4.16
				line.setLine_flag_name("技术评审通过");
				if(scli.getContract_no()!=null&&!"".equals(scli.getContract_no())){
					line.setLine_flag_no("102608");	//add in 2018.6.27
					line.setLine_flag_name("生效");
				}
				this.getMapper(SlmContractLineInfoMapper.class).update(line);
			}else{
				rm.setState("500");
				rm.setMsgInfo("该数据无法执行此次操作!");
			}
		}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 doReview(SlmContractLineInfo line) throws Exception{
		ResultModel rm=new ResultModel();
		rm.setState("200");
		try{
			SlmContractLineInfo scli=this.getMapper(SlmContractLineInfoMapper.class).findById(line.getContract_line_no());
			//存在数据，且传过来的需修改的状态与数据表中的一致，那么修改为当前实体类中的状态
			if(scli!=null &&("102602".equals(scli.getLine_flag_no())||"102603".equals(scli.getLine_flag_no()))){
				line.setP_line_flag_no(scli.getLine_flag_no());
				line.setP_line_flag_name(scli.getLine_flag_name());
				line.setLine_flag_no("102604");	//技术评审通过
				line.setLine_flag_name("技术评审通过");
				this.getMapper(SlmContractLineInfoMapper.class).update(line);
			}else{
				rm.setState("500");
				rm.setMsgInfo("该数据无法执行此次操作!");
			}
		}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 doReviewFail(SlmContractLineInfo line) throws Exception{
		ResultModel rm=new ResultModel();
		rm.setState("200");
		try{
			SlmContractLineInfo scli=this.getMapper(SlmContractLineInfoMapper.class).findById(line.getContract_line_no());
			//存在数据，且传过来的需修改的状态与数据表中的一致，那么修改为当前实体类中的状态
			if(scli!=null &&("102602".equals(scli.getLine_flag_no())||"102603".equals(scli.getLine_flag_no()))){
				line.setP_line_flag_no(scli.getLine_flag_no());
				line.setP_line_flag_name(scli.getLine_flag_name());
				line.setLine_flag_no("102601");	//编辑
				line.setLine_flag_name("编辑");
				this.getMapper(SlmContractLineInfoMapper.class).update(line);
			}else{
				rm.setState("500");
				rm.setMsgInfo("该数据无法执行此次操作!");
			}
		}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 doCloseWeb(CommonPage<SlmContractLineInfo> 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);
		rm.setState("200");
		List<SlmContractLineInfo> list=sum.getObjectList();
		try{
			for(SlmContractLineInfo lines:list){		//验证其下订单状态
				SlmContractLineInfo check=this.getMapper(SlmContractLineInfoMapper.class).findById(lines.getContract_line_no());
				if("0".equals(check.getValid_flag())){		//状态验证【【
					rm.setMsgInfo("无效合同行无法结案");
					rm.setState("500");
					return rm;
				}
				SlmOrderInfo order=new SlmOrderInfo();
				if(lines.getContract_no()==null||"".equals(lines.getContract_no()))
					order.setContract_line_no(lines.getContract_line_no());
				else
					order.setContract_no(lines.getContract_no());
				order.setContract_line_seq(lines.getContract_line_seq());
				order.setValid_flag("1");
				List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQuery(order);
				for(SlmOrderInfo orders:orderList){
					if(!"103412".equals(orders.getOrder_flag_no())){		//有状态不为关闭的【或不为结算？待定
						rm.setMsgInfo("需合同行下所有订单处于关闭状态，才可以结案");
						rm.setState("500");
						return rm;
					}
				}
				lines.setLine_flag_no(check.getLine_flag_no());
				lines.setLine_flag_name(check.getLine_flag_name());
			}
			for(SlmContractLineInfo lines:list){
				lines.setP_line_flag_no(lines.getLine_flag_no());
				lines.setP_line_flag_name(lines.getLine_flag_name());
				lines.setLine_flag_no("102609");
				lines.setLine_flag_name("结案");
				lines.setUpdate_time(new Date());
				lines.setUpdate_man_no(userId);
				lines.setUpdate_man_name(userName);
				this.getMapper(SlmContractLineInfoMapper.class).update(lines);
				//取消金额占用
				rm=this.getBean(SlmFundThirdAccountUsedServiceImpl.class).doReleaseFund(lines.getContract_no(),lines,null,null);
				if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
			} 
		}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 doCancelCloseWeb(CommonPage<SlmContractLineInfo> 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);
		rm.setState("200");
		List<SlmContractLineInfo> list=sum.getObjectList();
		try{
			if(list!=null){
				boolean in=true;
				for(SlmContractLineInfo lines:list){
					SlmContractLineInfo check=this.getMapper(SlmContractLineInfoMapper.class).findById(lines.getContract_line_no());
					if(in){
						SlmContractHeatInfo heat=this.getBean(SlmContractHeatInfoServiceImpl.class).doQueryOne(check.getContract_pk());
						if("102105".equals(heat.getContract_flag_no())){
							rm.setState("500");
							rm.setMsgInfo("该合同行所在的合同头已结案，无法启用");
							return rm;
						}
						in=false;
					}
					if(check==null||!"102609".equals(check.getLine_flag_no())){
						rm.setState("500");
						rm.setMsgInfo("存在无法取消结案的合同行");
						return rm;
					}
				} 
			}
			for(SlmContractLineInfo lines:list){
				lines.setLine_flag_no(lines.getP_line_flag_no());
				lines.setLine_flag_name(lines.getP_line_flag_name());
				lines.setUpdate_time(new Date());
				lines.setUpdate_man_no(userId);
				lines.setUpdate_man_name(userName);
				this.getMapper(SlmContractLineInfoMapper.class).update(lines);
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("取消结案失败"+ex.getMessage());
			ex.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 用户协议完成情况统计
	 * memo1年份  memo2月份
	 * */
	public ResultModel doProtocolExportWeb(CommonPage<SlmContractLineInfo> sum){
		ResultModel rm=new ResultModel();
		SlmContractLineInfo line=sum.getObject();
		String sDate=sum.getMemo1();		//开始时间
		String eDate=sum.getMemo2();		//结束时间
		try{
			List<SlmCustomerContractCensus> censusList=new ArrayList<SlmCustomerContractCensus>();
			SlmCustomerContractCensusSum total=new SlmCustomerContractCensusSum();
			if(line==null) line=new SlmContractLineInfo();
			if(sDate==null||"".equals(sDate)){
				sDate=new SimpleDateFormat("yyyy-MM").format(new Date());
			}
			if(eDate==null||"".equals(eDate)){
				eDate=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			}
			sDate+="-01 00:00:00";
			SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");  
			Calendar calendar = Calendar.getInstance();  
			calendar.setTime(dft.parse(eDate));  
			calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));  
			sDate=dft.format(calendar.getTime())+" 23:59:59";  

			List<SlmContractLineInfo> list=this.getMapper(SlmContractLineInfoMapper.class).doProtocolCensus(line,sDate,eDate);
			Double total_weight=0d;
			for(SlmContractLineInfo lines:list){
				total_weight+=lines.getEstimate_weight();
				SlmCustomerContractCensus census=new SlmCustomerContractCensus();
				census.setCustomer_no(lines.getCustomer_no());
				census.setCustomer_name(lines.getCustomer_name());
				census.setDelivery_state_code(lines.getDelivery_state_code());
				census.setDelivery_state_desc(lines.getDelivery_state_desc());
				if(lines.getDelivery_state_desc().equals("AR")){
					census.setHot_rolling(lines.getEstimate_weight());
				}
				if(lines.getDelivery_state_desc().equals("HR")){
					census.setAcid_pickling(lines.getEstimate_weight());
				}
				if(lines.getDelivery_state_desc().equals("CR")){
					census.setCold_rolling(lines.getEstimate_weight());
				}	
				census.setTotal(lines.getEstimate_weight());      //现在只有轧硬
				censusList.add(census);
			}
			total.setCold_rolling_sum(total_weight);
			total.setList(censusList);
			rm.setState("200");
			rm.setData(total);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 品种完成情况统计
	 * memo1年份  memo2月份
	 * */
	public ResultModel doProdExportWeb(CommonPage<SlmContractLineInfo> sum){
		ResultModel rm=new ResultModel();
		SlmContractLineInfo line=sum.getObject();
		String year=sum.getMemo1();
		String month=sum.getMemo2();
		try{
			List<SlmCustomerContractCensus> censusList=new ArrayList<SlmCustomerContractCensus>();
			SlmCustomerContractCensusSum total=new SlmCustomerContractCensusSum();
			if(line==null) line=new SlmContractLineInfo();
			String date="";

			if(year!=null&&!"".equals(year))
				date=year;
			if(month!=null&&!"".equals(month)){
				month=String.format("%02d", Integer.parseInt(month));	
				date+="-"+month;
			}

			List<SlmContractLineInfo> list=this.getMapper(SlmContractLineInfoMapper.class).doProdCensus(line,date);
			Double total_weight=0d;
			Double cold_weight=0d;
			for(SlmContractLineInfo lines:list){
				cold_weight+=lines.getEstimate_weight();
				SlmCustomerContractCensus census=new SlmCustomerContractCensus();
				census.setProd_code(lines.getProd_code());
				census.setProd_name(lines.getProd_name());
				census.setContract_weight(lines.getEstimate_weight());
				census.setType("3");      //暂时只有冷轧
				censusList.add(census);
			}
			total_weight+=cold_weight;
			total.setCold_rolling_sum(cold_weight);
			total.setContract_weight_sum(total_weight);
			total.setList(censusList);
			rm.setState("200");
			rm.setData(total);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	//------------------逻辑方法-------------------------------------------------
	public List<SlmContractLineInfo> doQueryWithCondition(SlmContractLineInfo line,String sWhere,String sOrder,int pageIndex,int pageSize){
		List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).findWithCondition(line, sWhere, sOrder, pageIndex, pageSize);
		return lineList;
	}
	public void doUpdate(SlmContractLineInfo line){
		this.getMapper(SlmContractLineInfoMapper.class).update(line);
	}
	public SlmContractLineInfo doQueryById(String lineNo) {
		return this.getMapper(SlmContractLineInfoMapper.class).findById(lineNo);
	}
	
	/**
	 * 净重合同导出
	 * @param cp
	 * @return
	 */
	public ResultModel doQuaryWeightType102301(CommonPage<SlmContractLineInfo> cp){
		ResultModel rm = new ResultModel();
		String weight_type_no = cp.getMemo1();
		List<String> strList = this.getMapper(SlmContractLineInfoMapper.class).doQuaryWeightType102301(weight_type_no);
		rm.setData(strList);
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 合同导入 20210519
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doImportContractInfo() throws Exception{
		synchronized (this) {
			ResultModel rm = new ResultModel();
			Workbook wb = null;
			URL url = this.getClass().getClassLoader().getResource("/");
	        // 替换路径中的空格
	        String filePath = url.getPath().replaceAll("%20", " ");
	        File file = new File(filePath);
	        //1.导入excel
	        try {
				List<FileItem> items = ImportUtil.getUpload(SlmContractLineInfoServiceImpl.this,file,getRequest());		
				for (FileItem item : items) {
					// 若是文件域则读取文件流
					if (!item.isFormField()) {
						wb = ImportUtil.getWB(item, file.length());
					}
				}
				rm.setState("200");
				rm.setMsgInfo("合同模板读取成功！");
			} catch (FileUploadException e) {
				rm.setState("500");
				rm.setMsgInfo("合同模板读取失败！");
			}
	        //System.out.println("导入成功！");
	        
	        // 2.读取Excel数据
	        int numRow = 0;//最后的行数
	        Sheet sheet = null;
			try {
				//第一个表单
				sheet = wb.getSheetAt(0);
				//行数
				numRow = sheet.getLastRowNum();//最后的行数
			} catch (Exception e) {
				throw new Exception("Excel表格数据读取失败！" + e.getMessage());
			}
			
			List<SlmContractHeatInfo> schiList= new ArrayList<SlmContractHeatInfo>();
			List<SlmContractLineInfo> scliList= new ArrayList<SlmContractLineInfo>();
			List<String> contractnoList = new ArrayList<String>();//合同号集合
			try {
				if (numRow >= 1) {
					Date now = new Date();
					String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
					String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
					//税率,当前税率是13
					Double rate = null;
					ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById("950902");
					if (cbi!=null) {
						rate = Double.parseDouble(cbi.getBase_name());
					}
					String year = Calendar.getInstance().get(Calendar.YEAR)+"";//年度
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					SimpleDateFormat sdfsss = new SimpleDateFormat("yyyyMMddHHmmssSSS");
					Calendar calendar = Calendar.getInstance();
					
					String contract_type_name,customer_name,psc_desc,contract_no,contract_line_seq,steel_name,thick,width;
					String estimate_weight,tax_rate,order_price1,trade_price,weight_type_name,cut_edge_type_name,delivery_state_desc;
					String solutions_name,pk_ask_desc,precisicon_type_desc,sign_date,deliver_date,memo;
					
					String manage=new SimpleDateFormat("yyyyMMdd").format(now);
					int mNo=this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(null, " substr(manage_no,0,6)='"+manage+"'")+1;//管理卡号：202105 + 0001					
					for (int i = 1; i <= numRow; i++) {
						Row row = sheet.getRow(i);
						//数字转文本：以前导入税率不填也不会报错，现在居然会报错，改下逻辑：20230904 刘侣
						row.getCell(3).setCellType(Cell.CELL_TYPE_STRING); //合同号
						row.getCell(4).setCellType(Cell.CELL_TYPE_STRING); //合同行序号
						row.getCell(5).setCellType(Cell.CELL_TYPE_STRING); //牌号
						row.getCell(6).setCellType(Cell.CELL_TYPE_STRING); //厚度
						row.getCell(7).setCellType(Cell.CELL_TYPE_STRING); //宽度
						row.getCell(8).setCellType(Cell.CELL_TYPE_STRING); //重量
						if (row.getCell(9) != null) {
							row.getCell(9).setCellType(Cell.CELL_TYPE_STRING); //税率
						}
						row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);//订货价(含税)
						row.getCell(11).setCellType(Cell.CELL_TYPE_STRING); //运费
						
						//处理行数据
						contract_type_name = String.valueOf(row.getCell(0).getStringCellValue());	//合同类型						
						customer_name = ImportUtil.getCellValue(row.getCell(1));					//客户名称
						psc_desc = String.valueOf(row.getCell(2).getStringCellValue());				//产品规范码						
						contract_no = String.valueOf(row.getCell(3).getStringCellValue());			//合同号						
						contract_line_seq = String.valueOf(row.getCell(4).getStringCellValue());	//合同行序号
						steel_name = String.valueOf(row.getCell(5).getStringCellValue());			//牌号
						thick = String.valueOf(row.getCell(6).getStringCellValue());				//厚度						
						width = String.valueOf(row.getCell(7).getStringCellValue());				//宽度
						estimate_weight = ImportUtil.getCellValue(row.getCell(8));					//重量(t)
						tax_rate = ImportUtil.getCellValue(row.getCell(9));							//税率
						order_price1 = String.valueOf(row.getCell(10).getStringCellValue());			//订货价(含税)
						trade_price = ImportUtil.getCellValue(row.getCell(11)); 					//运费
						weight_type_name = ImportUtil.getCellValue(row.getCell(12)); 				//计重方式
						cut_edge_type_name = ImportUtil.getCellValue(row.getCell(13)); 				//切边方式
						delivery_state_desc = ImportUtil.getCellValue(row.getCell(14));				//交货状态 
						solutions_name = ImportUtil.getCellValue(row.getCell(15));					//运输方案 
						pk_ask_desc = ImportUtil.getCellValue(row.getCell(16));						//包装要求  
						precisicon_type_desc = ImportUtil.getCellValue(row.getCell(17));			//精度类型 
						sign_date = ImportUtil.getCellValue(row.getCell(18));						//签订日期 
						deliver_date = ImportUtil.getCellValue(row.getCell(19));					//交货日期 
						memo = ImportUtil.getCellValue(row.getCell(20));							//合同行备注
						
						// 空值检测：如果合同类型，客户名称，合同号都为空，判定这行是空行，跳过 20230504 刘侣
						if (StringUtils.isEmpty(contract_type_name.trim()) && StringUtils.isEmpty(customer_name.trim()) && StringUtils.isEmpty(contract_no.trim())) {
							continue;
						}
						// end
						
						if (StringUtils.isEmpty(contract_no.trim())) {
							throw new Exception("第"+(i+1)+"行的合同号为空,导入失败");
						}
						//如果合同号第一次导入，则新增合同头信息
						SlmContractHeatInfo schi = new SlmContractHeatInfo();
						if (!contractnoList.contains(contract_no.trim())) {						
							//判断合同号是否存在
							String countCondition = " and contract_no = '"+contract_no.trim()+"'";
							int count = this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(null, countCondition);
							if (count > 0) {
								throw new Exception("第"+(i+1)+"行的合同号在系统中已经存在,导入失败");
							}
							contractnoList.add(contract_no.trim());
							schi.setContract_no(contract_no.trim());						
							schi.setManage_no(manage+String.format("%04d", mNo));//管理卡号：202105 + 0111
							mNo++;
							String strContractPk=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());						
							schi.setContract_pk(strContractPk+PbMethod.RandomCreate(3));//合同号PK：20210519104710575 + 562						
							//合同类型
							if (StringUtils.isNotEmpty(contract_type_name.trim())) {
								String condition = " and base_name = '"+contract_type_name.trim()+"' and sort_code = '1016' and validflag = '1'";
								List<ComBaseInfo> cbiList = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
								if (CollectionUtils.isNotEmpty(cbiList)) {
									schi.setContract_type_no(cbiList.get(0).getBase_code());
									schi.setContract_type_name(contract_type_name.trim());
								}
							}else {
								throw new Exception("第"+(i+1)+"行的合同【"+contract_no+"】未填写【合同类型】,导入失败");
							}
							//客户名称
							if (StringUtils.isNotEmpty(customer_name.trim())) {
								String condition = " and customer_name like '%"+customer_name.trim()+"%' and valid_flag = '1'";
								List<SlmCustomerInfo> sciList = this.getMapper(SlmCustomerInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
								if (CollectionUtils.isEmpty(sciList)) {
									throw new Exception("未找到第"+(i+1)+"行的客户【"+customer_name.trim()+"】信息,导入失败");
								} 
								if (sciList.size() > 1) {
									throw new Exception("第"+(i+1)+"行的客户【"+customer_name.trim()+"】信息在系统中存在多条数据,导入失败");
								}								
								schi.setCustomer_no(sciList.get(0).getCustomer_no());
								schi.setCustomer_name(sciList.get(0).getCustomer_name());
								schi.setCustomer_abr(sciList.get(0).getCustomer_abbr());//客户简称
								schi.setPhone(sciList.get(0).getPhone());
								schi.setFax(sciList.get(0).getFax());
								schi.setZip_code(sciList.get(0).getZip_code());
								schi.setSale_org_no(sciList.get(0).getSale_org_no());
								schi.setSale_org_name(sciList.get(0).getSale_org_name());
								schi.setSale_area_no(sciList.get(0).getSale_area_no());
								schi.setSale_area_name(sciList.get(0).getSale_area_name());
								schi.setTrade_type_no(sciList.get(0).getTrade_type_no());
								schi.setTrade_type_name(sciList.get(0).getTrade_type_name());
								schi.setLegal_man(sciList.get(0).getCorporation_man());			//法人代表
								schi.setFrist_bill_unit(sciList.get(0).getCustomer_name());		//首次受票单位
							}else {
								throw new Exception("第"+(i+1)+"行的合同【"+contract_no+"】未填写【客户名称】,导入失败");
							}
							if (StringUtils.isNotEmpty(schi.getCustomer_no())) {
								String condition = " and customer_no = '"+schi.getCustomer_no()+"' and valid_flag = '1'";
								List<SlmCustomerAccount> scaList = this.getMapper(SlmCustomerAccountMapper.class).findWithCondition(null, condition, null, 0, 0);
								if (CollectionUtils.isNotEmpty(scaList)) {
									schi.setBack(scaList.get(0).getBack());
									schi.setAddress(scaList.get(0).getAddress());
									schi.setTax_registra_number(scaList.get(0).getTax_registra_number());
									schi.setTelphone(scaList.get(0).getTelphone());
									schi.setAccount(scaList.get(0).getAccount());							
								}							
								List<SlmCustomerObruInfo> scoiList = this.getMapper(SlmCustomerObruInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
								if (CollectionUtils.isNotEmpty(scoiList)) {
									for (SlmCustomerObruInfo scoi : scoiList) {
										if ("1".equals(scoi.getBalance_unit_flag())) {	//是否结算单位										
											schi.setBalance_unit_no(scoi.getUnit_no());
											schi.setBalance_unit_name(scoi.getUnit_name());
										}
										if ("1".equals(scoi.getOrder_unit_flag())) {	//是否订货单位
											schi.setOrder_unit_no(scoi.getUnit_no());
											schi.setOrder_unit_name(scoi.getUnit_name());
										}
									}							
								}
							}						
							schi.setSupply_unit_no("20180122102823908069");
							schi.setSupply_unit_name("新余新钢优特钢带有限公司");
							schi.setSupplier_address("新钢公司创效路");										
							schi.setTrade_type_no("100801");
							schi.setTrade_type_name("内贸");
							schi.setPrice_type_no("101801");
							schi.setPrice_type_name("锁价");
							schi.setTax_total_price(0d);//暂定为0
							schi.setNot_tax_total_price(0d);
							schi.setIs_tax("1");
							schi.setCurrency_no("101901");
							schi.setCurrency_name("人民币");
							schi.setPayment_type_no("102001");
							schi.setPayment_type_name("现款和银行承兑");
							schi.setContract_year(year);
							schi.setContract_flag_no("102104");//合同状态编号
							schi.setContract_flag_name("生效");
							schi.setEffect_man_no(userId);
							schi.setEffect_man_name(userName);
							schi.setMake_price_type_no("102201");
							schi.setMake_price_type_name("采购价");
							schi.setSign_address("江西新余");
							schi.setSign_date(sdf.parse(sign_date));//"yyyy-MM-dd"
							schi.setEffec_start_date(sdf.parse(sign_date));//有效开始时间 = 签订日期
							schi.setDeliver_date(sdf.parse(deliver_date));//交货日期
							//有效结束日期 = 交货日期 + 30
							calendar.setTime(sdf.parse(deliver_date));
							calendar.add(Calendar.DATE, 30);
							schi.setEffec_end_date(calendar.getTime());
							//schi.setMemo("合同模板导入");
							schi.setCreate_man_no(userId);
							schi.setCreate_man_name(userName);
							schi.setCreate_time(now);
							//税率
							if (StringUtils.isEmpty(tax_rate.trim())) {							
								schi.setTax_rate(rate);
							}else {
								schi.setTax_rate(Double.parseDouble(tax_rate.trim()));
							}										
							schi.setHave_control("1");
							schi.setValid_flag("1");
							schiList.add(schi);
						}else {
							//如果导入的数据，存在相同的合同号，则直接取已经存在的合同头
							for (SlmContractHeatInfo s : schiList) {
								if (s.getContract_no().equals(contract_no.trim())) {
									schi = s;
									continue;
								}
							}
						}
						
						//组装合同行数据
						SlmContractLineInfo scli = new SlmContractLineInfo();
						scli.setContract_line_no(sdfsss.format(new Date())); 					//20210518+133738+614
						scli.setContract_line_seq(String.format("%03d", Integer.parseInt(contract_line_seq.trim())));	//合同行序号
						scli.setContract_pk(schi.getContract_pk());
						scli.setContract_no(schi.getContract_no());
						
						//产品规范码
						if (StringUtils.isNotEmpty(psc_desc.trim())) {
							String condition = " and psc_desc = '"+psc_desc.trim()+"' and validflag = '1'";
							List<ComPsc> cpList = this.getMapper(ComPscMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isEmpty(cpList)) {
								throw new Exception("未找到第"+(i+1)+"行的产品规范码【"+psc_desc.trim()+"】信息,导入失败");
							} 
							if (cpList.size() > 1) {
								throw new Exception("第"+(i+1)+"行的产品规范码【"+psc_desc.trim()+"】信息在系统中存在多条数据,导入失败");
							}
							scli.setPsc(cpList.get(0).getPsc());
							scli.setPsc_desc(cpList.get(0).getPsc_desc());
							scli.setProd_code(cpList.get(0).getProd_code());
							scli.setProd_name(cpList.get(0).getProd_name());
							scli.setSteel_code(cpList.get(0).getSteel_code());
							scli.setSteel_name(cpList.get(0).getSteel_name());
							scli.setStd_code(cpList.get(0).getStd_code());
							scli.setStd_name(cpList.get(0).getStd_name());
							scli.setProd_cls_no(cpList.get(0).getProd_code_l());	//品种分类编号
							scli.setProd_cls_name(cpList.get(0).getProd_desc_l());
							scli.setProd_figure_no(cpList.get(0).getProd_code_l());	//产品形态编号
							scli.setProd_figure_name(cpList.get(0).getProd_desc_l());
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【产品规范码】,导入失败");
						}
						//冶金规范码编号
						if (StringUtils.isNotEmpty(psc_desc.trim())) {
							String condition = " and msc_desc = '"+psc_desc.trim()+"' and validflag = 'A'";
							List<ComMsc> cmList = this.getMapper(ComMscMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isEmpty(cmList)) {
								throw new Exception("未找到第"+(i+1)+"行的产品规范码【"+psc_desc.trim()+"】对应的冶金规范码信息,导入失败");
							} 
							if (cmList.size() > 1) {
								throw new Exception("第"+(i+1)+"行的产品规范码【"+psc_desc.trim()+"】信息在系统中存在多条冶金规范码数据,导入失败");
							}							
							scli.setMsc(cmList.get(0).getMsc());
							scli.setMsc_desc(cmList.get(0).getMsc_desc());
							scli.setMsc_type_no("A");
							scli.setMsc_type_name("卷材+板材");
							scli.setUse_code(cmList.get(0).getAlpha_code());	//用途码编号
							scli.setUse_desc(cmList.get(0).getAlpha_name());
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【产品规范码】,导入失败");
						}
						scli.setEstimate_weight(Double.parseDouble(estimate_weight.trim()));	//估算重量
						scli.setDelivery_error_rate(10d);										//交货量误差率
						//交货误差： 120*(1±0.1)  
						scli.setDelivery_error_max(Double.parseDouble(estimate_weight.trim())*(1+10/100));
						scli.setDelivery_error_min(Double.parseDouble(estimate_weight.trim())*(1-10/100));						
						scli.setSingle_weight_max(22d);		//单重上限
						scli.setSingle_weight_min(18d);		//单重下限
						scli.setSingle_weight_unit_no("100306");
						scli.setSingle_weight_unit_name("t");
						scli.setOrder_price1(Double.parseDouble(order_price1.trim()));//含税价
						//不含税价:  4250/(1+13)*100
						scli.setOrder_price2(DoubleUtil.round(Double.parseDouble(order_price1.trim())/(1+schi.getTax_rate())*100,DoubleUtil.SCALE_PRICE));				
						scli.setTrade_price(Double.parseDouble(trade_price.trim()));						
						scli.setDiameter_inn_unit_no("100304");
						scli.setDiameter_inn_unit_name("mm");
						scli.setDiameter_out_unit_no("100304");
						scli.setDiameter_out_unit_name("mm");
						scli.setThick(Double.parseDouble(thick.trim()));
						scli.setThick_unit_no("100304");
						scli.setThick_unit_name("mm");
						scli.setWidth(Double.parseDouble(width.trim()));
						scli.setWidth_unit_no("100304");
						scli.setWidth_unit_name("mm");
						scli.setLine_flag_no("102608");
						scli.setLine_flag_name("生效");
						scli.setMemo(memo);
						scli.setCreate_man_no(userId);
						scli.setCreate_man_name(userName);
						scli.setCreate_time(now);
						scli.setEstimate_weight_unit_no("100306");
						scli.setEstimate_weight_unit_name("t");
						scli.setDelivery_unit_no("100306");
						scli.setDelivery_unit_name("t");
						//交货状态
						if (StringUtils.isNotEmpty(delivery_state_desc.trim())) {
							String condition = " and delivery_state_desc = '"+delivery_state_desc.trim()+"' and validflag = '1'";
							List<BaseDeliverystate> cbdList = this.getMapper(BaseDeliverystateMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isEmpty(cbdList)) {
								throw new Exception("未找到第"+(i+1)+"行的交货状态【"+delivery_state_desc.trim()+"】信息,导入失败");
							} 
							if (cbdList.size() > 1) {
								throw new Exception("第"+(i+1)+"行的交货状态【"+delivery_state_desc.trim()+"】信息在系统中存在多条数据,导入失败");
							}							
							scli.setDelivery_state_code(cbdList.get(0).getDeliveryStateCode());
							scli.setDelivery_state_desc(cbdList.get(0).getDeliveryStateDesc());
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【交货状态】,导入失败");
						}						
						//运输方案
						if (StringUtils.isNotEmpty(solutions_name.trim())) {
							solutions_name = solutions_name.trim().replace("-", "到");
							String condition = " and solutions_name = '"+solutions_name+"' and customer_no = '"+schi.getCustomer_no()+"' and valid_flag = '1'";
							List<SlmCustomerTransSolution> sctsList = this.getMapper(SlmCustomerTransSolutionMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isEmpty(sctsList)) {
								throw new Exception("未找到第"+(i+1)+"行的运输方案【"+solutions_name+"】信息,导入失败");
							} 
							if (sctsList.size() > 1) {
								throw new Exception("第"+(i+1)+"行的运输方案【"+solutions_name+"】信息在系统中存在多条数据,导入失败");
							}							
							scli.setSolutions_no(sctsList.get(0).getSolutions_no());
							scli.setSolutions_name(sctsList.get(0).getSolutions_name());
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【运输方案】,导入失败");
						}
						scli.setIs_tax("1");
						scli.setTax_rate(schi.getTax_rate());						
						scli.setCurrency_no(schi.getCurrency_no());
						scli.setCurrency_name(schi.getCurrency_name());						
						//计重方式
						if (StringUtils.isNotEmpty(weight_type_name.trim())) {
							String condition = " and base_name = '"+weight_type_name.trim()+"' and sort_code = '1023' and validflag = '1'";
							List<ComBaseInfo> cbiList = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isNotEmpty(cbiList)) {
								scli.setWeight_type_no(cbiList.get(0).getBase_code());
								scli.setWeight_type_name(weight_type_name.trim());
							}
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【计重方式】,导入失败");
						}
						//切边方式
						if (StringUtils.isNotEmpty(cut_edge_type_name.trim())) {
							String condition = " and base_name = '"+cut_edge_type_name.trim()+"' and sort_code = '1025' and validflag = '1'";
							List<ComBaseInfo> cbiList = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isNotEmpty(cbiList)) {
								scli.setCut_edge_type_no(cbiList.get(0).getBase_code());
								scli.setCut_edge_type_name(cut_edge_type_name.trim());
							}
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【切边方式】,导入失败");
						}
						//精度类型
						if (StringUtils.isNotEmpty(precisicon_type_desc.trim())) {
							String condition = " and base_name = '"+precisicon_type_desc.trim()+"' and sort_code = '4112' and validflag = '1'";
							List<ComBaseInfo> cbiList = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isNotEmpty(cbiList)) {
								scli.setPrecisicon_type_code(cbiList.get(0).getBase_code());
								scli.setPrecisicon_type_desc(precisicon_type_desc.trim());
							}
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【精度类型】,导入失败");
						}
						//包装要求
						if (StringUtils.isNotEmpty(pk_ask_desc.trim())) {
							String condition = " and base_name = '"+pk_ask_desc.trim()+"' and sort_code = '2011' and validflag = '1'";
							List<ComBaseInfo> cbiList = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
							if (CollectionUtils.isNotEmpty(cbiList)) {
								scli.setPk_ask_code(cbiList.get(0).getBase_code());
								scli.setPk_ask_desc(pk_ask_desc.trim());
							}
						}else {
							throw new Exception("未找到第"+(i+1)+"行的【包装要求】,导入失败");
						}	
						scli.setValid_flag("1");
						scliList.add(scli);						
					}						
				}
			} catch (Exception e) {
				throw new Exception("组装数据失败！" + e.getMessage());
			}
			
			try {

				// 判断一个合同的合同行内的合同行序号是否已经存在：20230302 刘侣
				HashSet<String> hs = new HashSet<>();
				for(SlmContractLineInfo si : scliList) {
					// 判断此时的set集合中的长度和之前的长度的区别：
					if (!hs.add(si.getContract_no() + si.getContract_line_seq())) {
						throw new Exception("导入文件中，合同：" + si.getContract_no() + " 已经存在相同的合同序号：" + si.getContract_line_seq());
					}
				}
				// end
				
				this.getMapper(SlmContractHeatInfoMapper.class).insertBatch(schiList);
				this.getMapper(SlmContractLineInfoMapper.class).insertBatch(scliList);
				
				//付款节点控制
				for (SlmContractHeatInfo schi : schiList) {
					if(!"101603".equals(schi.getContract_type_no()) && !"101607".equals(schi.getContract_type_no())){
						this.getBean(SlmContractPaymentServiceImpl.class).doAutoAdd(schi);
					}
				}
				
				//TODO  修改合同头的金额
				for (SlmContractHeatInfo schi : schiList) {
					String condition = " and contract_pk = '"+schi.getContract_pk()+"' and valid_flag = '1'";
					List<SlmContractLineInfo> slList = this.getMapper(SlmContractLineInfoMapper.class).findWithCondition(null, condition, null, 0, 0);
					if (CollectionUtils.isNotEmpty(slList)) {
						for (SlmContractLineInfo sl : slList) {
							schi.setTax_total_price(DoubleUtil.round(schi.getTax_total_price()+(sl.getOrder_price1()*sl.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
							schi.setNot_tax_total_price(DoubleUtil.round(schi.getNot_tax_total_price()+(sl.getOrder_price2()*sl.getEstimate_weight()),DoubleUtil.SCALE_PRICE));
						}
					}
					this.getMapper(SlmContractHeatInfoMapper.class).update(schi);
				}
				
				//自动生成合同账号
				for (SlmContractHeatInfo schi : schiList) {
					//找到对应的客户账户
					List<SlmFundFirstAccount> sffaList=this.getMapper(SlmFundFirstAccountMapper.class).findWithCondition(null, " customer_no='"+schi.getCustomer_no()+"'", null, 0, 0);
					if(CollectionUtils.isNotEmpty(sffaList)){		//有客户账户，再查找产线账户
						List<SlmFundSecondAccount> sfsaList=this.getMapper(SlmFundSecondAccountMapper.class).findWithCondition(null, " first_account_no='"+sffaList.get(0).getFirst_account_no()+"'", null, 0, 0);
						if(CollectionUtils.isNotEmpty(sfsaList) && sfsaList.size()==1){				//只有一条产线账户：之前不知道为什么 == 0，现在合同导入默认解开合同账户新增
							SlmFundThirdAccount t_account=new SlmFundThirdAccount();			//生成合同账户
							t_account.setFirst_account_no(sffaList.get(0).getFirst_account_no());
							t_account.setFirst_account_name(sffaList.get(0).getFirst_account_name());
							t_account.setSecond_account_no(sfsaList.get(0).getSecond_account_no());
							t_account.setSecond_account_name(sfsaList.get(0).getSecond_account_name());
							t_account.setBalance_object_no(sffaList.get(0).getBalance_object_no());
							t_account.setBalance_object_name(sffaList.get(0).getBalance_object_name());
							t_account.setCustomer_no(sffaList.get(0).getCustomer_no());
							t_account.setCustomer_name(sffaList.get(0).getCustomer_name());
							t_account.setThird_account_no(schi.getContract_no());
							t_account.setThird_account_name(schi.getContract_no());
							t_account.setInit_fund(0d);
							this.getBean(SlmFundThirdAccountServiceImpl.class).doAddWeb(t_account);
						}
					}
				}
				
			} catch (Exception e) {
				throw new Exception("新增数据失败！" + e.getMessage());
			}
			return rm; 
		} 	
	}
	
	/**
	 * 合同维护界面：合同导出功能
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryContractLineInfoExport(CommonPage cp) throws Exception{
		ResultModel rm = new ResultModel();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		String condition = " 1=1";
		if (StringUtils.isNotEmpty(startTime.trim())) {
			condition += " and t.sign_date >= to_date('"+startTime.trim()+"', 'yyyy-MM-dd')";
		}
		if (StringUtils.isNotEmpty(endTime.trim())) {
			condition += " and t.sign_date <= to_date('"+endTime.trim()+"', 'yyyy-MM-dd')";
		}
		String sql = "select t.customer_name, t.DELIVER_DATE, t.contract_type_name, sc.contract_no, sc.contract_line_seq, sc.psc_desc,"
				+ " sc.prod_name, sc.std_name, sc.steel_name, sc.estimate_weight, sc.thick, sc.width, sc.solutions_name,"
				+ " sc.order_price1, sc.trade_price, sc.delivery_state_desc, sc.create_man_name, to_char(t.sign_date,'yyyy-MM-dd') create_time,sc.MEMO "
				+ " from slm_contract_heat_info t "
				+ " left join slm_contract_line_info sc on t.contract_pk = sc.contract_pk "
				+ " where "+condition
				+ " and t.valid_flag = '1' and sc.valid_flag = '1' "
				+ " order by t.customer_name, sc.contract_no, sc.contract_line_seq";
		List<HashMap> hmList = this.getMapper(PbModelDbMapper.class).doQueryHashMap(sql);
		rm.setState("200");
		rm.setData(hmList);
		return rm;
	}
}
