package com.cyksj.web.controller.distribute;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyksj.common.constant.Constant;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserDistributeRankStatisticsRecordMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
import com.cyksj.model.entity.User;
import com.cyksj.model.entity.UserDistribute;
import com.cyksj.model.views.*;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.List;
import java.util.Optional;

/**
 * server/分销排行
 * 项目名: yhlxj
 * 文件名: DistributeRankController
 * 创建者: JavaZou
 * 创建时间:2024/7/23 17:10
 */
@RestController
@RequestMapping("/applets/distribute/rank")
@RequiredArgsConstructor
public class DistributeRankController {

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserDistributeMapper userDistributeMapper;

	private final UserDistributeRankStatisticsRecordMapper userDistributeRankStatisticsRecordMapper;

	private final UserMapper userMapper;

	/**
	 * 分销排行活动详情
	 */
	@GetMapping("/get/activity/detail")
	public Result<UserActivityDistributeDetailView> getActivityDetail() {
		long userId = StpUserUtil.getLoginIdAsLong();
		UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
				.eq(UserDistribute::getUserId, userId)
				.eq(UserDistribute::getDeleted, 1)
				.last("limit 1"));
		//非普通推广渠道
		if (userDistribute != null) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		String dateStr = DateTime.now().toString();
		String time = String.format(" and (ua.start_time is null or (ua.start_time < '%s' and ua.end_time > '%s'))", dateStr, dateStr);
		UserActivityDistributeDetailView view = beanSearcher.searchFirst(UserActivityDistributeDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(UserActivityDistributeDetailView::getType, 1)
				.put("time", time)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(view);
	}

	/**
	 * 个人分销排行详情  以及所属分类排行列表
	 */
	@GetMapping("/get/personal")
	public Result<DistributeUserRankPersonalView> getPersonal(@RequestParam(defaultValue = "0") Integer type, @RequestParam(defaultValue = "week") String statisticsType, @RequestParam(defaultValue = "1") Integer start, @RequestParam(defaultValue = "5") Integer limit) {
		long userId = StpUserUtil.getLoginIdAsLong();
		DistributeUserRankPersonalView distributeUserRankPersonalView = new DistributeUserRankPersonalView();
		String orderByField = Constant.money;
		//订单排行
		if (type == 1) {
			orderByField = Constant.orders;
		}
		String statisticsTime;
		if (Constant.week.equals(statisticsType)) {
			//上周一
			LocalDate monday = LocalDate.now().with(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue());
			statisticsTime = monday.toString();
		} else {
			DateTime beginOfMonth = DateUtil.beginOfMonth(DateTime.now());
			statisticsTime = beginOfMonth.toDateStr();
		}

		DistributeUserRankView self = Optional.ofNullable(userDistributeRankStatisticsRecordMapper.getSelfRank(orderByField, userId, statisticsTime)).orElseGet(()->{
			DistributeUserRankView distributeUserRankView = new DistributeUserRankView();
			User user = userMapper.selectById(userId);
			distributeUserRankView.setNickname(user.getNickname());
			distributeUserRankView.setHeadimgurl(user.getHeadimgurl());
			return distributeUserRankView;
		});
		if (self != null && self.getRankId() != null && self.getRankId() <= 10) {
			self.setIsPrize(true);
		}
		distributeUserRankPersonalView.setSelf(self);

		DistributeUserRankView more = userDistributeRankStatisticsRecordMapper.getMoreSelfRank(self.getRankId(), self.getOrders(), self.getMoney(), orderByField, statisticsTime);
		if (more != null) {
			if (type == 1) {
				self.setGapOrders(more.getOrders() - self.getOrders());
			} else {
				self.setGapMoney(more.getMoney().subtract(self.getMoney()));
			}
		}

		Page<DistributeUserRankView> ranks = userDistributeRankStatisticsRecordMapper.selectDistributeRanks(orderByField, statisticsTime, new Page<>(start, limit));
		distributeUserRankPersonalView.setRanks(ranks);
		return GatewayResponse.SUCCESS.newBuilder().toResult(distributeUserRankPersonalView);
	}

	/**
	 * 上期获奖名单
	 */
	@GetMapping("/get/previous/winners")
	public Result<List<DistributeUserRankPreView>> getPreviousWinners(@RequestParam(defaultValue = "0") Integer type, @RequestParam(defaultValue = "week") String statisticsType) throws Exception {
		long userId = StpUserUtil.getLoginIdAsLong();
		String lastTime;
		if (Constant.week.equals(statisticsType)) {
			//上周一
			LocalDate monday = LocalDate.now().with(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue()).plusWeeks(-1);
			lastTime = monday.toString();
		} else {
			DateTime lastBeginOfMonth = DateUtil.offsetMonth(DateUtil.beginOfMonth(DateTime.now()), -1);
			lastTime = lastBeginOfMonth.toDateStr();
		}
		List<DistributeUserRankPreView> ranks = beanSearcher.searchAll(DistributeUserRankPreView.class, MapUtils.builder().field(DistributeUserRankPreView::getType, type)
				.field(DistributeUserRankPreView::getStatisticsStartTime, lastTime).build());

		ranks.forEach(rank -> {
			if (ObjectUtil.equal(userId, rank.getUserId())) {
				//在前10
				rank.setIsPrize(true);
				rank.setUserId(null);
			}
		});

		return GatewayResponse.SUCCESS.newBuilder().toResult(ranks);
	}

	/**
	 * 获奖明细
	 */
	@GetMapping("/get/reward/detail")
	public Result<SearchResult<UserDistributeRankRewardDetailView>> getUserRewardDetailView() {
		long userId = StpUserUtil.getLoginIdAsLong();
		SearchResult<UserDistributeRankRewardDetailView> search = beanSearcher.search(UserDistributeRankRewardDetailView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(UserDistributeRankRewardDetailView::getUserId, userId)
				.orderBy(UserDistributeRankRewardDetailView::getCreatedTime).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 返现明细
	 */
	@GetMapping("/get/distribute/returnMoney/detai")
	public Result<SearchResult<userDistributeReturnMoneyDetail>> getReturnMoneyDetailView() {
		long userId = StpUserUtil.getLoginIdAsLong();
		SearchResult<userDistributeReturnMoneyDetail> search = beanSearcher.search(userDistributeReturnMoneyDetail.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(userDistributeReturnMoneyDetail::getUserId, userId)
				.orderBy(userDistributeReturnMoneyDetail::getCreatedTime).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

}
