/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-01-13
 * 描述            ：客户发票管理表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Slm.FundManagement.impl;
import java.util.Date;
import java.util.List;

import market.Com.pb.DoubleUtil;
import market.Com.pb.PbMethod;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.FundManagement.mapper.SlmFundDiscountMapper;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.service.SlmFundDiscountService;
import market.Slm.FundManagement.vo.SlmFundDiscount;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.NcService.MessystemToNC65ServiceLocator;
import market.Slm.NcService.OuterSystemRetVO;

import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;
import com.ibm.icu.text.SimpleDateFormat;

@RemoteService(path="SlmFundDiscountService")
public class SlmFundDiscountServiceImpl extends BaseServiceImpl<SlmFundDiscount,Object> implements SlmFundDiscountService {

	/**
	 * 查询 -贴息
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmFundDiscount> sum){
		ResultModel rm=new ResultModel();
		SlmFundDiscount dis=sum.getObject();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		try{
			String sWhere=" 1=1 ";
			if(startTime!=null&&!"".equals(startTime)){		//页面上为贴息时间，目前为创建时间
				sWhere+=" and to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
			}
			if(endTime!=null&&!"".equals(endTime)){
				sWhere+=" and to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
			}
			List<SlmFundDiscount> list=this.getMapper(SlmFundDiscountMapper.class).findWithCondition(dis, sWhere, " VALID_FLAG desc,CREATE_TIME desc", 0, 0);
			for(SlmFundDiscount dises:list){
				dises.setStatus("0");
				if("3".equals(dises.getFlag())||"4".equals(dises.getFlag())){
					dises.setStatus("1");
				}else if("5".equals(dises.getFlag())){
					dises.setStatus("2");
				}
			}
			rm.setData(list);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 新增 -贴息
	 * */
	public ResultModel doAddWeb(CommonPage<SlmFundDiscount> sum){
		ResultModel rm=new ResultModel();
		SlmFundDiscount dis=sum.getObject();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try{
			String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(3);
			dis.setSeq(id);
			dis.setCreate_man_no(userId);
			dis.setCreate_man_name(userName);
			dis.setCreate_time(new Date());
			dis.setValid_flag("1");
			dis.setFlag("1");		//1：编辑
			this.getMapper(SlmFundDiscountMapper.class).insert(dis);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 贴息 - 修改
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateWeb(CommonPage<SlmFundDiscount> sum){
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		SlmFundDiscount dis=sum.getObject();
		try{
			if(dis==null||dis.getSeq()==null){
				rm.setState("500");
				rm.setMsgInfo("请选择数据进行修改");
				return rm;
			}
			SlmFundDiscount check=this.getMapper(SlmFundDiscountMapper.class).findById(dis.getSeq());
			if(check==null||!"1".equals(check.getFlag())){
				rm.setState("500");
				rm.setMsgInfo("数据状态不为编辑无法修改");
				return rm;
			}
			dis.setUpdate_man_no(userId);
			dis.setUpdate_man_name(userName);
			dis.setUpdate_time(new Date());
			this.getMapper(SlmFundDiscountMapper.class).update(dis);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 贴息 - 删除
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteWeb(CommonPage<SlmFundDiscount> sum){
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		List<SlmFundDiscount> dis_list=sum.getObjectList();
		try{
			for(SlmFundDiscount dis:dis_list){
				dis=this.getMapper(SlmFundDiscountMapper.class).findById(dis.getSeq());
				if(dis==null){
					rm.setState("500");
					rm.setMsgInfo("数据不存在，请联系管理员处理");
					return rm;
				}
				if(!"1".equals(dis.getFlag())){
					rm.setState("500");
					rm.setMsgInfo("只有编辑状态的数据才能删除");
					return rm;
				}
				dis.setValid_flag("0"); 		//无效
				dis.setDelete_man_no(userId);
				dis.setDelete_man_name(userName);
				dis.setDelete_time(new Date());
				this.getMapper(SlmFundDiscountMapper.class).update(dis);
			}
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 提交
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSubmitWeb(CommonPage<SlmFundDiscount> 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<SlmFundDiscount> disList=sum.getObjectList();
		try{
			for(SlmFundDiscount dis:disList){
				dis=this.getMapper(SlmFundDiscountMapper.class).findById(dis.getSeq());
				if(dis!=null&&"1".equals(dis.getFlag())){
					dis.setUpdate_man_no(userId);
					dis.setUpdate_man_name(userName);
					dis.setUpdate_time(new Date());
					dis.setFlag("2");		//待确认
					this.getMapper(SlmFundDiscountMapper.class).update(dis);
				}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;
	}

	/**
	 * 撤回
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRollbackWeb(CommonPage<SlmFundDiscount> 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<SlmFundDiscount> disList=sum.getObjectList();
		try{
			for(SlmFundDiscount dis:disList){
				dis=this.getMapper(SlmFundDiscountMapper.class).findById(dis.getSeq());
				if(dis!=null&&"2".equals(dis.getFlag())){
					dis.setUpdate_man_no(userId);
					dis.setUpdate_man_name(userName);
					dis.setUpdate_time(new Date());
					dis.setFlag("1");   		//编辑
					this.getMapper(SlmFundDiscountMapper.class).update(dis);
				}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;
	}

	/**
	 * 审核通过
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doPassWeb(CommonPage<SlmFundDiscount> 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<SlmFundDiscount> disList=sum.getObjectList();
		try{
			for(SlmFundDiscount dis:disList){
				dis=this.getMapper(SlmFundDiscountMapper.class).findById(dis.getSeq());
				if(dis!=null&&"2".equals(dis.getFlag())){
					SlmFundFirstAccount account=this.getMapper(SlmFundFirstAccountMapper.class).findById(dis.getFirst_account_no());
					if(account==null){
						rm.setState("500");
						rm.setMsgInfo("客户账户"+dis.getFirst_account_name()+"数据丢失，请联系管理员");
						return rm;
					}

					dis.setFlag("3");   		//确认
					dis.setCheck_man_no(userId);
					dis.setCheck_man_name(userName);
					dis.setCheck_time(new Date());

					double dis_money=dis.getBalance_fund_discount();
					if(dis_money>account.getUse_fund()){
						throw new Exception("贴息金额["+dis_money+"]大于客户账户的可用金额["+account.getUse_fund()+"]");
					}
					//修改一级账户的金额
					account.setBalance_fund(DoubleUtil.sub(account.getBalance_fund(), dis_money));			//财务-
					account.setFinal_fund(DoubleUtil.sub(account.getFinal_fund(), dis_money));			//可拨-
					account.setUse_fund(DoubleUtil.sub(account.getUse_fund(), dis_money));			//可用-
					account.setDiscount_fund(DoubleUtil.add(account.getDiscount_fund(), dis_money));			//贴息+
					if(account.getFinal_fund()<0||account.getFinal_fund()>account.getUse_fund()) 
						account.setFinal_fund(account.getUse_fund());
					this.getMapper(SlmFundFirstAccountMapper.class).update(account);
					this.getMapper(SlmFundDiscountMapper.class).update(dis);
					
					//=====eason 2019-08-14 add==========
					//sendDiscountToNc(dis, "1");
					//===================================
					
				}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;
	}

	/**
	 * 反审 确认改成待确认
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doNotPassWeb(CommonPage<SlmFundDiscount> 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<SlmFundDiscount> disList=sum.getObjectList();
		try{
			for(SlmFundDiscount dis:disList){
				dis=this.getMapper(SlmFundDiscountMapper.class).findById(dis.getSeq());
				if(dis!=null&&"3".equals(dis.getFlag())){
					SlmFundFirstAccount account=this.getMapper(SlmFundFirstAccountMapper.class).findById(dis.getFirst_account_no());
					if(account==null){
						rm.setState("500");
						rm.setMsgInfo("客户账户"+dis.getFirst_account_name()+"数据丢失，请联系管理员");
						return rm;
					}
					dis.setUpdate_man_no(userId);
					dis.setUpdate_man_name(userName);
					dis.setUpdate_time(new Date());
					dis.setCheck_man_no("");
					dis.setCheck_man_name("");
					dis.setFlag("2");   		//待确认
					this.getMapper(SlmFundDiscountMapper.class).doNotPass(dis);

					//修改一级账户的金额
					double dis_money=dis.getBalance_fund_discount();
					account.setBalance_fund(DoubleUtil.add(account.getBalance_fund(), dis_money));			//财务+
					account.setFinal_fund(DoubleUtil.add(account.getFinal_fund(), dis_money));			//可拨+
					account.setUse_fund(DoubleUtil.add(account.getUse_fund(), dis_money));			//可用+
					account.setDiscount_fund(DoubleUtil.sub(account.getDiscount_fund(), dis_money));
					this.getMapper(SlmFundFirstAccountMapper.class).update(account);
				
					//=====eason 2019-08-14 add==========
					//sendDiscountToNc(dis, "0");
					//===================================
					
				}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;
	}

	/**
	 * 关联
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRelationWeb(CommonPage<SlmFundDiscount> 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);
		SlmFundDiscount discount=sum.getObject();
		try{
			SlmFundDiscount check=this.getMapper(SlmFundDiscountMapper.class).findById(discount.getSeq());
			if(check==null||discount.getInvoice_no()==null){
				rm.setState("500");
				rm.setMsgInfo("请检查参数");
				return rm;
			}
			if("3".equals(check.getFlag())||"4".equals(check.getFlag())){
				discount.setRelation_man_no(userId);
				discount.setRelation_man_name(userName);
				discount.setRelation_time(new Date());
				discount.setFlag("5");    		//已关联
				this.getMapper(SlmFundDiscountMapper.class).update(discount);
			}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;
	}

	/**
	 * 取消关联
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doCancelRelationWeb(CommonPage<SlmFundDiscount> sum) throws Exception{
		ResultModel rm=new ResultModel();
		SlmFundDiscount discount=sum.getObject();
		try{
			SlmFundDiscount check=this.getMapper(SlmFundDiscountMapper.class).findById(discount.getSeq());
			if(check==null){
				rm.setState("500");
				rm.setMsgInfo("请检查参数");
				return rm;
			}
			if("5".equals(check.getFlag())){
				discount.setRelation_man_no("");
				discount.setRelation_man_name("");
				discount.setInvoice_no("");
				discount.setFlag("3");    		//
				this.getMapper(SlmFundDiscountMapper.class).update(discount);
			}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;
	}

	/**
	 * 发送贴息数据
	 * status 1 正常发送   0撤销
	 * */
	public ResultModel sendDiscountToNc(SlmFundDiscount dis,String status) throws Exception{
		ResultModel rm=new ResultModel();
		String param="[{";
		try{
			String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dis.getCreate_time());
			//组合参数
			param+="\"primarykey\":\""+dis.getSeq()+"\",";				//编号
			param+="\"customername\":\""+dis.getCustomer_name()+"\","; 			//结算单位
			param+="\"ts\":\""+date+"\",";			//日期
			param+="\"note\":\""+dis.getBalance_fund_discount()+"\",";				//贴息金额
			param+="\"status\":\""+status+"\",";				//发送贴息数据  1 正常发送   0撤销
			param=param.substring(0,param.length()-1);
			param+="}]";

			logger.info(param);
			//调用用友接口传参
			MessystemToNC65ServiceLocator locator=new MessystemToNC65ServiceLocator();
			OuterSystemRetVO result=locator.getMessystemToNC65ServiceSOAP11port_http().distributeMd("be02","q02","ADD", param);
			if(result!=null){
				String re_invoice_no=result.getErrorMsg();
				rm.setMsgInfo(re_invoice_no);
				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("调用NC接口异常1,传送NC系统失败");
				this.logger.error("============调用NC接口异常1："+param);
			}
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo("调用NC接口异常2,传送NC系统失败");
			this.logger.error("===============调用NC接口异常2："+param+"："+e.getMessage());
			//throw e;
		}
		return rm;
	}
}