package com.cyksj.service.fission.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.GroupsMapper;
import com.cyksj.mapper.GroupsRelationMapper;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.fission.UserMirrorFissionReceiveRecordMapper;
import com.cyksj.mapper.fission.UserMirrorFissionRecordMapper;
import com.cyksj.mapper.fission.UserMirrorFissionTicketConfigMapper;
import com.cyksj.mapper.fission.UserMirrorFissionUserMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.response.UserMirrorFissionReceiveResp;
import com.cyksj.model.views.RenewalView;
import com.cyksj.service.fission.UserMirrorFissionFrontService;
import com.cyksj.service.relation.GroupRelationClearService;
import com.cyksj.service.relation.GroupRelationFrontService;
import com.cyksj.service.user.UserBindRelationService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 项目名: yhlxj2
 * 文件名: UserMirrorFissionFrontServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/11/21 18:23
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserMirrorFissionFrontServiceImpl implements UserMirrorFissionFrontService {
	private final UserBindRelationService userBindRelationService;

	private final OrderDonMapper orderDonMapper;

	private final UserMirrorFissionRecordMapper userMirrorFissionRecordMapper;

	private final GoodsDonSkuMapper goodsDonSkuMapper;

	private final UserMirrorFissionReceiveRecordMapper userMirrorFissionReceiveRecordMapper;

	private final GroupRelationFrontService groupRelationFrontService;

	private final GroupsRelationMapper groupsRelationMapper;

	private final GroupsMapper groupsMapper;

	private final UserMirrorFissionTicketConfigMapper userMirrorFissionTicketConfigMapper;

	private final UserMirrorFissionUserMapper userMirrorFissionUserMapper;

	private final BeanSearcher beanSearcher;

	private final GroupRelationClearService groupRelationClearService;

	@Override
	public Boolean getPurchasedMirrorStatus(long userId, Long goodsId) {
		return hasPaidMirrorTicket(userId, goodsId);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public UserMirrorFissionReceiveResp receiveTrialMirrorTicket(long userId, String code) {
		if (true) {
			throw BusinessRuntimeException.getInstance("活动已结束");
		}
		UserMirrorFissionRecord userMirrorFissionRecord = userMirrorFissionRecordMapper.selectOne(Wrappers.lambdaQuery(UserMirrorFissionRecord.class)
				.eq(UserMirrorFissionRecord::getCode, code)
				.last("limit 1"));
		if (userMirrorFissionRecord == null) {
			throw BusinessRuntimeException.getInstance("活动不存在");
		}
		Long fissionId = userMirrorFissionRecord.getId();
		UserMirrorFissionReceiveResp resp = new UserMirrorFissionReceiveResp();
		resp.setStatus(UserMirrorFissionReceiveResp.Status.success);
		if (userMirrorFissionRecord.getRemainNum() == 0) {
			resp.setStatus(UserMirrorFissionReceiveResp.Status.completed);
//			throw BusinessRuntimeException.getInstance("很抱歉，您来晚了，体验卡已被领完");
			return resp;
		}
		if (hasPaidMirrorTicket(userId, userMirrorFissionRecord.getGoodsId())) {
			resp.setStatus(UserMirrorFissionReceiveResp.Status.purchased);
//			throw BusinessRuntimeException.getInstance("很抱歉，您已购买过GPT镜像车票，无法参加此活动");
			return resp;
		}
		Long trialSkuId = userMirrorFissionRecord.getTrialSkuId();
		//发送试用镜像车票
		GoodsDonSku sku = goodsDonSkuMapper.selectById(userMirrorFissionRecord.getTrialSkuId());
		if (sku == null) {
			throw BusinessRuntimeException.getInstance("试用车票异常,请联系客服..");
		}
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		Integer selectCount = userMirrorFissionReceiveRecordMapper.selectCount(Wrappers.lambdaQuery(UserMirrorFissionReceiveRecord.class)
				.in(UserMirrorFissionReceiveRecord::getUserId, userIdList)
				.eq(UserMirrorFissionReceiveRecord::getSkuId, trialSkuId));
		if (selectCount > 0) {
			resp.setStatus(UserMirrorFissionReceiveResp.Status.claimed);
//			throw BusinessRuntimeException.getInstance("您已领取该试用车票");
			return resp;
		}
		Integer update = userMirrorFissionRecordMapper.updateFissionRemainNum(fissionId);
		if (update == 0) {
			resp.setStatus(UserMirrorFissionReceiveResp.Status.completed);
//			throw BusinessRuntimeException.getInstance("很抱歉，您来晚了，体验卡已被领完");
			return resp;
		}
		Long relationId = null;
		try {
			UserMirrorFissionReceiveRecord receiveRecord = new UserMirrorFissionReceiveRecord();
			receiveRecord.setUserId(userId);
			receiveRecord.setGoodsId(sku.getGoodsId());
			receiveRecord.setSkuId(trialSkuId);
			receiveRecord.setFissionId(fissionId);
			//车票id
			relationId = groupRelationFrontService.getTrialTicketByUserIdAndGoodsId(userId, trialSkuId, 3);
			receiveRecord.setRelationId(relationId);
			userMirrorFissionReceiveRecordMapper.insert(receiveRecord);
			//给裂变活动发起者车票添加时长
			groupsRelationMapper.incrExpiryTime(userMirrorFissionRecord.getRelationId(), userMirrorFissionRecord.getUserId());
		} catch (DuplicateKeyException e) {
			resp.setStatus(UserMirrorFissionReceiveResp.Status.claimed);
			if (relationId != null) {
				GroupsRelation relation = groupsRelationMapper.selectById(relationId);
				if (relation.getUserId().equals(userId)) {
					groupRelationClearService.clearTicket(relation, UserTicketClearedRecord.Source.manual);
				}
			}
			userMirrorFissionRecordMapper.incrFissionRemainNum(fissionId);
//			throw BusinessRuntimeException.getInstance("您已领取该试用车票");
		}
		return resp;
	}

	@Override
	public UserMirrorFissionRecord getPresentFissionTicket(long userId) {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		UserMirrorFissionRecord userMirrorFissionRecord = userMirrorFissionRecordMapper.selectOne(Wrappers.lambdaQuery(UserMirrorFissionRecord.class)
				.in(UserMirrorFissionRecord::getUserId, userIdList)
				.select(UserMirrorFissionRecord::getCode, UserMirrorFissionRecord::getRelationId, UserMirrorFissionRecord::getGoodsId, UserMirrorFissionRecord::getTrialSkuId, UserMirrorFissionRecord::getNum, UserMirrorFissionRecord::getRemainNum)
				.last("limit 1"));
		return userMirrorFissionRecord;
	}

	@Override
	public UserMirrorFissionRecord recordUserMirrorFission(long userId, Long relationId) throws Exception {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		GroupsRelation relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
				.in(GroupsRelation::getUserId, userIdList)
				.eq(GroupsRelation::getId, relationId)
				.gt(GroupsRelation::getExpiryTime, DateTime.now())
				.last("limit 1"));
		if (relation == null) {
			throw BusinessRuntimeException.getInstance("车票不存在");
		}
		UserMirrorFissionRecord userMirrorFissionRecord;
		GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
		GoodsDonSku sku = goodsDonSkuMapper.selectById(groupsTrips.getSkuId());
		if (!sku.getIsMirror()) {
			throw BusinessRuntimeException.getInstance("只支持镜像车票");
		}
		Integer count = userMirrorFissionRecordMapper.selectCount(Wrappers.lambdaQuery(UserMirrorFissionRecord.class)
				.eq(UserMirrorFissionRecord::getGoodsId, sku.getGoodsId())
				.in(UserMirrorFissionRecord::getUserId, userIdList));
		if (count > 0) {
			userMirrorFissionRecord = userMirrorFissionRecordMapper.selectOne(Wrappers.lambdaQuery(UserMirrorFissionRecord.class)
					.in(UserMirrorFissionRecord::getUserId, userIdList)
					.eq(UserMirrorFissionRecord::getRelationId, relationId)
					.eq(UserMirrorFissionRecord::getGoodsId, sku.getGoodsId())
					.last("limit 1"));
			return userMirrorFissionRecord;
		}
		//特定老用户可进行镜像裂变活动
		UserMirrorFissionUser userMirrorFissionUser = userMirrorFissionUserMapper.selectOne(Wrappers.lambdaQuery(UserMirrorFissionUser.class).
				in(UserMirrorFissionUser::getUserId, userIdList)
				.last("limit 1"));
		if (userMirrorFissionUser == null) {
			throw BusinessRuntimeException.getInstance("您不符合该活动要求");
		}
		UserMirrorFissionTicketConfig userMirrorFissionTicketConfig = userMirrorFissionTicketConfigMapper.selectOne(Wrappers.lambdaQuery(UserMirrorFissionTicketConfig.class)
				.eq(UserMirrorFissionTicketConfig::getGoodsId, sku.getGoodsId())
				.last("limit 1"));
		if (userMirrorFissionTicketConfig == null) {
			throw BusinessRuntimeException.getInstance("活动不存在");
		}
		try {
			userMirrorFissionRecord = new UserMirrorFissionRecord();
			userMirrorFissionRecord.setUserId(relation.getUserId());
			userMirrorFissionRecord.setRelationId(relationId);
			userMirrorFissionRecord.setGoodsId(sku.getGoodsId());
			userMirrorFissionRecord.setNum(userMirrorFissionTicketConfig.getNum());
			userMirrorFissionRecord.setRemainNum(userMirrorFissionTicketConfig.getNum());
			userMirrorFissionRecord.setTrialSkuId(userMirrorFissionTicketConfig.getTrialSkuId());
			userMirrorFissionRecord.setCode(RandomUtil.randomString(6));
			userMirrorFissionRecordMapper.insert(userMirrorFissionRecord);
		} catch (DuplicateKeyException e) {
			userMirrorFissionRecord = userMirrorFissionRecordMapper.selectOne(Wrappers.lambdaQuery(UserMirrorFissionRecord.class)
					.in(UserMirrorFissionRecord::getUserId, userIdList)
					.eq(UserMirrorFissionRecord::getRelationId, relationId)
					.eq(UserMirrorFissionRecord::getGoodsId, sku.getGoodsId())
					.last("limit 1"));
		}
		return userMirrorFissionRecord;
	}

	@Override
	public Boolean getPermitStatus(long userId, Long goodsId) throws Exception {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		//特定老用户可进行镜像裂变活动
		UserMirrorFissionUser userMirrorFissionUser = userMirrorFissionUserMapper.selectOne(Wrappers.lambdaQuery(UserMirrorFissionUser.class).
				in(UserMirrorFissionUser::getUserId, userIdList)
				.last("limit 1"));
		if (userMirrorFissionUser == null) {
			return false;
		}
		Number count = beanSearcher.searchCount(RenewalView.class, MapUtils.builder()
				.field(RenewalView::getGoodsId, goodsId)
				.field(RenewalView::getIsMirror, true)
				.field(RenewalView::getUserId, userIdList).op(Operator.InList)
				.field(RenewalView::getExpiryTime, DateTime.now()).op(Operator.GreaterThan)
				.build());
		if (count.intValue() == 0) {
			return false;
		}
		return true;
	}


	public Boolean hasPaidMirrorTicket(long userId, Long goodsId) {
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		Integer count = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
				.in(OrderDon::getUserId, userIdList)
				.notIn(OrderDon::getStatus, Constant.noOrderStatus)
				//未购买 且不是镜像店铺订单
				.apply(String.format("sku_id in (select id from goods_don_sku where goods_id = %s and is_mirror) and not exists (select 1 from user_mirror_shop_order_relate ocr where ocr.order_id = order_don.id)", goodsId)));
		if (count > 0) {
			return true;
		}
		return false;
	}
}
