package com.cyksj.web.controller.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
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.*;
import com.cyksj.mapper.manage.coupon.CouponSkuMapper;
import com.cyksj.mapper.manage.coupon.CouponUserMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.request.ReqGoodsSkuSpec;
import com.cyksj.model.views.*;
import com.cyksj.redis.RedisService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目名: yhlxj2
 * 文件名: UserBenefitsFrontController
 * 创建者: JavaZou
 * 创建时间:2024/9/23 15:32
 */
@RestController
@RequestMapping("/applets/user/benefits")
@RequiredArgsConstructor
@Slf4j
public class UserBenefitsFrontController {
	private final HttpServletRequest request;

	private final BeanSearcher beanSearcher;

	private final OrderDonMapper orderDonMapper;

	private final UserBindRelationService userBindRelationService;

	private final UserStudentCertRecordMapper studentCertRecordMapper;

	private final UserBenefitsOrderRecordMapper userBenefitsOrderRecordMapper;

	private final CouponUserMapper couponUserMapper;

	private final CouponSkuMapper couponSkuMapper;

	private final RedisService redisService;

	private final UserActivityMapper userActivityMapper;

	private final UserMapper userMapper;


	/**
	 * 权益分类
	 */
	@GetMapping("/get/classification")
	public Result<Map<UserBenefits.Type, List<UserBenefitsFrontView>>> getUserBenefitsClassification() {
		String key = RedisService.key.USER_BENEFITS_KEY.getName() + ":cfc";
		long userId = StpUserUtil.getLoginIdAsLong();
		Object o = redisService.get(key);
		Map<UserBenefits.Type, List<UserBenefitsFrontView>> classifications = null;
		List<UserBenefitsFrontView> userBenefitsFrontViews;
		if (o == null) {
			userBenefitsFrontViews = beanSearcher.searchAll(UserBenefitsFrontView.class, MapUtils.builder().onlySelect(UserBenefitsFrontView::getId, UserBenefitsFrontView::getType, UserBenefitsFrontView::getDescription).build());
			classifications = userBenefitsFrontViews.stream().collect(Collectors.groupingBy(UserBenefitsFrontView::getType, LinkedHashMap::new, Collectors.toList()));
			redisService.set(key, classifications, RedisService.key.USER_BENEFITS_KEY.getTimeout() + RandomUtil.randomInt(1800));
		} else {
			classifications = (Map<UserBenefits.Type, List<UserBenefitsFrontView>>) o;
		}
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		classifications.values().forEach(list -> setDataInfo(list, null, userIdList, true, userId));
		return GatewayResponse.SUCCESS.newBuilder().toResult(classifications);
	}

