package com.cyksj.web.controller.distribute;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.EnvCommonService;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.dto.UserSharedDto;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserChanceMapper;
import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserDistributeInviteRecordMapper;
import com.cyksj.model.dto.EquipmentConfigDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.views.GroupsRelationView;
import com.cyksj.model.request.LoginReq;
import com.cyksj.model.request.ReceiveBenefitsReq;
import com.cyksj.model.views.CouponUserView;
import com.cyksj.model.views.EquipmentCouponView;
import com.cyksj.model.views.EquipmentDistributeView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.distribute.equipment.EquipmentDistributeFrontService;
import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
import com.cyksj.service.sys.SysConfigService;
import com.cyksj.service.user.UserService;
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.MapBuilder;
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;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/*
 *项目名: netflix
 *文件名: EquipmentDistributeController
 *创建者: JavaZou
 *创建时间:2023/2/23 15:41
 */
@RestController
@RequestMapping("/applets/equipment")
@RequiredArgsConstructor
public class EquipmentDistributeController {
	private final EquipmentUserChanceMapper equipmentUserChanceMapper;

	private final EnvCommonService envCommonService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final SysConfigService sysConfigService;

	private final EquipmentDistributeFrontService equipmentDistributeFrontService;

	private final RedisService redisService;

	private final UserMapper userMapper;

	private final OrderDonMapper orderDonMapper;

	private final UserService userService;

	private final EquipmentDistributeService equipDistributeService;

