package com.cyksj.web.controller.manage.active;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserActivityRankRobotMapper;
import com.cyksj.mapper.UserDistributeRankStatisticsRecordMapper;
import com.cyksj.model.entity.UserActivity;
import com.cyksj.model.entity.UserActivityRankRobot;
import com.cyksj.model.views.ActivityOrderDataView;
import com.cyksj.model.views.UserDistributeRankActivityView;
import com.cyksj.service.user.UserActivityService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * admin/分销排行
 * 项目名: yhlxj
 * 文件名: UserActivityController
 * 创建者: JavaZou
 * 创建时间:2024/4/17 12:22
 */
@RestController
@RequestMapping("/manage/activity")
@Slf4j
@RequiredArgsConstructor
public class UserActivityController {
	private final UserActivityService userActivityService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserActivityRankRobotMapper rankRootMapper;

	private final UserDistributeRankStatisticsRecordMapper userDistributeRankStatisticsRecordMapper;

	/**
	 * 新建活动
	 */
	@PostMapping("/post")
	public Result<String> insertActivity(@RequestBody @Validated UserActivity userActivity) throws Exception {
		userActivityService.saveOrUpdateActivity(userActivity);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 编辑活动
	 */
	@PutMapping("/update")
	public Result<String> updateActivity(@RequestBody @Validated UserActivity userActivity) throws Exception {
		userActivityService.saveOrUpdateActivity(userActivity);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除活动
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deleteActivity(@PathVariable Long id) {
		UserActivity activity = userActivityService.getById(id);
		if (activity != null && activity.getDeleted()) {
			activity.setDeleted(false);
			userActivityService.updateById(activity);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 活动列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<UserActivity>> get() {
		SearchResult<UserActivity> search = beanSearcher.search(UserActivity.class, MapUtils.flatBuilder(request.getParameterMap()).field(UserActivity::getDeleted, 1).build());
		search.getDataList().forEach(e -> {
			if (e.getType() == 1) {
				String statisticsTime;
				if (e.getStatisticsType().equals(Constant.week)) {
					statisticsTime = LocalDate.now().with(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue()).toString();
				} else {
					statisticsTime = LocalDate.now().with(ChronoField.DAY_OF_MONTH, DayOfWeek.MONDAY.getValue()).toString();
				}
				List<UserActivityRankRobot> userActivityRankRobots = rankRootMapper.selectList(Wrappers.lambdaQuery(UserActivityRankRobot.class)
						.eq(UserActivityRankRobot::getAcId, e.getId()));
				userActivityRankRobots.forEach(robot -> {
					UserActivityRankRobot moneyRank = userDistributeRankStatisticsRecordMapper.getRobotRankInfo(robot.getId(), Constant.money, statisticsTime);
					if (moneyRank != null) {
						robot.setMoney(moneyRank.getMoney());
						robot.setMoneyRank(moneyRank.getRankId());
					}
					UserActivityRankRobot orderRank = userDistributeRankStatisticsRecordMapper.getRobotRankInfo(robot.getId(), Constant.orders, statisticsTime);
					if (orderRank != null) {
						robot.setOrders(orderRank.getOrders());
						robot.setOrderRank(orderRank.getRankId());
					}
				});
				e.setRankRobots(userActivityRankRobots);

				try {
					if (StrUtil.isNotBlank(e.getRewardInfo())) {
						List<UserActivity.RewardInfo> rewardInfos = Jsons.parseList(e.getRewardInfo(), UserActivity.RewardInfo.class);
						e.setRewardInfoList(rewardInfos);
					}
				} catch (Exception ex) {
				}

				//活动数据
				ActivityOrderDataView activityOrderDataView = userDistributeRankStatisticsRecordMapper.selectAcOrderDataView(e.getId());
				e.setOrderDataView(activityOrderDataView);
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 分销排行列表
	 */
	@GetMapping("/get/rank/list")
	public Result<Page<UserDistributeRankActivityView>> rankList(Long acId, String nickname, Long userId, String date, @RequestParam(defaultValue = "1") Integer start, @RequestParam(defaultValue = "10") Integer limit, @RequestParam(defaultValue = "0") Integer type, String orderBy, String sort) {
		String field = Constant.money;
		if (type == 1) {
			field = Constant.orders;
		}
		UserActivity activity = userActivityService.getById(acId);
		if (date == null) {
			if (activity.getStatisticsType().equals(Constant.week)) {
				date = LocalDate.now().with(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue()).toString();
			} else {
				date = LocalDate.now().with(ChronoField.DAY_OF_MONTH, DayOfWeek.MONDAY.getValue()).toString();
			}
		}
		Page<UserDistributeRankActivityView> page = userDistributeRankStatisticsRecordMapper.rankPage(nickname, userId, date, new Page<>(start, limit), field, orderBy, sort);
		return GatewayResponse.SUCCESS.newBuilder().toResult(page);
	}

}
