package org.springblade.modules.payment.listener;

import cn.hutool.core.lang.Assert;
import org.springblade.common.constant.SystemConstant;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.ldt.agenter.entity.Agenter;
import org.springblade.modules.ldt.agenter.service.IAgenterService;
import org.springblade.modules.ldt.billrecord.entity.BillRecord;
import org.springblade.modules.ldt.billrecord.service.IBillRecordService;
import org.springblade.modules.payment.entity.SuccessParams;
import org.springblade.modules.payment.event.AgentChargeEvent;
import org.springblade.modules.payment.event.UserPayEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author: lianghanqiang
 * @description: 代理付款回调
 * @since: 8/5/21 -- 3:01 PM
 */
@Component
public class AgentChargeListener {

	@Resource
	private IBillRecordService billRecordService;
	@Resource
	private IAgenterService agenterService;

	private final static String SUCCESS_STATUS = "success";


	@EventListener
	@Async
	public void PaySuccess(AgentChargeEvent agentChargeEvent){
		SuccessParams successParams = agentChargeEvent.getSuccessParams();
		//获取订单信息
		BillRecord billRecord = billRecordService.getById(successParams.getBillId());
		Assert.notNull(billRecord, "支付记录中无此订单");
		billRecord.setPlatformId(successParams.getPlatformId());
		System.out.println("successParams"+successParams);
		//已付款状态，只存平台订单id
		if (Objects.equals(billRecord.getPayStatus(), SystemConstant.BillRecordPayStatus.PAYED.getValue())) {
			System.out.println("1");
			//有可能是前端状态传错，把平台订单id存起来
			billRecordService.updateById(billRecord);
			return;
		}
		String status = successParams.getStatus();
		if (Objects.equals(status, SUCCESS_STATUS)) {
			System.out.println("2");
			//支付成功
			billRecord.setPayStatus(SystemConstant.BillRecordPayStatus.PAYED.getValue());
			billRecordService.updateById(billRecord);
			//代理状态改为激活状态
			Long userId = billRecord.getUserId();
			Agenter agenter = agenterService.getOne(Condition.getQueryWrapper(new Agenter()).lambda().eq(Agenter::getUserId, userId));
			Assert.notNull(agenter, billRecord.getId()+"未找到代理信息");
			agenter.setEnabled(SystemConstant.AgentEnable.IS_ENABLE.getValue());
			agenterService.updateById(agenter);
		}
		System.out.println("3");


	}
}
