package org.springblade.yeePay.listener;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.SystemConstant;
import org.springblade.common.utils.MoneyDesUtil;
import org.springblade.modules.guosen.bussiness.entity.BussinessBonusRecords;
import org.springblade.modules.guosen.bussiness.service.IBussinessBonusRecordsService;
import org.springblade.yeePay.event.BonusEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.math.BigDecimal;

@Component
@Slf4j
public class BonusNotifyListener {

	@Autowired
	private IBussinessBonusRecordsService bussinessBonusRecordsService;
	@Autowired
	private PlatformTransactionManager platformTransactionManager;
	@Autowired
	private TransactionDefinition transactionDefinition;
	/**
	 * 	分润回调业务逻辑处理
	 * @param  bonusEvent 回调事件
	 * */
	@EventListener
	public void notifyBonus(BonusEvent bonusEvent){
		//获取回调信息，解密后的数据
		JSONObject decryptData = bonusEvent.getDecryptData();
		String status = decryptData.getString("status");

		//通过订单id获取分润记录
		String requestNo = decryptData.getString("requestNo");
		String recordId = requestNo.split(":")[0];
		BussinessBonusRecords record = bussinessBonusRecordsService.getById(Long.valueOf(recordId));
		if (record == null) {
			log.info("=======================分润通知中找不到分润记录============================");
			return;
		}
		if (record.getBonusStatus() == SystemConstant.BussinessBonusStatus.SUCCESS.getValue() || record.getBonusStatus() == SystemConstant.BussinessBonusStatus.FAIL.getValue()
				|| record.getBonusStatus() == SystemConstant.BussinessBonusStatus.WATING.getValue()) {
			log.info("=======================分润通知中当前分润记录已分润完成或失败或处于待分润状态============================");
			return;
		} else {
			synchronized (record.getId().toString().intern()) {
				String freeze = MoneyDesUtil.decrypt(record.getFreeze(), MoneyDesUtil.KEY_FOR_UC);
				BigDecimal newFreeze = new BigDecimal(freeze);
				newFreeze = newFreeze.subtract(record.getPrice());
				record.setFreeze(MoneyDesUtil.encrypt(newFreeze.toString(), MoneyDesUtil.KEY_FOR_UC));
				record.setThirdPayLog(decryptData.toJSONString());
				record.setFailReason(decryptData.get("failReason") != null ? decryptData.get("failReason").toString() : null);
				if ("SUCCESS".equals(status)) {
					//修改分佣流水表的状态为成功
					record.setBonusStatus(SystemConstant.BussinessBonusStatus.SUCCESS.getValue());
						//开启事务
					TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
					//处理逻辑
					try {
						bussinessBonusRecordsService.updateById(record);
						//提交事务
						platformTransactionManager.commit(transaction);
					} catch (Exception e) {
						//回滚事务
						platformTransactionManager.rollback(transaction);
						e.printStackTrace();
						record.setStatus(SystemConstant.BussinessBonusStatus.ERROR.getValue());
						bussinessBonusRecordsService.updateById(record);
					}
				} else {//第三方支付回调结果为失败，记录分佣流水失败的原因
					record.setStatus(SystemConstant.BussinessDebitStatus.FAIL.getValue());
					bussinessBonusRecordsService.updateById(record);
				}
			}
		}
	}

}
