package org.springblade.payment.callback.trade;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.common.enums.AppConstant;
import org.springblade.common.enums.OrderType;
import org.springblade.ldt.agent.entity.AgentLeagueRecord;
import org.springblade.ldt.agent.entity.AgentRecord;
import org.springblade.ldt.agent.service.IAgentLeagueRecordService;
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;
	@Autowired
	IAgentLeagueRecordService agentLeagueRecordService;

	private final static String SUCCESS_STATUS = "success";


	@EventListener
	@Async
	@Transactional
	public void PaySuccess(AgentChargeEvent agentChargeEvent) {
		SuccessParams successParams = agentChargeEvent.getSuccessParams();

		//回调返回订单成功处理
		String status = successParams.getStatus();
		if (Objects.equals(status, SUCCESS_STATUS)) {
			//代理状态改为激活状态
			Long userId;
			if (Objects.equals(successParams.getOrderType(), OrderType.AGENT_CHARGE.name())) {
				userId = handleAgentData(successParams);
			} else {
				userId = handleBills(successParams);
			}
			if (ObjectUtil.isNotEmpty(userId)) {
				//更新代理记录
				AgentRecord agentRecord = agentRecordService.getOne(Wrappers.<AgentRecord>lambdaQuery().eq(AgentRecord::getAccountId, userId));
				agentRecord.setEnable(1);
				agentRecordService.updateById(agentRecord);
				//更新用户代标识
				LoginUser user = loginUserService.getById(userId);
				user.setUserType(agentRecord.getAgentType());
				loginUserService.updateById(user);
			}
		}
	}

	/**
	 * 处理代理数据
	 *
	 * @param successParams
	 */
	private Long handleAgentData(SuccessParams successParams) {
		AgentLeagueRecord agentLeagueRecord = agentLeagueRecordService.getById(successParams.getAgentLeagueRecord().getId());
		Assert.notNull(agentLeagueRecord, "加盟费缴费记录中无此订单");
		//判断订单状态，已付款订单处理 （单笔支付可能接收多笔回调）
		if (Objects.equals(agentLeagueRecord.getPayStatus(), AppConstant.BillPayStatus.付款成功.name())) {
			return null;
		}
		//支付成功
		agentLeagueRecord.setPayStatus(AppConstant.BillPayStatus.付款成功.name());
		agentLeagueRecordService.updateById(agentLeagueRecord);
		return agentLeagueRecord.getUserId();
	}

	/**
	 * 处理账单数据
	 *
	 * @param successParams
	 */
	private Long handleBills(SuccessParams successParams) {
		//获取订单信息
		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 null;
		}

		//支付成功
		bills.setPayStatus(AppConstant.BillPayStatus.付款成功.name());
		billsService.updateById(bills);
		return bills.getPayId();
	}
}
