package org.springblade.payment.callback.trade;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.common.enums.AppConstant;
import org.springblade.ldt.agent.entity.AgentRecord;
import org.springblade.ldt.agent.service.IAgentRecordService;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.ldt.bills.service.IBillsService;
import org.springblade.ldt.user.entity.LoginUser;
import org.springblade.ldt.user.service.ILoginUserService;
import org.springblade.payment.entity.SuccessParams;
import org.springblade.payment.event.AgentChargeEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


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

	@Autowired
	IBillsService billsService;
	@Autowired
	ILoginUserService loginUserService;
	@Autowired
	IAgentRecordService agentRecordService;

	private final static String SUCCESS_STATUS = "success";


	@EventListener
	@Async
	@Transactional
	public void PaySuccess(AgentChargeEvent agentChargeEvent){
		SuccessParams successParams = agentChargeEvent.getSuccessParams();
		//获取订单信息
		Bills bills = billsService.getById(successParams.getBills().getId());
		Assert.notNull(bills, "支付记录中无此订单");
		bills.setChannelId(successParams.getThirdOrderId());

		//判断订单状态，已付款订单处理 （单笔支付可能接收多笔回调）
		if (Objects.equals(bills.getPayStatus(), AppConstant.BillPayStatus.付款成功.name())) {
			billsService.updateById(bills);
			return;
		}

		//回调返回订单成功处理
		String status = successParams.getStatus();
		if (Objects.equals(status, SUCCESS_STATUS)) {
			//支付成功
			bills.setPayStatus(AppConstant.BillPayStatus.付款成功.name());
			billsService.updateById(bills);
			//代理状态改为激活状态
			Long userId = bills.getPayId();
			//更新代理记录
			AgentRecord agentRecord = agentRecordService.getOne(new QueryWrapper<AgentRecord>().lambda().eq(AgentRecord::getAccountId, userId));
			agentRecord.setEnable(1);
			agentRecordService.updateById(agentRecord);
			//更新用户代标识
			LoginUser user = loginUserService.getById(userId);
			user.setUserType(AppConstant.USER_TYPE.渠道代理.name());
			loginUserService.updateById(user);
		}
	}
}