	private final EquipmentUserDistributeInviteRecordMapper inviteRecordMapper;
	/**
	 * 个人实物分销详情
	 */
	@GetMapping("/personal")
	public Result<EquipmentDistributeView> getPersonalDetail() {
		Long userId = StpUserUtil.getLoginIdAsLong();
		EquipmentUserChance chance = equipmentUserChanceMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserChance.class)
				.eq(EquipmentUserChance::getUserId, userId).last("limit 1"));
		EquipmentDistributeView view = new EquipmentDistributeView();
		view.setNum(chance == null ? 0 : chance.getNum());
		String equipDistributeUrl = String.format("%syinhe/web/detail/15?sharedId=%s&dsType=%s", envCommonService.getDomain(), userId, 2);
		view.setUrl(equipDistributeUrl);
		SysConfig config = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.EQUIPMENT_DISTRIBUTE_KEY).last("limit 1"));
		if (config != null) {
			view.setEquipmentConfig(config.getSysValue());
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(view);
	}

	/**
	 * 邀请好友明细
	 */
	@GetMapping("/get/invite/record")
	public Result<SearchResult<EquipmentUserPayRecord>> getInviteRecord() {
		Long userId = StpUserUtil.getLoginIdAsLong();
		SearchResult<EquipmentUserPayRecord> search = beanSearcher.search(EquipmentUserPayRecord.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(EquipmentUserPayRecord::getShareId, userId)
				.build());
		search.getDataList().forEach(data -> {
			Optional.ofNullable(userMapper.selectById(data.getUserId())).ifPresent(user -> {
				data.setNickname(user.getNickname());
				data.setHeadImg(user.getHeadimgurl());
			});
			Optional.ofNullable(orderDonMapper.selectById(data.getOrderId())).ifPresent(oder -> data.setPayTime(oder.getPayTime()));
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 增加权益的车票
	 */
	@GetMapping("/get/benefits/ticket")
	public Result<List<GroupsRelationView>> getBenefitsTicket() throws Exception {
		Long userId = StpUserUtil.getLoginIdAsLong();
		SysConfig config = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.EQUIPMENT_DISTRIBUTE_KEY).last("limit 1"));
		List<Long> goodsIds = null;
		if (config != null) {
			String sysValue = config.getSysValue();
			if (StrUtil.isNotBlank(sysValue)) {
				EquipmentConfigDto equipmentConfigDto = Jsons.parseObject(sysValue, EquipmentConfigDto.class);
				if (CollUtil.isEmpty(equipmentConfigDto.getSkuList())) {
					return GatewayResponse.SUCCESS.newBuilder().toResult();
				}
				goodsIds = equipmentConfigDto.getSkuList().stream().map(GoodsDonSku::getGoodsId).collect(Collectors.toList());
			}
		}
		MapBuilder builder = MapUtils.builder()
				.field(GroupsRelationView::getUserId, userId)
				.field(GroupsRelationView::getGoodsType, 1)
				.field(GroupsRelationView::getGoodsSecondType, 2)
				.field(GroupsRelationView::getStatus, GroupsRelation.Status.validity.name())
				.field(GroupsRelationView::getExpiryTime).op(Operator.NotNull);
		if (!goodsIds.isEmpty()) {
			builder.field(GroupsRelationView::getGoodsId, goodsIds).op(Operator.InList);
		}
		List<GroupsRelationView> list = beanSearcher.searchAll(GroupsRelationView.class, builder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(list);
	}

	/**
	 * 领取权益
	 */
	@PostMapping("/use/benefits")
	public Result<GroupsRelationView> useBenefits(@RequestBody @Validated ReceiveBenefitsReq req) throws Exception {
		Long goodsId = req.getGoodsId(), skuId = req.getSkuId(), relationId = req.getRelationId();
		Long userId = StpUserUtil.getLoginIdAsLong();
		SysConfig config = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.EQUIPMENT_DISTRIBUTE_KEY).last("limit 1"));
		String sysValue = config.getSysValue();
		if (StrUtil.isEmpty(sysValue)) {
			throw BusinessRuntimeException.getInstance("");
		}
		EquipmentConfigDto equipmentConfigDto = Jsons.parseObject(sysValue, EquipmentConfigDto.class);
		if (CollUtil.isEmpty(equipmentConfigDto.getSkuList())) {
			throw BusinessRuntimeException.getInstance("暂无该车票权益");
		}
		Optional<GoodsDonSku> first = equipmentConfigDto.getSkuList().stream().filter(goodsDonSku -> {
			if (goodsDonSku.getId().equals(skuId)) {
				return true;
			}
			return false;
		}).findFirst();
		if (first.isEmpty()) {
			throw BusinessRuntimeException.getInstance("暂无该车票权益");
		}
		GroupsRelationView groupsRelationView = equipmentDistributeFrontService.useBenefits(userId, goodsId, skuId, relationId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(groupsRelationView);
	}

	/**
	 * 新用户领取后分销优惠券后弹窗
	 */
	@GetMapping("/get/couponList")
	public Result<EquipmentCouponView> getEquipmentCouponList() {
		Long userId = StpUserUtil.getLoginIdAsLong();
		Object value = redisService.get(RedisService.key.EQUIPMENT_DISTRIBUTE_COUPON_KEY.getNameFormat(userId));
		if (value != null) {
			EquipmentCouponView equipmentCouponView = new EquipmentCouponView();
			List<CouponUserView> couponUserViews = beanSearcher.searchAll(CouponUserView.class, MapUtils.builder()
					.field(CouponUserView::getUserId, userId)
					.field(CouponUserView::getChannel, CouponUser.Channel.equipment.name())
					.orderBy(CouponUserView::getOrderBy).asc()
					.build());
			EquipmentUserDistributeInviteRecord record = inviteRecordMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserDistributeInviteRecord.class)
					.eq(EquipmentUserDistributeInviteRecord::getUserId, userId).last("limit 1"));
			if (record != null) {
				User user = userMapper.selectById(record.getShareId());
				Optional.ofNullable(user).ifPresent(u->{
					equipmentCouponView.setNickname(u.getNickname());
					equipmentCouponView.setUserId(u.getId());
					equipmentCouponView.setHeadImg(u.getHeadimgurl());
				});
			}
			equipmentCouponView.setCouponList(couponUserViews);
			return GatewayResponse.SUCCESS.newBuilder().toResult(equipmentCouponView);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 已登录的用户 实物分销
	 */
	@PostMapping("/hasLogged")
	public Result<String> hasLogged(@RequestBody LoginReq req) {
		Long userId = StpUserUtil.getLoginIdAsLong();
		DateTime now = DateTime.now();
		User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getId, userId)
				.between(User::getCreatedTime, DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).last("limit 1"));
		Boolean isNewUser = user != null ? true : false;
		Long sharedId = req.getSharedId();
		String dsCode = req.getDsCode();
		Integer dsType = req.getDsType();
		if (StrUtil.isNotBlank(dsCode)) {
			UserSharedDto userSharedDto = userService.getUserShredDtoByDsCode(dsCode);
			if (userSharedDto != null) {
				sharedId = userSharedDto.getSharedId();
			}
		}
		//新旧用户都可实物分销
		if (sharedId != null && dsType != null && dsType == 2) {
			equipDistributeService.saveDistributionInvitation(sharedId, isNewUser, userId);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 是否是新用户
	 */
	@GetMapping("/get/isNewUser")
	public Result<Boolean> isNewUser() {
		Long userId = StpUserUtil.getLoginIdAsLong();
		DateTime now = DateTime.now();
		User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getId, userId)
				.between(User::getCreatedTime, DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).last("limit 1"));
		if (user == null) {
			return GatewayResponse.SUCCESS.newBuilder().toResult(false);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(true);
	}

	/**
	 * 实物分销绑定
	 */
	@GetMapping("/equipment/invite/bind")
	public Result<String> equipmentInviteBind(String dsCode) {
		long userId = StpUserUtil.getLoginIdAsLong();
		userService.saveEpDistributeShared(userId, dsCode);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}
}
