package org.springblade.gateway.client_gateway.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.PaymentCache;
import org.springblade.common.enums.AppConstant;
import org.springblade.common.enums.OrderType;
import org.springblade.common.enums.PaymentScene;
import org.springblade.common.enums.PaymentType;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.gateway.client_gateway.entity.vo.AgenterInfoVO;
import org.springblade.gateway.client_gateway.wrapper.ClientAgentBillsWrapper;
import org.springblade.ldt.agent.entity.Agent;
import org.springblade.ldt.agent.entity.AgentBills;
import org.springblade.ldt.agent.entity.AgentLeagueRecord;
import org.springblade.ldt.agent.entity.AgentRecord;
import org.springblade.ldt.agent.service.IAgentBillsService;
import org.springblade.ldt.agent.service.IAgentLeagueRecordService;
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.service.IBillsService;
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.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author: lianghanqiang
 * @description: 代理控制器
 * @since: 8/23/21 -- 2:54 PM
 */
@RestController
@RequestMapping("/app/agent")
@Api(tags = "APP代理商模块")
@AllArgsConstructor
public class AgentController {

	private IBillsService billsService;
	private ILoginUserService loginUserService;
	private IAgentBillsService agentBillsService;
	private IShopService shopService;
	private IAgentLeagueRecordService agentLeagueRecordService;
	private IAgentRecordService agentRecordService;
	private IAgentService agentService;


	@ApiOperation("获取代理商信息")
	@GetMapping("agenterInfo")
	public R<AgenterInfoVO> agenterInfo(@NotBlank String userId) {

		//获取代理商的基本信息
		LoginUser loginUser = loginUserService.getById(userId);
		Assert.notNull(loginUser, "获取代理商信息失败");

		//今日收益
		QueryWrapper<AgentBills> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("IFNULL(sum(fee),0) as todayEarning")
			.lambda()
			.eq(AgentBills::getAgenter, userId)
			.between(AgentBills::getCreateTime, DateUtil.beginOfDay(new Date()), DateUtil.beginOfDay(new Date()));
		Map<String, Object> map = agentBillsService.getMap(queryWrapper);
		Double todayEarning = Convert.toDouble(map.get("todayEarning"));

		//总收益
		Double totalEarning = Convert.toDouble(loginUser.getTotalBalance());

		//推广数量
		int count = shopService.count(Condition.getQueryWrapper(new Shop()).lambda().eq(Shop::getAgenter, userId));

		AgenterInfoVO agenterInfoVO = AgenterInfoVO.builder()
			.agenterName(loginUser.getNickName())
			.agenterAvatar(loginUser.getAvatar())
			.agenterType(loginUser.getUserType())
			.totalEarning(totalEarning)
			.todayEarning(todayEarning)
			.promoteNum(count)
			.build();

		return R.data(agenterInfoVO);
	}

	@ApiOperation("获取收益明细")
	@GetMapping("earningsDetail")
	public R earningsDetail(AgentBills agentBills, Query query) {
		IPage<AgentBills> pages = agentBillsService.page(Condition.getPage(query), Condition.getQueryWrapper(agentBills));
		return R.data(ClientAgentBillsWrapper.build(shopService, loginUserService).pageVO(pages));
	}

	@ApiOperation("获取推广明细")
	@GetMapping("promoteDetail")
	public R promoteDetail(@NotBlank String userId) {
		return R.data(null);

	}

	/*@ApiOperation("提交申请订单")
	@PostMapping("addAgentOrder")
	public R addAgentOrder(@Valid @RequestBody Bills bills){
		boolean flag = billsService.saveOrUpdate(bills);
		//支付参数
		SuccessParams successParams  = SuccessParams.builder()
			.orderType(OrderType.AGENT_CHARGE.name())
			.status(AppConstant.BillPayStatus.待付款.name())
			.userId(bills.getPayId())
			.totalPrice(bills.getPrice())
			.bills(bills)
			.tenantId(AppConstant.PLATFORM_TENANT_ID)
			.build();
		PaymentCache.putSuccessParams(Convert.toStr(bills.getId()),successParams);
		return flag?R.data(bills): R.fail("提交订单失败！");
	}*/

	@ApiOperation("提交申请订单")
	@PostMapping("addAgentOrder")
	public R addAgentOrder(@Valid @RequestBody AgentLeagueRecord agentLeagueRecord) {

		AgentRecord agentRecord = agentRecordService.getOne(Condition.getQueryWrapper(new AgentRecord()).lambda().eq(AgentRecord::getAccountId, agentLeagueRecord.getUserId()));
		if (!Objects.isNull(agentRecord)) {
			Agent agent = agentService.getById(agentLeagueRecord.getAgentId());
			agentRecord.setAgentId(agent.getId());
			agentRecord.setAgentType(agent.getLevel());
			agentRecordService.updateById(agentRecord);
		}

		Bills bills = new Bills();
		bills.setPointNum(BigDecimal.ZERO);
		bills.setFee(BigDecimal.ZERO);
		bills.setPointFee(BigDecimal.ZERO);
		bills.setBalanceNum(BigDecimal.ZERO);
		bills.setPrice(agentLeagueRecord.getLeague());
		bills.setPayPlugin(PaymentType.YEE_PAY.name());
		bills.setPayId(agentLeagueRecord.getUserId());
		bills.setTitle("代理缴费");
		bills.setPayStatus(AppConstant.BillPayStatus.待付款.name());
		bills.setPayScene(PaymentScene.SCAN_CODE.name());
		bills.setCost(agentLeagueRecord.getLeague());
		bills.setTotalPrice(agentLeagueRecord.getLeague());
		bills.setType(OrderType.AGENT_CHARGE.name());
		bills.setDiscount(BigDecimal.ONE);
		org.springframework.util.Assert.isTrue(billsService.saveOrUpdate(bills), () -> {
			throw new ServiceException("订单异常！");
		});

		agentLeagueRecord.setTradeNo(bills.getId());
		boolean flag = agentLeagueRecordService.saveOrUpdate(agentLeagueRecord);

		//支付参数
		SuccessParams successParams = SuccessParams.builder()
			.orderType(OrderType.AGENT_CHARGE.name())
			.status(AppConstant.BillPayStatus.待付款.name())
			.userId(agentLeagueRecord.getUserId())
			.totalPrice(agentLeagueRecord.getLeague())
			.agentLeagueRecord(agentLeagueRecord)
			.tenantId(AppConstant.PLATFORM_TENANT_ID)
			.build();
		PaymentCache.putSuccessParams(Convert.toStr(bills.getId()), successParams);
		return flag ? R.data(agentLeagueRecord) : R.fail("提交订单失败！");
	}

}
