package com.sys.service;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cab.dao.CabThirdPartyMapper;
import com.cab.model.CabThirdParty;
import com.cku.dao.CkuDvUserMapper;
import com.cku.dao.CkuMemberBalanMapper;
import com.cku.dao.CkuUserPayListMapper;
import com.cku.model.CkuDvUserModel;
import com.cku.model.CkuMemberBalance;
import com.cku.model.CkuUserPayList;

@Service("alipayService")
public class AlipayServiceImpl {

	@Autowired
	public CkuUserPayListMapper ckuUserPayListMapper;	
	@Autowired
	public CabThirdPartyMapper cabThirdPartyMapper;
	@Autowired
	public CkuDvUserMapper ckuDvUserMapper;
	@Autowired
	public CkuMemberBalanMapper ckuMemberBalanMapper;
	/**
	 * 更改余额
	 * @param userId
	 * @param money
	 * @return
	 */
	@Transactional
	public boolean rechargeBanlance(Long userId,String order ,String money){
		boolean result = false;
		String dvUserId = "-1";
		String ckuUserId = "-1";
		//根据cab用户id查询出第三方表中对应的CKU账号信息
		CabThirdParty cabThirdParty = cabThirdPartyMapper.selectByUserId(Integer.parseInt(userId.toString()));
		if(cabThirdParty != null){
			dvUserId = cabThirdParty.getCkuUserId();
		}
		//根据CKU账号id查询出CKU账号信息
		CkuDvUserModel ckuDvUserModel = ckuDvUserMapper.getckuMemberByUserId(dvUserId);
		if(ckuDvUserModel != null){
			ckuUserId = ckuDvUserModel.getCkuId();
		}
		//根据CKU会员号查询出对应用户的余额信息
		CkuMemberBalance ckuMemberBalance = ckuMemberBalanMapper.getCkuMemberBalance(ckuUserId);
		//根据CKU会员号查询出对应用户的余额信息
		CkuUserPayList ckuUserPayList = new CkuUserPayList();
		ckuUserPayList.setUserId(ckuUserId);
		ckuUserPayList.setMoneyType("0");
		ckuUserPayList.setMoneyDate(new Date());
		ckuUserPayList.setMoneyAmount(new BigDecimal(money));
		ckuUserPayList.setMoneyWay("1");
		ckuUserPayList.setRunningNumber(order);
		ckuUserPayList.setPayState("1");
		ckuUserPayList.setOutTradeNo(order);
		ckuUserPayList.setAlipayS("caib");
		ckuUserPayList.setAddTime(new Date());
		ckuUserPayList.setOperater(ckuUserId);
		ckuUserPayListMapper.insertSelective(ckuUserPayList);
		
		if(ckuMemberBalance!=null){
			String dbMoney = ckuMemberBalance.getMoneyAmount();
			BigDecimal bigDbMoney = new BigDecimal(dbMoney);
			BigDecimal lastMoney = bigDbMoney.add(new BigDecimal(money));
			if(ckuMemberBalanMapper.updateMemberBalance(lastMoney, ckuUserId)>0){
				result = true;
			};
		}
		
		return result;
	
	}
}
