package com.cyksj.web.controller.market;

import com.cyksj.common.annotation.NoSubmit;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.common.util.StringUtil;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserMapper;
import com.cyksj.model.entity.LuckyDraw;
import com.cyksj.model.entity.User;
import com.cyksj.model.manage.views.GroupsRelationView;
import com.cyksj.model.request.LuckyDrawReq;
import com.cyksj.model.views.LuckyDrawRecordView;
import com.cyksj.model.views.LuckyDrawView;
import com.cyksj.service.market.MarketFrontService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/*
 *项目名: netflix
 *文件名: LuckyDrawFrontController
 *创建者: JavaZou
 *创建时间:2022/12/28 13:51
 */
@RestController
@RequestMapping("/applets/market/luckyDraw")
@RequiredArgsConstructor
public class LuckyDrawFrontController {
	private final BeanSearcher beanSearcher;

	private final MarketFrontService marketFrontService;

	private final UserMapper userMapper;

	private final HttpServletRequest request;

	/**
	 * 奖品列表
	 */
	@GetMapping("/get")
	public Result<List<LuckyDrawView>> getLuckyDraw(@RequestParam(defaultValue = "true") Boolean isRepeat) throws Exception {
		long userId = StpUserUtil.getLoginIdAsLong();
		List<LuckyDrawView> drawViews = beanSearcher.searchAll(LuckyDrawView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(LuckyDrawView::getStatus, true).op(Operator.Equal).build());
		if (drawViews.isEmpty()) {
			throw BusinessRuntimeException.getInstance("暂未配置奖品");
		}
		List<LuckyDrawView> re = new ArrayList<>();
		for (LuckyDrawView drawView : drawViews) {
			List<Integer> positions = Jsons.parseList(drawView.getPosition(), Integer.class);
			for (Integer i : positions) {
				LuckyDrawView view = new LuckyDrawView();
				BeanUtils.copyProperties(drawView, view);
				view.setPosition(i.toString());
				re.add(view);
				if (!isRepeat) {
					break;
				}
			}
		}
		re = re.stream().sorted(Comparator.comparing(LuckyDrawView::getPosition)).collect(Collectors.toList());
		return GatewayResponse.SUCCESS.newBuilder().toResult(re);
	}

	/**
	 * 我的抽奖记录
	 */
	@GetMapping("/get/record")
	public Result<SearchResult<LuckyDrawRecordView>> getLuckyDrawRecord(HttpServletRequest request) {
		long userId = StpUserUtil.getLoginIdAsLong();
		SearchResult<LuckyDrawRecordView> search = beanSearcher.search(LuckyDrawRecordView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(LuckyDrawRecordView::getUserId, userId)
				.build());
		search.getDataList().forEach(data -> {
			User user = userMapper.selectById(data.getUserId());
			if (user != null) {
				data.setNickname(StringUtil.anonymity(user.getNickname().toCharArray()));
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 特定抽奖机会
	 */
	@GetMapping("/get/specific/num")
	public Result<Integer> getSpecificNum() {
		long userId = StpUserUtil.getLoginIdAsLong();
		Integer num = marketFrontService.getSpecificChanceNum(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(num);
	}

	/**
	 * 特定奖池 可选平台车票
	 */
	@GetMapping("/get/specific/tickets")
	public Result<List<GroupsRelationView>> getSpecificTickets() throws Exception {
		long userId = StpUserUtil.getLoginIdAsLong();
		List<GroupsRelationView> result = marketFrontService.getSpecificTickets(userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(result);
	}

	/**
	 * 抽奖
	 */
//	@PostMapping("/lottery")
	@NoSubmit
	public Result<LuckyDrawView> lottery(@RequestParam(defaultValue = "normal") LuckyDraw.DrawType drawType) throws Exception {
		Long userId = StpUserUtil.getLoginIdAsLong();
		LuckyDrawView luckyDrawView = marketFrontService.lottery(userId, drawType);
		return GatewayResponse.SUCCESS.newBuilder().toResult(luckyDrawView);
	}

	/**
	 * 领取奖品
	 */
	@PostMapping("/post/receive")
	@NoSubmit
	public Result<String> receivedLuckyDraw(@RequestBody @Validated LuckyDrawReq luckyDrawReq) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		marketFrontService.receivedLuckyDraw(userId, luckyDrawReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult("领取成功");
	}

}
