package org.springblade.payment.listener;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Asserts;
import org.springblade.common.constant.BillsConstant;
import org.springblade.gateway.common_gateway.entity.vo.BillSuccessEvent;
import org.springblade.ldt.agent.entity.Agent;
import org.springblade.ldt.agent.entity.AgentBills;
import org.springblade.ldt.agent.entity.AgentRecord;
import org.springblade.ldt.agent.service.IAgentBillsService;
import org.springblade.ldt.agent.service.IAgentRecordService;
import org.springblade.ldt.agent.service.IAgentService;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.ldt.bills.entity.PlatformBills;
import org.springblade.ldt.bills.service.IPlatformBillsService;
import org.springblade.ldt.shop.entity.Shop;
import org.springblade.ldt.shop.service.IShopService;
import org.springblade.ldt.user.entity.LoginUser;
import org.springblade.ldt.user.service.ILoginUserService;
import org.springblade.payment.entity.SuccessParams;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * @author: lianghanqiang
 * @description: 根据订单信息，处理响应代理关系以及代理费
 * @since: 8/31/21 -- 9:49 AM
 */
@Component
@AllArgsConstructor
@Slf4j
public class AgentFeeHandle {
	private IAgentBillsService iAgentBillsService;
	private IPlatformBillsService iPlatformBillsService;
	private IShopService iShopService;
	private ILoginUserService loginUserService;
	private IAgentRecordService agentRecordService;
	private IAgentService agentService;

	@EventListener
	@Async
	public void addAgentFee(BillSuccessEvent billSuccessEvent) {
		//获取付款流水号数据
		SuccessParams successParams = billSuccessEvent.getSuccessParams();
		Bills bills = successParams.getBills();

		//总的手续费
		BigDecimal totalFee = Optional.ofNullable(bills.getFee()).orElse(BigDecimal.ZERO).add(bills.getPointFee());
		if (totalFee.compareTo(BigDecimal.ZERO) == 0) {
			//总手续费等于0不插入收益流水
			return;
		}
		//查询是否有城市代理商
		Long receiveId = bills.getReceiveId();

		//获取商家信息
		Shop shop = iShopService.getById(receiveId);

		//设置平台收益对象
		PlatformBills platformBills = new PlatformBills();
		platformBills.setPayment(bills.getId());
		platformBills.setPayer(bills.getPayId());
		platformBills.setReceiver(bills.getReceiveId());
		platformBills.setType(bills.getType());
		platformBills.setPrice(bills.getPrice());
		platformBills.setTenantId(successParams.getTenantId());

		//当前创建时间
		DateTime now = DateTime.now();
		platformBills.setCreateTime(now);

		//判断是否有渠道合作伙伴
		Long agenter = shop.getAgenter();
		LoginUser loginUser = loginUserService.getById(agenter);

		if (loginUser != null) {
			//获取代理人的信息
			//创建代理人费用
			AgentBills agentBills = new AgentBills();
			agentBills.setAgenter(agenter);
			agentBills.setPayment(bills.getId());
			agentBills.setPayer(bills.getPayId());
			agentBills.setReceiver(bills.getReceiveId());
			agentBills.setType(bills.getType());
			agentBills.setPrice(bills.getPrice());
			agentBills.setTenantId(successParams.getTenantId());
			agentBills.setCreateTime(now);

			AgentRecord agentRecord = agentRecordService.getOne(Wrappers.<AgentRecord>lambdaQuery().eq(AgentRecord::getUserId, agenter));
			Asserts.notNull(agentRecord, "该用户未找到代理记录！");
			Agent agent = agentService.getById(agentRecord.getAgentId());
			Asserts.notNull(agent, "未找到该代理等级！");

			//计算代理人和平台收益费用各占50%
			BigDecimal fee = totalFee.multiply(new BigDecimal(BillsConstant.CHANNEL_PARTNERS_AGENT_BILLS_FREE));
			BigDecimal agentFee = fee.multiply(agent.getPlatformFeeDivide());//根据代理等级再分收益
			BigDecimal platformFee = totalFee.subtract(agentFee);//平台收益为总收益 - 代理收益
			agentBills.setFee(agentFee);
			platformBills.setFee(platformFee);

			BigDecimal availableBalance = Optional.ofNullable(loginUser).map(LoginUser::getAvailableBalance).orElse(BigDecimal.ZERO);
			availableBalance = availableBalance.add(agentFee);
			loginUser.setAvailableBalance(availableBalance);

			BigDecimal totalBalance = Optional.ofNullable(loginUser).map(LoginUser::getTotalBalance).orElse(BigDecimal.ZERO);
			totalBalance = totalBalance.add(agentFee);
			loginUser.setTotalBalance(totalBalance);

			loginUserService.updateById(loginUser);

			boolean save = iAgentBillsService.save(agentBills);

			Assert.isTrue(save, "添加代理人收益信息错误");
		} else {
			//平台全收益(收取的服务费+积分交易费)
			platformBills.setFee(totalFee);
		}

		boolean save = iPlatformBillsService.save(platformBills);
		Assert.isTrue(save, "添加平台收益信息错误");
	}
}