	/**
	 * 用户权益
	 */
	@GetMapping("/get")
	public Result<List<UserBenefitsFrontView>> getUserBenefits(UserBenefits.Type type) {
		long userId = StpUserUtil.getLoginIdAsLong();
		String key = RedisService.key.USER_BENEFITS_KEY.getName();
		if (type != null) {
			key += ":type:" + type.name();
		}
		Object o = redisService.get(key);
		List<UserBenefitsFrontView> userBenefitsFrontViews;
		if (o == null) {
			MapBuilder builder = MapUtils.builder();
			if (type != null) {
				builder.field(UserBenefitsFrontView::getType, type.name());
			}
			userBenefitsFrontViews = beanSearcher.searchAll(UserBenefitsFrontView.class, builder.build());
			if (CollUtil.isEmpty(userBenefitsFrontViews)) {
				return GatewayResponse.SUCCESS.newBuilder().toResult();
			}
			redisService.setNx(key, userBenefitsFrontViews, RedisService.key.USER_BENEFITS_KEY.getTimeout());
		} else {
			userBenefitsFrontViews = (List<UserBenefitsFrontView>) o;
		}
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		setDataInfo(userBenefitsFrontViews, type, userIdList, false, userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(userBenefitsFrontViews);
	}


	public void setDataInfo(List<UserBenefitsFrontView> userBenefitsFrontViews, UserBenefits.Type type, List<Long> userIdList, Boolean isAll, Long userId) {
		for (UserBenefitsFrontView data : userBenefitsFrontViews) {
			if (isAll || type == null) {
				type = data.getType();
			}
			Integer fhCount = 0;
			if (type == UserBenefits.Type.COMBO) {
				//是否已经购买实物
				fhCount = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class).in(OrderDon::getUserId, userIdList).eq(OrderDon::getGoodsId, Constant.NF_EP_GID).notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
				//近一年是否已经使用过该权益
				DateTime lastYear = DateUtil.offsetMonth(DateTime.now(), -12);
				//是否已经使用过该权益
				Integer comboCount = userBenefitsOrderRecordMapper.selectUseComboRecordByUid(userIdList, data.getType(), data.getGoodsId(), null, Constant.noOrderStatus, lastYear, null, null);
				data.setIsComboUsed(comboCount > 0);

				if (StrUtil.isNotBlank(data.getComboSkuIds())) {
					List<GoodsDonSkuFrontView> comboSkuInfo = null;
					try {
						comboSkuInfo = beanSearcher.searchAll(GoodsDonSkuFrontView.class, MapUtils.builder().field(GoodsDonSkuFrontView::getId, Jsons.parseList(data.getComboSkuIds(), Long.class)).op(Operator.InList)
								.selectExclude(GoodsDonSkuFrontView::getSpecJson, GoodsDonSkuFrontView::getImg)
								.build());
						GoodsDonSpec goodsDonSpec = beanSearcher.searchFirst(GoodsDonSpec.class, MapUtils.builder().field(GoodsDonSpec::getGoodsId, 15).build());
						List<ReqGoodsSkuSpec> specs = Jsons.parseList(goodsDonSpec.getSpecsJson(), ReqGoodsSkuSpec.class);
						Map<String, List<ReqGoodsSkuSpec>> collect = specs.stream().collect(Collectors.groupingBy(ReqGoodsSkuSpec::getKey));
						ReqGoodsSkuSpec reqGoodsSkuSpec = collect.get("套餐").get(0);
						data.setGoodsSpecJson(Jsons.toJson(reqGoodsSkuSpec));
					} catch (Exception e) {
						log.error("解析实物套餐json错误,:{}", StringUtil.getErrorText(e));
					}
					data.setComboSkuInfo(comboSkuInfo);
				}
			}
			if (type == UserBenefits.Type.RENEW) {
				//是否购买过该规格套餐
				Long skuId = data.getSkuId();
				Number tickets = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
						.field(RenewalView::getSkuId, skuId)
						.field(RenewalView::getUserId, userIdList).op(Operator.InList)
						.field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
						.build());
				fhCount = tickets.intValue();
			}
			if (type == UserBenefits.Type.CERT) {
				//是否进行大学生认证过
				fhCount = studentCertRecordMapper.selectCount(Wrappers.lambdaQuery(UserStudentCertRecord.class)
						.in(UserStudentCertRecord::getUserId, userIdList));
				try {
					//获取大学生认证优惠券
					UserActivity userActivity = userActivityMapper.selectOne(Wrappers.lambdaQuery(UserActivity.class)
							.eq(UserActivity::getType, 0)
							.eq(UserActivity::getDeleted, 1)
							.last("limit 1"));
					String couponIdsStr = userActivity.getCouponIds();
					List<Long> couponIds = Jsons.parseList(couponIdsStr, Long.class);
					//优惠券使用详情
					if (fhCount > 0) {
						List<CouponUserView> couponUserViews = couponUserMapper.couponPersonalByCouponIds(List.of(userId), couponIds);
						couponUserViews.forEach(couponUserView -> {
							String str = couponSkuMapper.selectGoodsSkuStr(couponUserView.getCouponId());
							couponUserView.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
							List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(couponUserView.getCouponId());
							try {
								couponUserView.setGoodsSkuIds(Jsons.toJson(couponSkus));
								if (StrUtil.isEmpty(couponUserView.getGoodsImg())) {
									Long goodsId = couponSkus.get(0).getGoodsId();
									GoodsDon goodsDon = beanSearcher.searchFirst(GoodsDon.class, MapUtils.builder().field(GoodsDon::getId, goodsId).build());
									couponUserView.setGoodsImg(goodsDon.getImg());
								}
							} catch (Exception e) {

							}
						});
						data.setCouponUserViews(couponUserViews);
					} else {
						List<CouponView> couponViews = beanSearcher.searchAll(CouponView.class, MapUtils.builder().field(CouponView::getId, couponIds).op(Operator.InList).build());
						couponViews.forEach(couponView -> {
							String str = couponSkuMapper.selectGoodsSkuStr(couponView.getId());
							couponView.setGoodsSkuStr(str.replaceAll(",", "/").replaceAll(";", ""));
							List<CouponSkuView> couponSkus = couponSkuMapper.getGoodsSkuByCouponId(couponView.getId());
							try {
								couponView.setGoodsSkuIds(Jsons.toJson(couponSkus));
								if (StrUtil.isEmpty(couponView.getGoodsImg())) {
									Long goodsId = couponSkus.get(0).getGoodsId();
									GoodsDon goodsDon = beanSearcher.searchFirst(GoodsDon.class, MapUtils.builder().field(GoodsDon::getId, goodsId).build());
									couponView.setGoodsImg(goodsDon.getImg());
								}
							} catch (Exception e) {

							}
						});
						data.setCouponViews(couponViews);
					}
				} catch (Exception e) {
					log.error("解析大学生认证json错误,:{}", StringUtil.getErrorText(e));
				}
			}
			if (type == UserBenefits.Type.WELFARE) {
				//是否添加过企业微信
				User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
						.in(User::getId, userIdList)
						.ne(User::getUnionid, StrUtil.EMPTY)
						.last("limit 1"));
				if (user != null) {
					CorpUserFollowView corpUserFollowView = beanSearcher.searchFirst(CorpUserFollowView.class, MapUtils.builder()
							.field(CorpUserFollowView::getUnionId, user.getUnionid())
							.field(CorpUserFollowView::getStatus, 1).build());
					if (corpUserFollowView != null) {
						fhCount = 1;
					}
				}
			}
			data.setIsFh(fhCount > 0);
		}
	}

	/**
	 * 续费权益 车票续费次数
	 */
	@GetMapping("/get/renew/num")
	public Result<Integer> getRenewNum(Long relationId) {
		long userId = StpUserUtil.getLoginIdAsLong();
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		RenewalView renewalViews = beanSearcher.searchFirst(RenewalView.class, MapUtils.builder()
				.field(RenewalView::getRelationId, relationId)
				.field(RenewalView::getUserId, userIdList).op(Operator.InList)
				.field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
				.build());
		Integer renewCount = 0;
		if (renewalViews != null) {
			renewCount = userBenefitsOrderRecordMapper.selectUseComboRecordByUid(userIdList, UserBenefits.Type.RENEW, renewalViews.getGoodsId(), renewalViews.getSkuId(), Constant.noOrderAllStatus, null, renewalViews.getStartTime(), renewalViews.getRelationId());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(renewCount);
	}
}
