/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-01-13
 * 描述            ：客户二级账户明细信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Slm.FundManagement.impl;
import java.text.SimpleDateFormat;
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.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundSecondAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundSecondDetailMapper;
import market.Slm.FundManagement.mapper.SlmFundThirdAccountMapper;
import market.Slm.FundManagement.service.SlmFundSecondDetailService;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.FundManagement.vo.SlmFundSecondAccount;
import market.Slm.FundManagement.vo.SlmFundSecondDetail;
import market.Slm.FundManagement.vo.SlmFundThirdAccount;

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="SlmFundSecondDetailService")
public class SlmFundSecondDetailServiceImpl extends BaseServiceImpl<SlmFundSecondDetail,Object> implements SlmFundSecondDetailService {

	/**
	 * 资金调拨查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmFundSecondDetail> sum){
		ResultModel rm=new ResultModel();
		SlmFundSecondDetail detail=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String startTime=sum.getStartTime(); 			// 交易时间查询
		String endTime=sum.getEndTime();
		PageModel<SlmFundSecondDetail> pm=new PageModel<SlmFundSecondDetail>(pageIndex, pageSize);
		try{
			String sWhere=" 1=1 ";
			if(startTime!=null&&!"".equals(startTime)){
				//				startTime+=" 00:00:00";
				sWhere+=" and to_char(trans_time, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
			}
			if(endTime!=null&&!"".equals(endTime)){
				//				endTime+=" 23:59:59";
				sWhere+=" and to_char(trans_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
			}
			String in_out=" and in_out_fund>0";	//查一级拨出 二级拨入 三级拨出
			if(detail.getFlag()==null||("1".equals(detail.getFlag())&&detail.getOther_account_no()!=null)||("0".equals(detail.getFlag())&&detail.getSecond_account_no()!=null)){
				in_out=" and in_out_fund<0";		//查一级拨入 二级拨出 三级拨入
			}
			sWhere+=in_out;
			detail.setIn_out_fund(null);
			List<SlmFundSecondDetail> list=this.getMapper(SlmFundSecondDetailMapper.class).findWithCondition(detail, sWhere, " TRANS_TIME desc", (pageIndex-1)*pageSize, pageSize);
			int count=this.getMapper(SlmFundSecondDetailMapper.class).countWithCondition(detail, sWhere);
			for(SlmFundSecondDetail details:list){
				if(details.getIn_out_fund()<0)		//负数
					details.setFlag("0");
				else
					details.setFlag("1");
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 新增（资金调拨）拨入
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddInWeb(SlmFundSecondDetail detail) 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{
			SlmFundSecondAccount s_account=this.getMapper(SlmFundSecondAccountMapper.class).findById(detail.getSecond_account_no());
			if(s_account==null){
				rm.setState("500");
				rm.setMsgInfo("未找到二级账户");
				return rm;
			}
			if("1".equals(s_account.getLock_flag())){
				rm.setState("500");
				rm.setMsgInfo("该账户已经结转，如须拨款请解锁");
				return rm;
			}
			String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(10);
			detail.setDetail_no(id);
			detail.setTrans_man_no(userId);
			detail.setTrans_man_name(userName);
			detail.setTrans_time(new Date());
			detail.setCarryover_flag("0");		//未结转
			double money=detail.getIn_out_fund();		//需调拨的金额，转入为+
			//与一级账户交易,从1级拨到2级
			if("1".equals(detail.getTrans_class())){
				SlmFundFirstAccount account=this.getMapper(SlmFundFirstAccountMapper.class).findById(detail.getOther_account_no());
				if(account!=null){
					if(money>0&&money>account.getFinal_fund()){
						rm.setState("500");
						rm.setMsgInfo("调拨金额超出客户账户的可调拨资金");
						return rm;
					}else{
						account.setFinal_fund(DoubleUtil.sub(account.getFinal_fund(),money));		//一级 可调拨金额-money
						account.setOut_fund(DoubleUtil.add(account.getOut_fund(),money));     		//一级 拨出金额+money
						s_account.setUse_fund(DoubleUtil.add(s_account.getUse_fund(),money)); 		//二级 可用金额+money
						s_account.setIn_fund(DoubleUtil.add(s_account.getIn_fund(),money));		//二级 拨进金额+money
						this.getMapper(SlmFundFirstAccountMapper.class).update(account);		//修改一级账户金额
						this.getMapper(SlmFundSecondAccountMapper.class).update(s_account);    //修改二级账户金额
					}
				}
			}else
				//与三级账户交易
				if("3".equals(detail.getTrans_class())){
					SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(detail.getOther_account_no());
					if(t_account!=null&&s_account!=null){
						if((money>0&&money>t_account.getUse_fund())){
							rm.setState("500");
							rm.setMsgInfo("调拨金额超出合同账户的可调拨资金");
							return rm;
						}else{
							t_account.setUse_fund(DoubleUtil.sub(t_account.getUse_fund(),money));		//三级 可用金额-money
							s_account.setUse_fund(DoubleUtil.add(s_account.getUse_fund(),money)); 		//二级 可用金额+money
							t_account.setOut_fund(DoubleUtil.add(t_account.getOut_fund(),money));     		//三级 拨出金额+money
							s_account.setIn_fund(DoubleUtil.add(s_account.getIn_fund(),money));		//二级 拨进金额+money
							this.getMapper(SlmFundThirdAccountMapper.class).update(t_account);		//修改三级账户金额
							this.getMapper(SlmFundSecondAccountMapper.class).update(s_account);    //修改二级账户金额
						}
					}
				}
			detail.setUse_fund(s_account.getUse_fund());      //可用金额设置为二级账号可用金额
			this.getMapper(SlmFundSecondDetailMapper.class).insert(detail);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}
	
	/**
	 * 新增（资金调拨）拨入全部 20230306刘侣
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddInWebAll(CommonPage<SlmFundSecondDetail> cp) throws Exception{
		ResultModel rm=new ResultModel("200", "调拨成功");
		List<SlmFundSecondDetail> sdL = cp.getObjectList();
		String allMoney = cp.getMemo1();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //操作时间
		try{
			
			for(SlmFundSecondDetail detail : sdL) {
				SlmFundSecondAccount s_account=this.getMapper(SlmFundSecondAccountMapper.class).findById(detail.getSecond_account_no());
				if(s_account==null){
					throw new Exception("未找到二级账户");				
				}
				if("1".equals(s_account.getLock_flag())){
					throw new Exception("该账户已经结转，如须拨款请解锁");
				
				}
				String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(10);
				detail.setDetail_no(id);
				detail.setTrans_man_no(userId);
				detail.setTrans_man_name(userName);
				detail.setTrans_time(new Date());
				detail.setCarryover_flag("0");		//未结转
				double money=detail.getIn_out_fund();		//需调拨的金额，转入为+
				//与一级账户交易,从1级拨到2级
				//与三级账户交易
				SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(detail.getOther_account_no());
				if(t_account!=null&&s_account!=null){
					money = t_account.getUse_fund();
					if((money>0&&money>t_account.getUse_fund())){
						throw new Exception("调拨金额超出合同账户的可调拨资金");
					}else{
						t_account.setUse_fund(DoubleUtil.sub(t_account.getUse_fund(),money));		//三级 可用金额-money
						s_account.setUse_fund(DoubleUtil.add(s_account.getUse_fund(),money)); 		//二级 可用金额+money
						t_account.setOut_fund(DoubleUtil.add(t_account.getOut_fund(),money));     		//三级 拨出金额+money
						s_account.setIn_fund(DoubleUtil.add(s_account.getIn_fund(),money));		//二级 拨进金额+money
						this.getMapper(SlmFundThirdAccountMapper.class).update(t_account);		//修改三级账户金额
						this.getMapper(SlmFundSecondAccountMapper.class).update(s_account);    //修改二级账户金额
					}
				}
				detail.setUse_fund(s_account.getUse_fund());      //可用金额设置为二级账号可用金额
				this.getMapper(SlmFundSecondDetailMapper.class).insert(detail);
			}
			
			MesOprLog mol = new MesOprLog("销售管理", "账户管理", "资金调拨", userName, opr_time, null, null, null, null, sdL.get(0).getCustomer_name() + " 调拨总金额为：" + allMoney);
			this.getMapper(MesOprLogMapper.class).insert(mol);
			rm.setState("200");
		}catch(Exception e){
			// 手动回滚：
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	/**
	 * 新增（资金调拨）拨出
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddOutWeb(SlmFundSecondDetail detail) 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{
			SlmFundSecondAccount s_account=this.getMapper(SlmFundSecondAccountMapper.class).findById(detail.getSecond_account_no());
			if("1".equals(s_account.getLock_flag())){
				rm.setState("500");
				rm.setMsgInfo("该账户已经结转，如须拨款请解锁");
				return rm;
			}
			String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(10);
			detail.setDetail_no(id);
			detail.setTrans_man_no(userId);
			detail.setTrans_man_name(userName);
			detail.setTrans_time(new Date());
			detail.setCarryover_flag("0");		//未结转
			double money=detail.getIn_out_fund();		//需调拨的金额，转出为-(存表时给予符号)
			//与一级账户交易
			if("1".equals(detail.getTrans_class())){
				SlmFundFirstAccount account=this.getMapper(SlmFundFirstAccountMapper.class).findById(detail.getOther_account_no());
				if(account!=null&&s_account!=null){
					if(money>s_account.getUse_fund()){
						rm.setState("500");
						rm.setMsgInfo("调拨金额超出产线账户的可调拨资金");
						return rm;
					}else{
						account.setFinal_fund(DoubleUtil.add(account.getFinal_fund(),money));		//一级 可调拨金额+money
						account.setIn_fund(DoubleUtil.add(account.getIn_fund(),money));     		//一级 拨进金额+money
						s_account.setUse_fund(DoubleUtil.sub(s_account.getUse_fund(),money)); 		//二级 可用金额-money
						s_account.setOut_fund(DoubleUtil.add(s_account.getOut_fund(),money));		//二级 拨出金额+money
						if(account.getFinal_fund()>account.getUse_fund())
							account.setFinal_fund(account.getUse_fund());
						this.getMapper(SlmFundFirstAccountMapper.class).update(account);		//修改一级账户金额
						this.getMapper(SlmFundSecondAccountMapper.class).update(s_account);    //修改二级账户金额
					}
				}else{
					rm.setState("500");
					rm.setMsgInfo("数据异常，一级账户不存在");
					return rm;
				}
			}else
				//与三级账户交易
				if("3".equals(detail.getTrans_class())){
					SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(detail.getOther_account_no());
					if(t_account!=null&&s_account!=null){
						if(money>s_account.getUse_fund()){
							rm.setState("500");
							rm.setMsgInfo("调拨金额超出产线账户的可调拨资金");
							return rm;
						}else{
							t_account.setUse_fund(DoubleUtil.add(t_account.getUse_fund(),money));		//三级 可用金额+money
							t_account.setIn_fund(DoubleUtil.add(t_account.getIn_fund(),money));     		//三级 拨入金额+money
							s_account.setUse_fund(DoubleUtil.sub(s_account.getUse_fund(),money)); 		//二级 可用金额-money
							s_account.setOut_fund(DoubleUtil.add(s_account.getOut_fund(),money));		//二级 拨出金额+money
							this.getMapper(SlmFundThirdAccountMapper.class).update(t_account);		//修改三级账户金额
							this.getMapper(SlmFundSecondAccountMapper.class).update(s_account);    //修改二级账户金额
						}
					}else{
						rm.setState("500");
						rm.setMsgInfo("数据异常，三级账户不存在");
						return rm;
					}
				}
			detail.setIn_out_fund(-money); 		//设置符号
			detail.setUse_fund(s_account.getUse_fund());      //可用金额设置为二级账号可用金额
			this.getMapper(SlmFundSecondDetailMapper.class).insert(detail);
			rm.setState("200");
		}catch(Exception e){
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			throw e;
		}
		return rm;
	}

	public ResultModel doAuto(SlmFundFirstAccount f_account,SlmFundThirdAccount account) throws Exception{
		ResultModel rm=new  ResultModel();
		double buku=Math.abs(account.getUse_fund());
		SlmFundSecondAccount s_account=this.getMapper(SlmFundSecondAccountMapper.class).findById(account.getSecond_account_no());
		if(s_account!=null&&f_account.getUse_fund()>buku&&f_account.getFinal_fund()>buku){
			//从一级到二级
			SlmFundSecondDetail inOut=new SlmFundSecondDetail();
			inOut.setSecond_account_no(s_account.getSecond_account_no());
			inOut.setSecond_account_name(s_account.getSecond_account_name());
			inOut.setOther_account_no(f_account.getFirst_account_no());
			inOut.setOther_account_name(f_account.getFirst_account_name());
			inOut.setBalance_object_no(f_account.getBalance_object_no());
			inOut.setBalance_object_name(f_account.getBalance_object_name());
			inOut.setCustomer_no(f_account.getCustomer_no());
			inOut.setCustomer_name(f_account.getCustomer_name());
			inOut.setIn_out_fund(buku);
			inOut.setTrans_class("1");		//一级到二级
			this.getBean(SlmFundSecondDetailServiceImpl.class).doAddInWeb(inOut);
			//二级到三级
			inOut.setOther_account_no(account.getThird_account_no());
			inOut.setOther_account_name(account.getThird_account_name());
			inOut.setIn_out_fund(buku);
			inOut.setTrans_class("3");		//二级到三级
			this.getBean(SlmFundSecondDetailServiceImpl.class).doAddOutWeb(inOut);
		}
		return rm;
	}
}