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

import java.io.File;
import java.io.IOException;
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.CellView;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import market.Com.pb.DoubleUtil;
import market.Com.pb.PbMethod;
import market.Com.pb.XMLUtil;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentMapper;
import market.Slm.ContractManagement.service.SlmContractHeatInfoService;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmContractPayment;
import market.Slm.CustomerInformation.mapper.SlmCustomerAccountMapper;
import market.Slm.CustomerInformation.mapper.SlmCustomerInfoMapper;
import market.Slm.CustomerInformation.vo.SlmCustomerAccount;
import market.Slm.CustomerInformation.vo.SlmCustomerInfo;
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.mapper.SlmFundThirdAccountMapper;
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.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="SlmContractHeatInfoService")
public class SlmContractHeatInfoServiceImpl extends BaseServiceImpl<SlmContractHeatInfo,Object> implements SlmContractHeatInfoService {
	
	/**
	 * 合同查询
	 * 合同文本号txt_contract_no模糊查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String startTime=sum.getStartTime();		
		String endTime=sum.getEndTime();
		String startTime2=sum.getStartTime2();		//创建时间
		String endTime2=sum.getEndTime2();
		String flag=sum.getMemo1();
		try{
			PageModel<SlmContractHeatInfo> pm = new PageModel<SlmContractHeatInfo>(pageIndex,pageSize);
			SlmContractHeatInfo sb=sum.getObject();
			String sWhere="1=1";
			if(sb!=null&&!"".equals(sb.getContract_no())&&sb.getContract_no()!=null){
				sWhere+=" and contract_no like '%"+sb.getContract_no()+"%'";
				sb.setContract_no(null);
			}
			if(startTime!=null&&!"".equals(startTime)){
				startTime+=" 00:00:00";
				sWhere+=" and to_char(sign_date, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
			}
			if(endTime!=null&&!"".equals(endTime)){
				endTime+=" 23:59:59";
				sWhere+=" and to_char(sign_date, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
			}
			if(startTime2!=null&&!"".equals(startTime2)){
				startTime2+=" 00:00:00";
				sWhere += " and create_time >= to_date('"+startTime2+"','yyyy-mm-dd hh24:mi:ss')"; 
			}
			if(endTime2!=null&&!"".equals(endTime2)){
				endTime2+=" 23:59:59";
				sWhere += " and create_time <= to_date('"+endTime2+"','yyyy-mm-dd hh24:mi:ss')";
			}
			if("1".equals(flag)){		//查询已生效，结案的
				sWhere+=" and contract_flag_no in('102104','102105')";
			}
			List<SlmContractHeatInfo> list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(sb, sWhere, " create_time desc", (pageIndex-1)*pageSize, pageSize);
			
			for(SlmContractHeatInfo heats:list){
				//查询付款类型
				if(heats.getHave_control()==null||"".equals(heats.getHave_control())){
					SlmContractPayment payment=new SlmContractPayment();
					payment.setValid_flag("1");
					payment.setContract_pk(heats.getContract_pk());
					int count=this.getMapper(SlmContractPaymentMapper.class).count(payment);
					if(count>0){
						heats.setHave_control("1");
					}else{
						heats.setHave_control("0");
					}
				}
				
				SlmContractLineInfo line=new SlmContractLineInfo();
				line.setContract_pk(heats.getContract_pk());
				line.setValid_flag("1");
				List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).find(line, 0, 0);
				Double total_weight=0d;
				int a=0;
				int b=0;
				int c=0;
				for(SlmContractLineInfo lines:lineList){
					total_weight+=lines.getEstimate_weight();
					//查询是否新增完订单
					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 material_total=0d;		//原料卷总重
						Double work_total=0d;		//加工总重
						Double unplan_total=0d;		//非计划总重
						Double cool_weight=0d;      //冷轧重量
						for(SlmOrderInfo orders:orderlist){
							if("1".equals(orders.getOrder_nature())){		//原料卷
								material_total+=orders.getEstimate_weight();
							}
							if("2".equals(orders.getOrder_nature())){		//需加工
								work_total+=orders.getEstimate_weight();
							}
							if("3".equals(orders.getOrder_nature())){		//非计划
								unplan_total+=orders.getEstimate_weight();
							}
							if("4".equals(orders.getOrder_nature())){		//冷轧
								cool_weight+=orders.getEstimate_weight();
							}
						}
						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){
							a++;			//原料卷 + 非计划重量>=合同行重量 绿色
						}
						if(DoubleUtil.round(work_total-total_weight, 4)>=0){
							b++;			//需加工重量>=合同行重量 黄色
						}
						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)){
							c++;			//重量已全部用完 橙色
						}
						lines.setHave_order("1"); 		//有订单
					}
				}
				heats.setFinish_status("0");
				if(a==lineList.size()&&a>0){
					heats.setFinish_status("1");
				}
				if(b==lineList.size()&&b>0){
					heats.setFinish_status("2");		
				}
				if(c==lineList.size()&&c>0){
					heats.setFinish_status("3");
				}
				heats.setTotal_weight(DoubleUtil.round(total_weight,DoubleUtil.DEF_DIV_SCALE));

				//如果没有账号信息
				//if(heats.getAccount()==null||(heats.getAccount()!=null && heats.getAccount().contains("201") && heats.getAccount().length()==20)){
				if(heats.getAccount()==null||(heats.getAccount()!=null && heats.getAccount().length()==20)){
					List<SlmCustomerAccount> account_list=this.getMapper(SlmCustomerAccountMapper.class).findWithCondition(null, " customer_no='"+heats.getCustomer_no()+"' and valid_flag='1'", null, 0, 0);
					if(account_list.size()>0){
						heats.setAccount(account_list.get(0).getAccount_no());
					}
				}
				//如果没有账号信息
				if(heats.getZip_code()==null){
					 SlmCustomerInfo  customer=this.getMapper(SlmCustomerInfoMapper.class).findById(heats.getCustomer_no());
					if(customer!=null){
						heats.setZip_code(customer.getZip_code());
					}
				}
			}
			pm.setRows(list);
			pm.setTotal(this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(sb,sWhere));
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 查询有结算单的合同
	 * */
	public ResultModel doQuerySettleWeb(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo heat=sum.getObject();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		try{
			List<SlmContractHeatInfo> list=this.getMapper(SlmContractHeatInfoMapper.class).doQuerySettle(heat,startTime,endTime);
			rm.setState("200");
			rm.setData(list);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 合同头详情查询
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		try{
			rm.setState("200");
			rm.setData(this.getMapper(SlmContractHeatInfoMapper.class).findById(sum.getObject().getContract_pk()));
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 添加数据
	 * @param bd
	 * @return
	 * @throws Exception 
	 */
	public ResultModel doAddWeb(CommonPage<SlmContractHeatInfo> sum) throws Exception {
		ResultModel rm=new ResultModel();
		try {
			SlmContractHeatInfo bd=sum.getObject();
			String strContractPk=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			bd.setContract_pk(strContractPk+PbMethod.RandomCreate(3));
			String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			bd.setCreate_man_no(userId);
			bd.setCreate_man_name(userName);

			int mNo=this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(null, " substr(manage_no,0,6)='"+strContractPk.substring(0,6)+"'")+1;
			bd.setManage_no(strContractPk.substring(0,6)+String.format("%04d", mNo));
			if(bd.getContract_no()==null)
				bd.setContract_no("");
			bd.setContract_flag_no("102101");			//编辑
			bd.setContract_flag_name("编辑");		//
			bd.setCreate_time(new Date());
			bd.setHave_control("0");
			this.getMapper(SlmContractHeatInfoMapper.class).insert(bd);

			//=============eason 2019-06-25 add ================================
			// 不为厂内合同则都需要走付款控制
			// 20191226  委托加工合同(针对新钢销售公司委托加工，不做资金控制)101607
			if(!"101603".equals(bd.getContract_type_no()) && !"101607".equals(bd.getContract_type_no())){
				this.getBean(SlmContractPaymentServiceImpl.class).doAutoAdd(bd);
			}
			
			//=============eason 2019-06-25 edit 注释代码================================
			//现款合同自动添加付款控制
			/*
			if("101601".equals(bd.getContract_type_no())){
				this.getBean(SlmContractPaymentServiceImpl.class).doAutoAdd(bd);
			}
			*/
			//=================================================
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，新增失败!"+e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 修改数据
	 * 只有状态为录入(编辑102101)的数据才可修改
	 * @param bd
	 * @return
	 * @throws Exception 
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmContractHeatInfo> sum) throws Exception {
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo obd = sum.getObject();
		try {
			SlmContractHeatInfo schi=this.getMapper(SlmContractHeatInfoMapper.class).findById(sum.getObject().getContract_pk());
			if(schi!=null
					&&"102101".equals(schi.getContract_flag_no()) //需考虑合同状态是否是可修改的
					){
				String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
				String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
				obd.setUpdate_man_no(userId);
				obd.setUpdate_man_name(userName);
				obd.setUpdate_time(new Date());
				this.getMapper(SlmContractHeatInfoMapper.class).update(obd);
			}else{
				rm.setState("500");
				rm.setMsgInfo("该合同状态无法修改");
				return rm;
			}
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("修改失败!"+e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 废除数据
	 * 需传入被删除数据应该是什么状态可删
	 * 生效之前可废除
	 * @param bd
	 * @return
	 * @throws Exception 
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteWeb(CommonPage<SlmContractHeatInfo> 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{
			SlmContractHeatInfo obd = sum.getObject();
			SlmContractHeatInfo schi=this.getMapper(SlmContractHeatInfoMapper.class).findById(sum.getObject().getContract_pk());
			if(schi!=null			//需考虑合同状态是否是可废除的
					&&"102101".equals(schi.getContract_flag_no()) 
					){
				SlmContractLineInfo line=new SlmContractLineInfo();
				line.setContract_pk(obd.getContract_pk());
				SlmOrderInfo order=new SlmOrderInfo();
				order.setContract_pk(obd.getContract_pk());
				if("0".equals(obd.getValid_flag())){		//若合同头置为无效
					//判断其下合同行和订单的状态
					List<SlmContractLineInfo> lineList=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryWithCondition(line,null,null,0,0);
					for(SlmContractLineInfo lines:lineList){
						if(!"102601".equals(lines.getLine_flag_no())){
							rm.setState("500");
							rm.setMsgInfo("该合同下有已"+lines.getLine_flag_name()+"合同行，无法停用");
							return rm;
						}
					}
					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;
						}
					}
				}
				schi.setValid_flag(obd.getValid_flag());
				schi.setDelete_man_no(userId);
				schi.setDelete_man_name(userName);
				schi.setDelete_time(new Date());
				this.getMapper(SlmContractHeatInfoMapper.class).update(schi);
				//修改合同行状态
				line.setValid_flag(obd.getValid_flag());
				line.setDelete_man_no(userId);
				line.setDelete_man_name(userName);
				line.setDelete_time(new Date());
				this.getMapper(SlmContractLineInfoMapper.class).doUpdate(line);
				//修改订单状态
				order.setValid_flag(obd.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 e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 提交或其它状态修改
	 * @throws Exception 
	 * */
	public ResultModel doSubmitWeb(CommonPage<SlmContractHeatInfo> sum) throws Exception {
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo heat = sum.getObject();
		List<SlmContractHeatInfo> list = sum.getObjectList();
		try{
			if(list==null){
				list=new ArrayList<SlmContractHeatInfo>();
				if(heat!=null) list.add(heat);
			} 
			for(SlmContractHeatInfo heats:list){
				SlmContractHeatInfo check=this.getMapper(SlmContractHeatInfoMapper.class).findById(heats.getContract_pk());
				if(check!=null&&"102101".equals(check.getContract_flag_no())){
					check.setP_contract_flag_no(check.getContract_flag_no());
					check.setP_contract_flag_name(check.getContract_flag_name());
					check.setContract_flag_no("102103");
					check.setContract_flag_name("评审通过");
					check.setHave_control(null);
					this.getMapper(SlmContractHeatInfoMapper.class).update(check);
					//合同行也一并提交
					SlmContractLineInfo line=new SlmContractLineInfo();
					line.setContract_pk(check.getContract_pk());
					line.setValid_flag("1");
					List<SlmContractLineInfo> lineList=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryWithCondition(line, null, null, 0, 0);
					CommonPage<SlmContractLineInfo> lineSum=new CommonPage<SlmContractLineInfo>();
					for(SlmContractLineInfo lines:lineList){
						lineSum.setObject(lines);
						this.getBean(SlmContractLineInfoServiceImpl.class).doSubmitWeb(lineSum);
					}
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 撤回 （评审通过状态的）
	 * @throws Exception 
	 * */
	public ResultModel doRollbackWeb(CommonPage<SlmContractHeatInfo> sum) throws Exception {
		ResultModel rm=new ResultModel();
		List<SlmContractHeatInfo> list = sum.getObjectList();
		SlmContractHeatInfo heat = sum.getObject();
		try{
			if(list==null){
				list=new ArrayList<SlmContractHeatInfo>();
				if(heat!=null) list.add(heat);
			} 
			SlmContractLineInfo line=new SlmContractLineInfo();
			line.setValid_flag("1");
			SlmContractHeatInfo check=new SlmContractHeatInfo();
			for(SlmContractHeatInfo heats:list){
				check=this.getMapper(SlmContractHeatInfoMapper.class).findById(heats.getContract_pk());
				if(check!=null&&"102103".equals(check.getContract_flag_no())){
					check.setP_contract_flag_no(check.getContract_flag_no());
					check.setP_contract_flag_name(check.getContract_flag_name());
					check.setContract_flag_no("102101");
					check.setContract_flag_name("编辑");
					check.setHave_control(null);
					this.getMapper(SlmContractHeatInfoMapper.class).update(check);
					//合同行也一并提交
					line.setContract_pk(check.getContract_pk());
					List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).find(line ,0, 0);
					for(SlmContractLineInfo lines:lineList){
						lines.setP_line_flag_no(lines.getLine_flag_no());
						lines.setP_line_flag_name(lines.getLine_flag_name());
						lines.setLine_flag_no("102601");
						lines.setLine_flag_name("编辑");
						this.getMapper(SlmContractLineInfoMapper.class).update(lines);
					}
				}else{
					rm.setState("500");
					rm.setMsgInfo("合同状态不为评审通过，无法撤回");
					return rm;
				}
			}
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 合同生效
	 * contract_pk及生效相关信息
	 * 生成合同号，填入合同头，行，订单。通过contract_pk关联查询
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doEffectWeb(CommonPage<SlmContractHeatInfo> 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{
			SlmContractHeatInfo heat=sum.getObject();
			SlmContractHeatInfo check=this.getMapper(SlmContractHeatInfoMapper.class).findById(heat.getContract_pk());
			//暂定 是否只有评审通过，      待审批的才能生效
			if(check!=null&&"1".equals(check.getValid_flag())&&("102103".equals(check.getContract_flag_no())||"102102".equals(check.getContract_flag_no()))){
				//生成合同号,更新头信息
				String contract_no="YT"+new SimpleDateFormat("yyyyMM").format(new Date());		//01为产线？
				int count=this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(null, " substr(contract_no,0,8)='"+contract_no+"'")+1;
				contract_no+=String.format("%04d", count);     
				//合同行 
				SlmContractLineInfo line=new SlmContractLineInfo();
				line.setContract_pk(heat.getContract_pk());
				line.setValid_flag("1");
				List<SlmContractLineInfo> lineList=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryWithCondition(line, "", "", 0, 0);
				int a=0;		//状态验证
				for(SlmContractLineInfo lines:lineList){
					if("102601".equals(lines.getLine_flag_no()))
						a++;
				}
				if(a>0){
					rm.setState("500");
					rm.setMsgInfo("该合同下存在未提交的合同行，无法生效");
					return rm;
				}
				if(heat.getContract_no()!=null&&!"".equals(heat.getContract_no())){
					SlmContractHeatInfo newHeat=new SlmContractHeatInfo();
					newHeat.setContract_no(heat.getContract_no());
					int newCount=this.getMapper(SlmContractHeatInfoMapper.class).count(newHeat);
					if(newCount>0){			//验证合同号是否已存在
						rm.setState("500");
						rm.setMsgInfo("该合同号已存在，请重新修改");
						return rm;
					}
					contract_no=heat.getContract_no();
				}else{
					heat.setContract_no(contract_no);	
				}

				//修改合同行、头的状态
				for(SlmContractLineInfo lines:lineList){
					lines.setP_line_flag_no(lines.getLine_flag_no());
					lines.setP_line_flag_name(lines.getLine_flag_name());
					lines.setLine_flag_no("102608");
					lines.setLine_flag_name("生效");
					lines.setContract_no(contract_no);
					//					lines.setUpdate_man_no(userId);
					//					lines.setUpdate_man_name(userName);
					//					lines.setUpdate_time(new Date());
					this.getBean(SlmContractLineInfoServiceImpl.class).doUpdate(lines);
				}
				//合同头
				heat.setEffect_man_no(userId);
				heat.setEffect_man_name(userName);
				heat.setContract_flag_no("102104");
				heat.setContract_flag_name("生效");
				heat.setP_contract_flag_no(check.getContract_flag_no());
				heat.setP_contract_flag_name(check.getContract_flag_name());
				this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
				//订单信息
				SlmOrderInfo order=new SlmOrderInfo();
				order.setContract_pk(heat.getContract_pk());
				List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(order, "", "", 0, 0);
				for(SlmOrderInfo orders:orderList){
					orders.setContract_no(contract_no);
					orders.setUpdate_man_no(userId);
					orders.setUpdate_man_name(userName);
					orders.setUpdate_time(new Date());
					this.getBean(SlmOrderInfoServiceImpl.class).doUpdate(orders);
				}
				//自动生成合同账号
				if(heat.getContract_no()!=null){
					SlmContractHeatInfo p_heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(heat.getContract_pk());
					//找到对应的客户账户
					List<SlmFundFirstAccount> f_account_list=this.getMapper(SlmFundFirstAccountMapper.class).findWithCondition(null, " customer_no='"+p_heat.getCustomer_no()+"'", null, 0, 0);
					if(f_account_list.size()>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);
						if(s_account_list.size()==1){			//只有一条产线账户
							SlmFundThirdAccount 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(heat.getContract_no());
							t_account.setThird_account_name(heat.getContract_no());
							t_account.setInit_fund(0d);
							this.getBean(SlmFundThirdAccountServiceImpl.class).doAddWeb(t_account);
						}
					}
				}
			}else{
				rm.setState("500");
				rm.setMsgInfo("该合同状态无法生效");
				return rm;
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 取消合同生效
	 * contract_pk及生效相关信息
	 * 生成合同号，填入合同头，行，订单。通过contract_pk关联查询
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelEffectWeb(CommonPage<SlmContractHeatInfo> 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);
		SlmContractHeatInfo heat=sum.getObject();
		try{
			SlmContractHeatInfo check=this.getMapper(SlmContractHeatInfoMapper.class).findById(heat.getContract_pk());
			//订单信息
			SlmOrderInfo order=new SlmOrderInfo();
			order.setContract_pk(heat.getContract_pk());
			List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(order, "", "", 0, 0);
			for(SlmOrderInfo orders:orderList){
				//				if(Integer.parseInt(orders.getOrder_flag_no())>103402&&!"103405".equals(orders.getOrder_flag_no())){
				if("1".equals(orders.getValid_flag())){
					rm.setState("500");
					rm.setMsgInfo("该合同下存在有效订单，无法取消生效，请走合同变更流程");
					return rm;
				}
			}
			for(SlmOrderInfo orders:orderList){
				orders.setContract_no("");
				orders.setUpdate_man_no(userId);
				orders.setUpdate_man_name(userName);
				orders.setUpdate_time(new Date());
				this.getBean(SlmOrderInfoServiceImpl.class).doUpdate(orders);
			}

			//更新头信息
			//暂时 修改为 编辑状态 （应该为 102103  评审通过）
			//			SlmContractHeatInfo check=this.getMapper(SlmContractHeatInfoMapper.class).findById(heat.getContract_pk());
			//			if(check!=null&&check.getP_contract_flag_no()!=null){
			//				heat.setContract_flag_no(check.getP_contract_flag_no());
			//				heat.setContract_flag_name(check.getP_contract_flag_name());
			//			}else{

			heat.setContract_flag_no("102101");
			heat.setContract_flag_name("编辑");
			//			}
			this.getMapper(SlmContractHeatInfoMapper.class).doCancelEffect(heat);
			//合同行
			SlmContractLineInfo line=new SlmContractLineInfo();
			line.setContract_pk(heat.getContract_pk());
			List<SlmContractLineInfo> lineList=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryWithCondition(line, "", "", 0, 0);
			for(SlmContractLineInfo lines:lineList){
				lines.setContract_no("");
				lines.setLine_flag_no("102601");
				lines.setLine_flag_name("编辑");
				lines.setUpdate_man_no(userId);
				lines.setUpdate_man_name(userName);
				lines.setUpdate_time(new Date());
				this.getBean(SlmContractLineInfoServiceImpl.class).doUpdate(lines);
			}

			//删除合同账户
			if(check!=null&&check.getContract_no()!=null&&!"".equals(check.getContract_no())){
				SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(check.getContract_no());
				if(t_account!=null){
					this.getMapper(SlmFundThirdAccountMapper.class).delete(check.getContract_no());
				}
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 合同头结案
	 * 合同头下所有合同行处于结案状态，该合同头才可结案。
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCloseWeb(CommonPage<SlmContractHeatInfo> 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<SlmContractHeatInfo> list=sum.getObjectList();
		try{
			if(list!=null){
				for(SlmContractHeatInfo heat:list){
					//合同行状态检验
					SlmContractLineInfo line=new SlmContractLineInfo();
					line.setContract_pk(heat.getContract_pk());
					line.setValid_flag("1");
					List<SlmContractLineInfo> lineList=this.getBean(SlmContractLineInfoServiceImpl.class).doQueryWithCondition(line, "", "", 0, 0);
					for(SlmContractLineInfo lines:lineList){
						if(!"102609".equals(lines.getLine_flag_no())){		//不为结案
							rm.setState("500");
							rm.setMsgInfo("该合同头下存在未结案的合同行，无法结案");
							return rm;
						}
					}
				}
			}
			for(SlmContractHeatInfo heat:list){
				SlmContractHeatInfo check=this.getMapper(SlmContractHeatInfoMapper.class).findById(heat.getContract_pk());
				if(!"102105".equals(check.getContract_flag_no())){
					heat.setP_contract_flag_no(check.getContract_flag_no());
					heat.setP_contract_flag_name(check.getContract_flag_name());
					heat.setContract_flag_no("102105");
					heat.setContract_flag_name("结案");
					heat.setClose_man_no(userId);
					heat.setClose_man_name(userName);
					heat.setUpdate_man_no(userId);
					heat.setUpdate_man_name(userName);
					heat.setUpdate_time(new Date());
					this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
				}
				//取消金额占用
				rm=this.getBean(SlmFundThirdAccountUsedServiceImpl.class).doReleaseFund(check.getContract_no(),null,null,null);
				if("500".equals(rm.getState())) throw new Exception(rm.getMsgInfo());
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 合同头取消结案
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelCloseWeb(CommonPage<SlmContractHeatInfo> 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<SlmContractHeatInfo> list=sum.getObjectList();
		try{
			for(SlmContractHeatInfo heat:list){
				SlmContractHeatInfo check=this.getMapper(SlmContractHeatInfoMapper.class).findById(heat.getContract_pk());
				heat.setContract_flag_no(check.getP_contract_flag_no());
				heat.setContract_flag_name(check.getP_contract_flag_name());
				heat.setClose_man_no("");
				heat.setClose_man_name("");
				heat.setUpdate_man_no(userId);
				heat.setUpdate_man_name(userName);
				heat.setUpdate_time(new Date());
				this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 合同生效时，查询默认结束时间
	 * */
	public ResultModel doQueryDefaultTime(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo heat=sum.getObject();
		SlmOrderInfo order=new SlmOrderInfo();
		order.setContract_pk(heat.getContract_pk());
		order.setValid_flag("1");
		List<SlmOrderInfo> orderList=this.getBean(SlmOrderInfoServiceImpl.class).doQueryWithCondition(order, null, null, 0, 0);
		Date date=null;
		for(SlmOrderInfo orders:orderList){
			if(date==null){
				date=orders.getDeliver_date();
			}else{
				if(orders.getDeliver_date().getTime()>date.getTime())
					date=orders.getDeliver_date();
			}
		}
		Calendar now =Calendar.getInstance();  
		now.setTime(date);  
		now.set(Calendar.DATE,now.get(Calendar.DATE)+30);
		String reDate=new SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
		rm.setData(reDate);
		rm.setState("200");
		return rm;
	}

	/**
	 * 合同打印
	 * */
	public ResultModel doPrintWeb(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo heat=sum.getObject();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		heat=this.getMapper(SlmContractHeatInfoMapper.class).findById(heat.getContract_pk());
		if(heat!=null&&!"0".equals(heat.getValid_flag())){
			//通过验证 修改打印人，打印次数
			if(heat.getPrint_num()==null){
				heat.setPrint_num(1);
			}else{
				heat.setPrint_num(heat.getPrint_num()+1);
			}
			heat.setPrint_time(new Date());
			heat.setPrint_man_no(userId);
			heat.setPrint_man_name(userName);
			this.getMapper(SlmContractHeatInfoMapper.class).update(heat);
			rm.setState("200");
		}else{
			rm.setState("500");
			rm.setMsgInfo("该合同无法打印，请检查状态");
		}
		return rm;
	}

	/**
	 * 合同跟踪
	 * */
	public ResultModel doQueryTrackWeb(CommonPage<SlmContractHeatInfo> sum){
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo heat=sum.getObject();
		String startTime=sum.getStartTime();		//签订时间
		String endTime=sum.getEndTime();
		try{
			List<SlmContractHeatInfo> list=this.getMapper(SlmContractHeatInfoMapper.class).doQueryTrack(heat,startTime,endTime);
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 查询可新增合同账号的合同号
	 * */
	public ResultModel doQueryContractNo(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo heat=sum.getObject();
		try{
			List<SlmContractHeatInfo> list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(heat, " contract_flag_no='102104' and valid_flag='1'", " create_time desc", 0, 0);
			List<SlmContractHeatInfo> newList=new ArrayList<SlmContractHeatInfo>();
			List<SlmFundThirdAccount> account_list=this.getMapper(SlmFundThirdAccountMapper.class).findWithCondition(null," customer_no='"+heat.getCustomer_no()+"'",null,0,0);
			for(SlmContractHeatInfo heats:list){
				boolean in=true;
				for(SlmFundThirdAccount account:account_list){
					if(account.getThird_account_no().equals(heats.getContract_no())){
						in=false;
					}
				}
				if(in){
					newList.add(heats);
				}
			}
			rm.setState("200");
			rm.setData(newList);
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 合同号校验
	 * */
	public ResultModel doCheckContractNo(String contractNo){
		ResultModel rm=new ResultModel();
		rm.setState("200");
		SlmContractHeatInfo newHeat=new SlmContractHeatInfo();
		newHeat.setContract_no(contractNo);
		int newCount=this.getMapper(SlmContractHeatInfoMapper.class).count(newHeat);
		if(newCount>0){			//验证合同号是否已存在
			rm.setState("500");
			rm.setMsgInfo("该合同号已存在，请重新修改");
		}
		return rm;
	}

	public SlmContractHeatInfo doQueryOne(String contract_pk) {
		return this.getMapper(SlmContractHeatInfoMapper.class).findById(contract_pk);
	}
	
	/**
	 * 报表管理--销售报表--销售合同交付情况查询
	 * @param sum
	 * @return
	 */
	public ResultModel doQueryReport(CommonPage<SlmContractHeatInfo> sum){
		ResultModel rm=new ResultModel();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		SlmContractHeatInfo sch = sum.getObject();
		List<HashMap> lhm=this.getMapper(SlmContractHeatInfoMapper.class).doQueryReport(startTime,endTime,sch);		
		rm.setData(lhm);
		rm.setState("200");
		return rm;
	}

	

	//====================================eason add 2019-07-09 app端=======================
	/**
	 * 合同查询
	 * 合同文本号txt_contract_no模糊查询
	 * */
	public ResultModel doQueryApp(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String startTime=sum.getStartTime();//签订日期		
		String endTime=sum.getEndTime();
		String startTime2=sum.getStartTime2();//交货日期
		String endTime2=sum.getEndTime2();
		try{
			PageModel<SlmContractHeatInfo> pm = new PageModel<SlmContractHeatInfo>(pageIndex,pageSize);
			SlmContractHeatInfo sb=sum.getObject();
			String sWhere="customer_no='"+this.getSession().getAttribute(HomeService.SESSION_DEPT_ID)+"'";
			if(sb!=null&&!"".equals(sb.getContract_no())&&sb.getContract_no()!=null){
				sWhere+="  and contract_no like '%"+sb.getContract_no()+"%'";
				sb.setContract_no(null);
			}
			if(startTime!=null&&!"".equals(startTime)){
				startTime+=" 00:00:00";
				sWhere+=" and to_char(sign_date, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
			}
			if(endTime!=null&&!"".equals(endTime)){
				endTime+=" 23:59:59";
				sWhere+=" and to_char(sign_date, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
			}
			if(startTime2!=null&&!"".equals(startTime2)){
				startTime2+=" 00:00:00";
				sWhere+=" and to_char(deliver_date, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime2+"'";
			}
			if(endTime2!=null&&!"".equals(endTime2)){
				endTime2+=" 23:59:59";
				sWhere+=" and to_char(deliver_date, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime2+"'";
			}
			List<SlmContractHeatInfo> list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(sb, sWhere, " create_time desc", (pageIndex-1)*pageSize, pageSize);
			for(SlmContractHeatInfo heats:list){
				//查询付款类型
				if(heats.getHave_control()==null||"".equals(heats.getHave_control())){
					SlmContractPayment payment=new SlmContractPayment();
					payment.setValid_flag("1");
					payment.setContract_pk(heats.getContract_pk());
					int count=this.getMapper(SlmContractPaymentMapper.class).count(payment);
					if(count>0){
						heats.setHave_control("1");
					}else{
						heats.setHave_control("0");
					}
				}
				SlmContractLineInfo line=new SlmContractLineInfo();
				line.setContract_pk(heats.getContract_pk());
				line.setValid_flag("1");
				List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).find(line, 0, 0);
				Double total_weight=0d;
				for(SlmContractLineInfo lines:lineList){
					total_weight+=lines.getEstimate_weight();
				}
				// heats.setLine(lineList);
				heats.setTotal_weight(DoubleUtil.round(total_weight,DoubleUtil.DEF_DIV_SCALE));
			}
			pm.setRows(list);
			pm.setTotal(this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(sb,sWhere));
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 合同查询
	 * */
	public ResultModel doQueryDetailApp(CommonPage<SlmContractHeatInfo> sum) {
		ResultModel rm=new ResultModel();
		SlmContractHeatInfo heat=sum.getObject()==null?new SlmContractHeatInfo():sum.getObject();
		try{
			//heat.setCustomer_no("201712270001");
			heat.setCustomer_no((String)this.getSession().getAttribute(HomeService.SESSION_DEPT_ID));
			List<SlmContractHeatInfo> list=this.getMapper(SlmContractHeatInfoMapper.class).doQueryDetailTrack(heat);
			List<SlmContractHeatInfo> ls=new ArrayList<SlmContractHeatInfo>();
			for(SlmContractHeatInfo heatC : list){
				SlmContractLineInfo line=new SlmContractLineInfo();
				line.setContract_pk(heatC.getContract_pk());
				line.setValid_flag("1");
				List<SlmContractLineInfo> lineList=this.getMapper(SlmContractLineInfoMapper.class).find(line, 0, 0);
				heatC.setLine(lineList);
				ls.add(heatC);
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
}  

