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

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.manage.coupon.CouponUserMapper;
import com.cyksj.mapper.manage.exchange.ExchangeCodeMapper;
import com.cyksj.mapper.market.draw.LuckyDrawMapper;
import com.cyksj.mapper.market.draw.LuckyDrawRecordMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.DrawRecordDetail;
import com.cyksj.model.views.LuckyDrawView;
import com.cyksj.service.market.draw.LuckyDrawService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/*
 *项目名: netflix
 *文件名: LuckyDrawController
 *创建者: JavaZou
 *创建时间:2022/12/27 13:33
 */
@RestController
@RequestMapping("/manage/market/luckyDraw")
@RequiredArgsConstructor
public class LuckyDrawController {
	private final LuckyDrawService luckyDrawService;

	private final LuckyDrawMapper luckyDrawMapper;

	private final BeanSearcher beanSearcher;

	private final LuckyDrawRecordMapper luckyDrawRecordMapper;

	private final UserMapper userMapper;

	private final ExchangeCodeMapper exchangeCodeMapper;

	private final CouponUserMapper couponUserMapper;

	/**
	 * 新增抽奖奖品
	 */
	@PostMapping("/post")
	public Result<String> saveLuckyDraw(@RequestBody @Validated LuckyDraw luckyDraw) throws Exception {
		luckyDrawService.saveLuckyDraw(luckyDraw);
		return GatewayResponse.SUCCESS.newBuilder().toResult("新增奖品成功");
	}

	/**
	 * 上下架奖品
	 */
	@PutMapping("/put/status/{id}")
	public Result<String> putStatus(@PathVariable Long id) throws Exception {
		luckyDrawService.putStatus(id);
		return GatewayResponse.SUCCESS.newBuilder().toResult("操作成功");
	}

	/**
	 * 编辑奖品
	 */
	@PutMapping("/put")
	public Result<String> updateLuckyDraw(@RequestBody LuckyDraw luckyDraw) throws Exception {
		luckyDrawService.updateLuckyDraw(luckyDraw);
		return GatewayResponse.SUCCESS.newBuilder().toResult("操作成功");
	}

	/**
	 * 删除奖品
	 */
	@DeleteMapping("/delete/{id}")
	public Result<String> deleteLuckyDraw(@PathVariable Long id) {
		LuckyDraw luckyDraw = luckyDrawMapper.selectById(id);
		if (luckyDraw == null || !luckyDraw.getDeleted()) {
			throw BusinessRuntimeException.getInstance("该奖品已不存在");
		}
		luckyDraw.setDeleted(!luckyDraw.getDeleted());
		luckyDrawMapper.updateById(luckyDraw);
		return GatewayResponse.SUCCESS.newBuilder().toResult("删除奖品成功");
	}

	/**
	 * 奖品列表
	 */
	@GetMapping("/get")
	@SaCheckPermission("raffle:view")
	public Result<SearchResult<LuckyDrawView>> get(HttpServletRequest request) {
		SearchResult<LuckyDrawView> search = beanSearcher.search(LuckyDrawView.class, MapUtils.flatBuilder(request.getParameterMap())
				.build());
		search.getDataList().forEach(data->{
			Integer lotteryNum = luckyDrawRecordMapper.getLotteryNum(data.getId());
			data.setLotteryNum(lotteryNum);
			Integer lotteryCount = luckyDrawRecordMapper.selectCount(Wrappers.lambdaQuery(LuckyDrawRecord.class)
					.eq(LuckyDrawRecord::getDrawId, data.getId()));
			data.setLotteryCount(lotteryCount);
			Integer luckyOrderCount = luckyDrawRecordMapper.selectCount(Wrappers.lambdaQuery(LuckyDrawRecord.class)
					.eq(LuckyDrawRecord::getDrawId, data.getId())
					.eq(LuckyDrawRecord::getStatus, LuckyDrawRecord.Status.success));
			data.setLuckyOrderCount(luckyOrderCount);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 奖品中奖明细
	 */
	@GetMapping("/get/detail")
	public Result<SearchResult<DrawRecordDetail>> getDrawRecordDetail(HttpServletRequest request) {
		SearchResult<DrawRecordDetail> search = beanSearcher.search(DrawRecordDetail.class, MapUtils.flatBuilder(request.getParameterMap())
				.build());
		search.getDataList().forEach(data -> {
			User user = userMapper.selectById(data.getUserId());
			data.setNickname(user != null ? user.getNickname() : "");
			if (data.getType() == LuckyDraw.Type.virtualGoods) {
				ExchangeCode code = exchangeCodeMapper.selectOne(Wrappers.lambdaQuery(ExchangeCode.class)
						.eq(ExchangeCode::getUserId, data.getUserId())
						.eq(ExchangeCode::getCode, data.getExCode()).select(ExchangeCode::getUseStatus).last("limit 1"));
				if (code != null) {
					data.setDrawStatus(code.getUseStatus() ? LuckyDrawRecord.Status.success : LuckyDrawRecord.Status.pending);
				}
			} else if (data.getType() == LuckyDraw.Type.coupon) {
				CouponUser couponUser = couponUserMapper.selectOne(Wrappers.lambdaQuery(CouponUser.class)
						.eq(CouponUser::getUserId, data.getUserId())
						.eq(CouponUser::getCouponId, data.getCouponId()).select(CouponUser::getStatus).last("limit 1"));
				if (couponUser != null) {
					data.setDrawStatus(couponUser.getStatus() != CouponUser.Status.unused ? LuckyDrawRecord.Status.success : LuckyDrawRecord.Status.pending);
				}
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}
}
