/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：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.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractPaymentMapper;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.ContractManagement.vo.SlmContractPayment;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundSettleBillLineMapper;
import market.Slm.FundManagement.mapper.SlmFundThirdAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundThirdAccountUsedMapper;
import market.Slm.FundManagement.service.SlmFundThirdAccountUsedService;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.FundManagement.vo.SlmFundSettleBill;
import market.Slm.FundManagement.vo.SlmFundSettleBillLine;
import market.Slm.FundManagement.vo.SlmFundThirdAccount;
import market.Slm.FundManagement.vo.SlmFundThirdAccountUsed;
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="SlmFundThirdAccountUsedService")
public class SlmFundThirdAccountUsedServiceImpl extends BaseServiceImpl<SlmFundThirdAccountUsed,Object> implements SlmFundThirdAccountUsedService {

	/**
	 * 新增-资金占用 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddWeb(SlmFundThirdAccountUsed used){
		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{
			//占用表新增
			String id=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+PbMethod.RandomCreate(6);
			used.setSeq(id);			
			used.setTrans_man_no(userId);
			used.setTrans_man_name(userName);
			used.setTrans_time(new Date());
			used.setFlag("0");
			//修改一级 和 三级账户表
			SlmFundFirstAccount account=this.getMapper(SlmFundFirstAccountMapper.class).findById(used.getFirst_account_no());
			SlmFundThirdAccount t_account=this.getMapper(SlmFundThirdAccountMapper.class).findById(used.getThird_account_no());
			if(account!=null&&t_account!=null){
				if("1".equals(account.getLock_flag())||"1".equals(t_account.getLock_flag())){
					rm.setState("500");
					rm.setMsgInfo("该账户已经结转，如须资金占用请解锁");
					return rm;
				}
				double money=used.getUsed_fund();		//占用资金
				if(money>t_account.getUse_fund()||money>account.getUse_fund()){
					account.setUse_fund(DoubleUtil.sub(account.getUse_fund(),money));		//一级 账期可用资金-money
					account.setUsed_fund(DoubleUtil.add(account.getUsed_fund(),money)); 		//一级  账期占用资金+money
					t_account.setUse_fund(DoubleUtil.sub(t_account.getUse_fund(),money)); 	//三级  可用资金-money
					t_account.setUsed_fund(DoubleUtil.add(t_account.getUsed_fund(),money)); 	//三级 占用资金+money
					this.getMapper(SlmFundThirdAccountMapper.class).update(t_account);
					this.getMapper(SlmFundFirstAccountMapper.class).update(account);
					if(t_account.getUse_fund()<0){
						this.getBean(SlmFundSecondDetailServiceImpl.class).doAuto(account,t_account);
					}
				}else{
					rm.setState("500");
					rm.setMsgInfo("占用金额超出账户可用金额");
					return rm;
				}
			}else{
				rm.setState("500");
				rm.setMsgInfo("数据丢失，请联系管理员修复");
				return rm;
			}
			this.getMapper(SlmFundThirdAccountUsedMapper.class).insert(used);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 资金占用查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmFundThirdAccountUsed> sum){
		ResultModel rm=new ResultModel();
		SlmFundThirdAccountUsed used=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String startTime=sum.getStartTime(); 			//trans_time查询
		String endTime=sum.getEndTime();
		PageModel<SlmFundThirdAccountUsed> pm=new PageModel<SlmFundThirdAccountUsed>(pageIndex, pageSize);
		try{
			String sWhere=" 1=1 ";
//			改--查询所有未结转的明细
			used.setCarryover_flag("0");
			// 本期占用应该是未结转，未释放的：已释放的查出来干嘛；20230222刘侣
			used.setFlag("0");
			// end
			
//			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+"'";
//			}
			
			List<SlmFundThirdAccountUsed> list=this.getMapper(SlmFundThirdAccountUsedMapper.class).findWithCondition(used, sWhere, " TRANS_TIME desc", (pageIndex-1)*pageSize, pageSize);
			int count=this.getMapper(SlmFundThirdAccountUsedMapper.class).countWithCondition(used, sWhere);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 三级账户资金占用查询
	 * 20230222刘侣
	 * */
	public ResultModel doQueryWebSanJi(CommonPage<SlmFundThirdAccountUsed> sum){
		ResultModel rm=new ResultModel();
		SlmFundThirdAccountUsed used=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String startTime=sum.getStartTime(); 			//trans_time查询
		String endTime=sum.getEndTime();
		PageModel<SlmFundThirdAccountUsed> pm=new PageModel<SlmFundThirdAccountUsed>(pageIndex, pageSize);
		try{
			String sWhere=" 1=1 ";
//			改--查询所有未结转的明细
			
			
			List<SlmFundThirdAccountUsed> list=this.getMapper(SlmFundThirdAccountUsedMapper.class).doQueryZYByCon(used.getThird_account_no());
//			int count=this.getMapper(SlmFundThirdAccountUsedMapper.class).countWithCondition(used, sWhere);
			pm.setRows(list);
//			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	
	/**
	 * 资金占用查询-历史
	 * */
	public ResultModel doQueryHistoryWeb(CommonPage<SlmFundThirdAccountUsed> sum){
		ResultModel rm=new ResultModel();
		SlmFundThirdAccountUsed used=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		PageModel<SlmFundThirdAccountUsed> pm=new PageModel<SlmFundThirdAccountUsed>(pageIndex, pageSize);
		try{
			List<SlmFundThirdAccountUsed> list=this.getMapper(SlmFundThirdAccountUsedMapper.class).doQueryHistory(used, (pageIndex-1)*pageSize, pageIndex*pageSize);
			int count=this.getMapper(SlmFundThirdAccountUsedMapper.class).doQueryHistoryCount(used);
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	public SlmFundThirdAccountUsed doAdd(SlmFundThirdAccount t_account, SlmContractPayment payment, SlmContractHeatInfo contract_heat){
		SlmFundThirdAccountUsed used=new SlmFundThirdAccountUsed();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		//占用表新增
		String id=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+PbMethod.RandomCreate(6);
		used.setSeq(id);		
		used.setFirst_account_no(t_account.getFirst_account_no());
		used.setFirst_account_name(t_account.getFirst_account_name());
		used.setSecond_account_no(t_account.getSecond_account_no());
		used.setSecond_account_name(t_account.getSecond_account_name());
		used.setThird_account_no(t_account.getThird_account_no());
		used.setThird_account_name(t_account.getThird_account_name());
		used.setBalance_object_no(t_account.getBalance_object_no());
		used.setBalance_object_name(t_account.getBalance_object_name());
		used.setCustomer_no(t_account.getCustomer_no());
		used.setCustomer_name(t_account.getCustomer_name());
		used.setContract_pk(contract_heat.getContract_pk());
		used.setContract_no(contract_heat.getContract_no());
		used.setPayment_point_no(payment.getPayment_point_no());
		used.setPayment_point_name(payment.getPayment_point_name());
		used.setPayment_ratio_type_no(payment.getPayment_ratio_type_no());
		used.setPayment_ratio_type_name(payment.getPayment_ratio_type_name());
		used.setTrans_man_no(userId);
		used.setTrans_man_name(userName);
		used.setTrans_time(new Date());
		used.setPayment_content(payment.getPayment_content());
		used.setFlag("0");
		if(used.getContract_no()==null||used.getContract_pk()==null){
			SlmContractHeatInfo heat=new SlmContractHeatInfo();
			heat.setContract_no(used.getThird_account_no());
			List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).find(heat,0,0);
			if(heat_list.size()>0){
				used.setContract_no(heat_list.get(0).getContract_no());
				used.setContract_pk(heat_list.get(0).getContract_pk());
			}
		}
		return used;
	}

	//释放掉所有的占用金额
	public ResultModel doReleaseFund(String contract_no,SlmContractLineInfo line,SlmOrderInfo order, SlmFundSettleBill bill){
		ResultModel rm=new ResultModel();
		rm.setState("200");
		try{
			if(contract_no==null){
				return rm;
			}
			SlmFundThirdAccount account=this.getMapper(SlmFundThirdAccountMapper.class).findById(contract_no);
			if(account!=null){
				SlmFundFirstAccount f_account=this.getMapper(SlmFundFirstAccountMapper.class).findById(account.getFirst_account_no());
				if(f_account!=null){
					//取消资金占用
					double used_money=0d;
					SlmContractPayment param_payment=new SlmContractPayment();
					param_payment.setCustomer_no(f_account.getCustomer_no());
					param_payment.setValid_flag("1");
					List<SlmContractPayment> payment_list=this.getMapper(SlmContractPaymentMapper.class).findWithCondition(param_payment, null, " payment_point_no desc", 0, 0);
					if(payment_list.size()>0){										
						List<SlmContractHeatInfo> heat_list=this.getMapper(SlmContractHeatInfoMapper.class).findWithCondition(null, " contract_no='"+contract_no+"'", null, 0, 0);
						if(heat_list.size()>0){
							//查询释放哪些提单 1.首先是要该结算单下的
							String sWhere=" 1=1 ";
							if(bill!=null){
								SlmFundSettleBillLine bill_line=new SlmFundSettleBillLine();
								bill_line.setSettle_bill_no(bill.getSettle_bill_no());
								List<SlmFundSettleBillLine> line_list=this.getMapper(SlmFundSettleBillLineMapper.class).find(bill_line,0,0);
								if(line_list.size()>0){
									sWhere+=" and bill_no in (";
									for(SlmFundSettleBillLine lines:line_list){
										sWhere+= "'"+lines.getBill_no()+"',";
									}
									sWhere=sWhere.substring(0,sWhere.length()-1);
									sWhere+=")";
								}
							}
							//2.其次合同号要匹配
							sWhere+=" and contract_no='"+contract_no+"'";
							SlmFundThirdAccountUsed used=new SlmFundThirdAccountUsed();	
							used=this.getBean(SlmFundThirdAccountUsedServiceImpl.class).doAdd(account,payment_list.get(0),heat_list.get(0));
							used.setFlag("1");
							//查询占用了多少金额
							SlmFundThirdAccountUsed param_used=new SlmFundThirdAccountUsed();
							param_used.setThird_account_no(account.getThird_account_no());
							param_used.setContract_no(contract_no);
							param_used.setFlag("0");
							if(line!=null){
								param_used.setContract_line_seq(line.getContract_line_seq());
							}
							if(order!=null){
								param_used.setContract_line_seq(order.getContract_line_seq());
								param_used.setOrder_seq(order.getOrder_seq());
								used.setContract_line_no(order.getContract_line_no());
								used.setContract_line_seq(order.getContract_line_seq());
								used.setOrder_seq(order.getOrder_seq());
							}
							//查询出占用明细，进行释放
							List<SlmFundThirdAccountUsed> used_list=this.getMapper(SlmFundThirdAccountUsedMapper.class).findWithCondition(param_used,sWhere,null, 0, 0);
							for(SlmFundThirdAccountUsed useds:used_list){
								//原明细标记为已释放
								used_money=DoubleUtil.add(used_money, useds.getUsed_fund());				//记录总释放金额
								useds.setFlag("1");
								this.getMapper(SlmFundThirdAccountUsedMapper.class).update(useds);
								//新增-金额的占用明细
								double add_used_money=-useds.getUsed_fund();
								if(Math.abs(add_used_money)>0){
									String used_id=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+PbMethod.RandomCreate(6);
									used.setUsed_fund(add_used_money);
									used.setSeq(used_id);
									this.getMapper(SlmFundThirdAccountUsedMapper.class).insert(used);
								}
							}	
						}
						if(Math.abs(used_money)>0){
							used_money=-used_money;
							//账户金额修改
							f_account.setUse_fund(DoubleUtil.sub(f_account.getUse_fund(),used_money));		//一级 账期可用资金-money
							//======================eason edit 2019-06-28 注释下面这行代码=========================
							//f_account.setFinal_fund(DoubleUtil.sub(f_account.getFinal_fund(),used_money));		//一级 账期可拨资金-money
							//=====================================================================================
							f_account.setUsed_fund(DoubleUtil.add(f_account.getUsed_fund(),used_money)); 		//一级  账期占用资金+money
							account.setUse_fund(DoubleUtil.sub(account.getUse_fund(),used_money)); 	//三级  可用资金-money
							account.setUsed_fund(DoubleUtil.add(account.getUsed_fund(),used_money)); 	//三级 占用资金+money
							if(f_account.getFinal_fund()>f_account.getUse_fund())	f_account.setFinal_fund(f_account.getUse_fund());
							this.getMapper(SlmFundThirdAccountMapper.class).update(account);
							this.getMapper(SlmFundFirstAccountMapper.class).update(f_account);
							if(account.getUse_fund()<0){
								this.getBean(SlmFundSecondDetailServiceImpl.class).doAuto(f_account,account);
							}
						}
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
}