/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：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.FundManagement.mapper.SlmFundFirstAccountHisMapper;
import market.Slm.FundManagement.mapper.SlmFundFirstAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundSecondAccountMapper;
import market.Slm.FundManagement.mapper.SlmFundThirdAccountMapper;
import market.Slm.FundManagement.service.SlmFundFirstAccountService;
import market.Slm.FundManagement.vo.SlmFundFirstAccount;
import market.Slm.FundManagement.vo.SlmFundFirstAccountHis;
import market.Slm.FundManagement.vo.SlmFundSecondAccount;
import market.Slm.FundManagement.vo.SlmFundThirdAccount;

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="SlmFundFirstAccountService")
public class SlmFundFirstAccountServiceImpl extends BaseServiceImpl<SlmFundFirstAccount,Object> implements SlmFundFirstAccountService {

	/**
	 * 一级(客户)账户查询
	 * */
	public ResultModel doQueryWeb(CommonPage<SlmFundFirstAccount> sum){
		ResultModel rm=new ResultModel();
		SlmFundFirstAccount account=sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		String startTime=sum.getStartTime();
		String endTime=sum.getEndTime();
		PageModel<SlmFundFirstAccount> pm=new PageModel<SlmFundFirstAccount>(pageIndex, pageSize);
		try{
			String sWhere=" 1=1 ";
			if(startTime!=null&&!"".equals(startTime)){
				//				startTime+=" 00:00:00";
				sWhere+=" and to_char(init_fund_time, 'yyyy-mm-dd hh24:mi:ss') >='"+startTime+"'";
			}
			if(endTime!=null&&!"".equals(endTime)){
				//				endTime+=" 23:59:59";
				sWhere+=" and to_char(init_fund_time, 'yyyy-mm-dd hh24:mi:ss') <= '"+endTime+"'";
			}
			List<SlmFundFirstAccount> list=this.getMapper(SlmFundFirstAccountMapper.class).findWithCondition(account, sWhere, " is_closure,first_account_name", (pageIndex-1)*pageSize, pageSize);
			int count=this.getMapper(SlmFundFirstAccountMapper.class).countWithCondition(account, sWhere);
			Double all_in_fund=0d;
			Double all_out_fund=0d;
			Double all_settlement_fund=0d;
			Double all_used_fund=0d;
			Double all_pay_back_fund=0d;
			for(SlmFundFirstAccount accounts:list){
				all_in_fund+=accounts.getIn_fund()==null?0:accounts.getIn_fund();
				all_out_fund+=accounts.getOut_fund()==null?0:accounts.getOut_fund();
				all_settlement_fund+=accounts.getSettlement_fund()==null?0:accounts.getSettlement_fund();
				all_used_fund+=accounts.getUsed_fund()==null?0:accounts.getUsed_fund();
				all_pay_back_fund+=accounts.getPay_back_fund()==null?0:accounts.getPay_back_fund();
				if(doJudge(accounts)) accounts.setHave_second_account("0");
				else accounts.setHave_second_account("1"); 		//有二级账号
			}
			if(list.size()>0){
				list.get(0).setAll_in_fund(DoubleUtil.round(all_in_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_out_fund(DoubleUtil.round(all_out_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_settlement_fund(DoubleUtil.round(all_settlement_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_used_fund(DoubleUtil.round(all_used_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_pay_back_fund(DoubleUtil.round(all_pay_back_fund,DoubleUtil.SCALE_PRICE));
			}
			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 doAddWeb(SlmFundFirstAccount account){
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String deptId=(String) this.getSession().getAttribute(HomeService.SESSION_DEPT_ID);
		String deptName=(String) this.getSession().getAttribute(HomeService.SESSION_DEPT_NAME);
		try{
			//验证重复
			if(!doCheckWeb(account)){
				rm.setState("500");
				rm.setMsgInfo("该客户账户已存在");
				return rm;
			}
			String id=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+PbMethod.RandomCreate(10);
			if(account.getFirst_account_no()==null||"".equals(account.getFirst_account_no())) 
				account.setFirst_account_no(id);
			if(account.getInit_fund_time()==null)
				account.setInit_fund_time(new Date()); 		//期初时间
			account.setFinal_fund(account.getInit_fund()); 			//可调拨金额=期初
			account.setUse_fund(account.getInit_fund()); 			//账期可用金额=期初
			account.setBalance_fund(account.getInit_fund()); 		//账期财务余额=期初
			account.setInit_balance_fund(0d);
			account.setInit_used_fund(0d);
			account.setCreate_man_no(userId);
			account.setCreate_man_name(userName);
			account.setCreate_dept_no(deptId);
			account.setCreate_dept_name(deptName);
			account.setCreate_time(new Date());
			account.setIs_closure("0");  //不封存
			account.setLock_flag("0");
			this.getMapper(SlmFundFirstAccountMapper.class).insert(account);
			rm.setState("200");
			rm.setData(id);
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 一级(客户)账户修改
	 * */
	public ResultModel doUpdateWeb(SlmFundFirstAccount account){
		ResultModel rm=new ResultModel();
		try{
			if(!doJudge(account)){
				rm.setState("500");
				rm.setMsgInfo("请先将该客户账户下的产线账户删除");
				return rm;
			}
			SlmFundFirstAccount check=this.getMapper(SlmFundFirstAccountMapper.class).findById(account.getFirst_account_no());
			if(check!=null){
				Double total=check.getIn_fund()+check.getOut_fund()+check.getSettlement_fund()+check.getUsed_fund()+check.getPay_back_fund();
				if("1".equals(check.getLock_flag())){
					rm.setState("500");
					rm.setMsgInfo("该客户账户已经结转，如须修改请解锁");
					return rm;
				}
				if(total>0){
					rm.setState("500");
					rm.setMsgInfo("该客户账户已发生资金变动，无法修改");
					return rm;
				}
				if(check.getInit_fund()!=account.getInit_fund()){		//修改了期初金额
					account.setFinal_fund(account.getInit_fund()); 			//可调拨金额=期初
					account.setUse_fund(account.getInit_fund()); 			//账期可用金额=期初
					account.setBalance_fund(account.getInit_fund()); 		//账期财务余额=期初
				}
				this.getMapper(SlmFundFirstAccountMapper.class).update(account);
				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("该账户不存在");
				return rm;
			}
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 一级(客户)账户删除
	 * */
	public ResultModel doDeleteWeb(SlmFundFirstAccount account){
		ResultModel rm=new ResultModel();
		try{
			if(!doJudge(account)){
				rm.setState("500");
				rm.setMsgInfo("请先将该客户账户下的产线账户删除");
				return rm;
			}
			SlmFundFirstAccount check=this.getMapper(SlmFundFirstAccountMapper.class).findById(account.getFirst_account_no());
			if(check!=null){
				Double total=check.getIn_fund()+check.getOut_fund()+check.getSettlement_fund()+check.getUsed_fund()+check.getPay_back_fund();
				if("1".equals(check.getLock_flag())){
					rm.setState("500");
					rm.setMsgInfo("该客户账户已经结转，如须修改请解锁");
					return rm;
				}
				if(total>0){
					rm.setState("500");
					rm.setMsgInfo("该客户账户已发生资金变动，无法修改");
					return rm;
				}
				this.getMapper(SlmFundFirstAccountMapper.class).delete(account.getFirst_account_no());
				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("该账户不存在");
				return rm;
			}
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 账户弃用，封存
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doClosureWeb(SlmFundFirstAccount account) throws Exception{
		ResultModel rm=new ResultModel();
		try{
			account=this.getMapper(SlmFundFirstAccountMapper.class).findById(account.getFirst_account_no());
			if(account==null){
				rm.setState("500");
				rm.setMsgInfo("账户数据丢失，请联系管理员");
				return rm;
			}
			account.setIs_closure("1"); 		//封存
			this.getMapper(SlmFundFirstAccountMapper.class).update(account);
			//二级账户封存
			List<SlmFundSecondAccount> s_account_list=this.getMapper(SlmFundSecondAccountMapper.class).findWithCondition(null, " first_account_no='"+account.getFirst_account_no()+"'", null, 0, 0);
			for(SlmFundSecondAccount s_account:s_account_list){
				s_account.setIs_closure("1");
				this.getMapper(SlmFundSecondAccountMapper.class).update(s_account);
			}
			//三级账户封存
			List<SlmFundThirdAccount> t_account_list=this.getMapper(SlmFundThirdAccountMapper.class).findWithCondition(null, " first_account_no='"+account.getFirst_account_no()+"'", null, 0, 0);
			for(SlmFundThirdAccount t_account:t_account_list){
				t_account.setIs_closure("1");
				this.getMapper(SlmFundThirdAccountMapper.class).update(t_account);
			}
			
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}
	
	/**
	 * 账户解封
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUnClosureWeb(SlmFundFirstAccount account) throws Exception{
		ResultModel rm=new ResultModel();
		try{
			account=this.getMapper(SlmFundFirstAccountMapper.class).findById(account.getFirst_account_no());
			if(account==null){
				rm.setState("500");
				rm.setMsgInfo("账户数据丢失，请联系管理员");
				return rm;
			}
			account.setIs_closure("0"); 		//解封
			this.getMapper(SlmFundFirstAccountMapper.class).update(account);
			//二级账户解封
			List<SlmFundSecondAccount> s_account_list=this.getMapper(SlmFundSecondAccountMapper.class).findWithCondition(null, " first_account_no='"+account.getFirst_account_no()+"'", null, 0, 0);
			for(SlmFundSecondAccount s_account:s_account_list){
				s_account.setIs_closure("0");
				this.getMapper(SlmFundSecondAccountMapper.class).update(s_account);
			}
			//三级账户解封
			List<SlmFundThirdAccount> t_account_list=this.getMapper(SlmFundThirdAccountMapper.class).findWithCondition(null, " first_account_no='"+account.getFirst_account_no()+"'", null, 0, 0);
			for(SlmFundThirdAccount t_account:t_account_list){
				t_account.setIs_closure("0");
				this.getMapper(SlmFundThirdAccountMapper.class).update(t_account);
			}
			
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 检验是否重复
	 * 结算主体编号balance_object_no ,客户编号 customer_no
	 * */
	public boolean doCheckWeb(SlmFundFirstAccount account){
		SlmFundFirstAccount param=new SlmFundFirstAccount();
		param.setBalance_object_no(account.getBalance_object_no());
		param.setCustomer_no(account.getCustomer_no());
		int count=this.getMapper(SlmFundFirstAccountMapper.class).count(param);
		if(count>0){
			return false;
		}
		return true;
	}

	//检查是否拥有二级账户，有则不可修改 删除
	private boolean doJudge(SlmFundFirstAccount account){
		SlmFundSecondAccount second=new SlmFundSecondAccount();
		second.setFirst_account_no(account.getFirst_account_no());
		int count=this.getMapper(SlmFundSecondAccountMapper.class).count(second);
		if(count>0){
			return false;
		}
		return true;
	}
	
	//=======================APP eason add 2019-07-15===================
	/**
	 * 一级(客户)账户查询
	 * */
	public ResultModel doQueryApp(CommonPage<SlmFundFirstAccount> sum){
		ResultModel rm=new ResultModel();
		SlmFundFirstAccount account=sum.getObject()==null?new SlmFundFirstAccount():sum.getObject();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		account.setCustomer_no((String)this.getSession().getAttribute(HomeService.SESSION_DEPT_ID));
		PageModel<SlmFundFirstAccount> pm=new PageModel<SlmFundFirstAccount>(pageIndex, pageSize);
		try{
			String sWhere=" 1=1 ";
			List<SlmFundFirstAccount> list=this.getMapper(SlmFundFirstAccountMapper.class).findWithCondition(account, sWhere, " is_closure,first_account_name", (pageIndex-1)*pageSize, pageSize);
			int count=this.getMapper(SlmFundFirstAccountMapper.class).countWithCondition(account, sWhere);
			Double all_in_fund=0d;
			Double all_out_fund=0d;
			Double all_settlement_fund=0d;
			Double all_used_fund=0d;
			Double all_pay_back_fund=0d;
			//实际上此处只会有一个账户，所以没用关联查询
			for(SlmFundFirstAccount accounts:list){
				SlmFundFirstAccountHis fah=new SlmFundFirstAccountHis();
				fah.setFirst_account_no(accounts.getFirst_account_no());
				List<SlmFundFirstAccountHis> lh=this.getMapper(SlmFundFirstAccountHisMapper.class).findWithCondition(fah, "", "carryover_time desc", 0, 1);
				if(lh!=null&&lh.size()>0){
					accounts.setCarryover_time(lh.get(0).getCarryover_time());
				}
				all_in_fund+=accounts.getIn_fund()==null?0:accounts.getIn_fund();
				all_out_fund+=accounts.getOut_fund()==null?0:accounts.getOut_fund();
				all_settlement_fund+=accounts.getSettlement_fund()==null?0:accounts.getSettlement_fund();
				all_used_fund+=accounts.getUsed_fund()==null?0:accounts.getUsed_fund();
				all_pay_back_fund+=accounts.getPay_back_fund()==null?0:accounts.getPay_back_fund();
				if(doJudge(accounts)) accounts.setHave_second_account("0");
				else accounts.setHave_second_account("1"); 		//有二级账号
			}
			if(list.size()>0){
				list.get(0).setAll_in_fund(DoubleUtil.round(all_in_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_out_fund(DoubleUtil.round(all_out_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_settlement_fund(DoubleUtil.round(all_settlement_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_used_fund(DoubleUtil.round(all_used_fund,DoubleUtil.SCALE_PRICE));
				list.get(0).setAll_pay_back_fund(DoubleUtil.round(all_pay_back_fund,DoubleUtil.SCALE_PRICE));
			}
			pm.setRows(list);
			pm.setTotal(count);
			rm.setData(pm);
			rm.setState("200");
		}catch(Exception e){
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
}