package org.springblade.yeePay.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.common.constant.SystemConstant;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.guosen.ads.entity.Ads;
import org.springblade.modules.guosen.bussiness.entity.BussinessBonusRecords;
import org.springblade.modules.guosen.bussiness.service.IBussinessBonusRecordsService;
import org.springblade.modules.guosen.hotDetail.entity.HotDetail;
import org.springblade.modules.guosen.hotDetail.service.IHotDetailService;
import org.springblade.modules.guosen.loginUser.entity.LoginUser;
import org.springblade.modules.guosen.loginUser.service.ILoginUserService;
import org.springblade.modules.guosen.userActivityStatistical.entity.UserActivityStatistical;
import org.springblade.modules.guosen.userActivityStatistical.service.IUserActivityStatisticalService;
import org.springblade.modules.guosen.withdrawRecords.entity.WithdrawRecords;
import org.springblade.modules.guosen.withdrawRecords.service.IWithdrawRecordsService;
import org.springblade.yeePay.event.TransferEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Component
public class TransferNotifyListener {

	@Resource
	private IWithdrawRecordsService withdrawRecordsService;
	@Resource
	private ILoginUserService loginUserService;
	@Resource
	private IUserActivityStatisticalService userActivityStatisticalService;
	@Resource
	private StringRedisTemplate stringRedisTemplate;
	@Resource
	private IHotDetailService hotDetailService;
	@Resource
	private IBussinessBonusRecordsService bussinessBonusRecordsService;
	@Resource
	private BladeLogger bladeLogger;
	/**
	 * 	转账回调业务逻辑处理
	 * @param  transferEvent 回调事件
	 * */
	@EventListener
	@Async
	public void notifyBusiness(TransferEvent transferEvent){
		//获取回调信息，解密后的数据
		JSONObject decryptData = transferEvent.getDecryptData();
		String status = decryptData.getString("status");

		//通过订单id获取提现记录
		String requestNo = decryptData.getString("requestNo");
		WithdrawRecords withdrawRecords = withdrawRecordsService.getOne(Condition.getQueryWrapper(new WithdrawRecords()).lambda()
			.eq(WithdrawRecords::getRequestNo, requestNo));
		Assert.notNull(withdrawRecords, "提现记录为空");

		if (withdrawRecords.getWithdrawStatus() == 1) {
			//系统有可能回调很多次，要判断是否处理过
			return;
		}
		withdrawRecords.setBankCode(decryptData.getString("bankCode"));
		withdrawRecords.setFinishTime(decryptData.getString("finishTime"));
		withdrawRecords.setOrderNo(decryptData.getString("orderNo"));
		withdrawRecords.setFee(decryptData.getString("fee"));
		withdrawRecords.setDebitAmount(decryptData.getString("debitAmount"));
		withdrawRecords.setReceiverAccountName(decryptData.getString("receiverAccountName"));
		withdrawRecords.setReceiveAmount(decryptData.getString("receiveAmount"));
		withdrawRecords.setOrderTime(decryptData.getString("orderTime"));
		withdrawRecords.setFeeUndertakerMerchantNo(decryptData.getString("feeUndertakerMerchantNo"));
		withdrawRecords.setMerchantNo(decryptData.getString("merchantNo"));
		withdrawRecords.setYeeStatus(status);

		if (Objects.equals(status, "SUCCESS")) {
			if(SystemConstant.WithdrawRecordType.ADS_BONUS.getValue() == withdrawRecords.getType()){//采购商红利分润
				BussinessBonusRecords bussinessBonusRecords = bussinessBonusRecordsService.getBaseMapper().selectOne(new QueryWrapper<>(new BussinessBonusRecords())
					.lambda().eq(BussinessBonusRecords::getWithdrawId, withdrawRecords.getId()));
				bussinessBonusRecords.setBonusStatus(SystemConstant.BussinessBonusStatus.SUCCESS.getValue());
				bussinessBonusRecordsService.updateById(bussinessBonusRecords);
				withdrawRecordsService.updateById(withdrawRecords);
				return;
			}
			/**
			 * 用户提现
			 */
			Long userId = withdrawRecords.getUserId();
			//加进缓存里
			this.putIntRedis(userId);
			//已发款
			withdrawRecords.setWithdrawStatus(1);
			//更新用户的可用热力
			BigDecimal hotValue = withdrawRecords.getHotValue();//消耗的热力值
			LoginUser loginUser = loginUserService.getById(userId);
			Assert.notNull(loginUser, "用户信息为空");
			loginUser.setUsableHot(loginUser.getUsableHot().subtract(hotValue));
			loginUserService.updateById(loginUser);
			//插入热力明细表
			HotDetail hotDetail = new HotDetail();
			hotDetail.setNote("奖金提现");
			hotDetail.setType(3);
			hotDetail.setRelationId(withdrawRecords.getId());
			hotDetail.setUserId(userId);
			hotDetail.setHotValue(hotValue.negate());
			hotDetailService.save(hotDetail);
			//更新用户统计数据
			String affair = withdrawRecords.getUpdateAffair();
			List<UserActivityStatistical> statisticals = JSONObject.parseArray(affair, UserActivityStatistical.class);
			Assert.notNull(statisticals, "操作的记录为空");
			userActivityStatisticalService.updateBatchById(statisticals);
		}else{
			withdrawRecords.setWithdrawStatus(2);//提现失败
			withdrawRecords.setFailReason(decryptData.getString("failReason"));//提现失败的原因
		}
		//更新提现记录数据
		withdrawRecordsService.updateById(withdrawRecords);
//decryptData 解密后的数据为
//		{
//			"bankCode":"ICBC",
//			"finishTime":"2021-07-08 17:49:30.503",
//			"orderNo":"202107081749298c97badd",
//			"fee":"1.00",
//			"debitAmount":"1.01",
//			"requestNo":"123455698899898992",
//			"receiverAccountName":"方权",
//			"receiveAmount":"0.01",
//			"orderAmount":"0.01",
//			"orderTime":"2021-07-08 17:49:29.763",
//			"feeUndertakerMerchantNo":"10086062555",
//			"receiverAccountNo":"6212263602077061919",
//			"receiveType":"REAL_TIME",
//			"status":"SUCCESS",
//			"merchantNo":"10086062555"
//		}
//		{
//			"bankCode":"CMBCHINA",
//			"finishTpime":"2021-07-08 22:39:39.291",
//			"orderNo":"2021070822393835e3b1f4",
//			"fee":"1.00",
//			"debitAmount":"1.10",
//			"requestNo":"d819c23837414616bbe9340f7fac7673",
//			"receiverAccountName":"田炳生",
//			"receiveAmount":"0.10",
//			"orderAmount":"0.10",
//			"orderTime":"2021-07-08 22:39:38.459",
//			"feeUndertakerMerchantNo":"10086062555",
//			"receiverAccountNo":"6214832057600516",
//			"failReason":"银行无此账户信息",
//			"receiveType":"REAL_TIME",
//			"status":"FAIL",
//			"merchantNo":"10086062555"
//		}

	}

	private void putIntRedis(Long userId) {
		//提现成功，将提现次数加入缓存
		String strWithDrawTime = stringRedisTemplate.boundValueOps(SystemConstant.WITHDRAW_KEY + userId).get();
		int num = 1;
		if (StringUtil.isNotBlank(strWithDrawTime)) {
			num = Integer.valueOf(strWithDrawTime) + 1;
		}
		stringRedisTemplate.boundValueOps(SystemConstant.WITHDRAW_KEY + userId).set(String.valueOf(num));
	}


}
