package com.cyksj.service.mange.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.mapper.*;
import com.cyksj.mapper.codex.CodexUserRenewExpiryRecordMapper;
import com.cyksj.model.entity.*;
import com.cyksj.redis.RedisService;
import com.cyksj.service.claude.ClaudeCodeService;
import com.cyksj.service.codex.CodexService;
import com.cyksj.service.mange.MirrorUserCleatService;
import com.cyksj.service.user.UserBindRelationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 项目名: yhlxj
 * 文件名: MirrorUserCleatServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/6/27 11:15
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MirrorUserCleatServiceImpl implements MirrorUserCleatService {
	private final ChatgptUserMapper chatgptUserMapper;

	private final MidjourneyUserMapper midjourneyUserMapper;

	private final RedisService redisService;

	private final OrderDonRenewRecordMapper orderDonRenewRecordMapper;

	private final GoodsDonSkuMapper skuMapper;

	private final UserBindRelationService userBindRelationService;

	private final UpgradePackageMapper upgradePackageMapper;

	private final GroupsRelationMapper groupsRelationMapper;

	private final GroupsMapper groupsMapper;

	private final ClaudeUserMapper claudeUserMapper;

	private final LumaUserMapper lumaUserMapper;

	private final GrokUserMapper grokUserMapper;

	private final OrderDonUpgradeRenewRecordMapper orderDonUpgradeRenewRecordMapper;

	private final UserTicketClearedRecordMapper userTicketClearedRecordMapper;

	private final ClaudeCodeUserRenewExpiryRecordMapper claudeCodeUserRenewExpiryRecordMapper;

	private final ClaudeCodeUserMapper claudeCodeUserMapper;

	private final ClaudeCodeService claudeCodeService;

	private final OrderDonMapper orderDonMapper;

	private final CodexUserMapper codexUserMapper;

	private final CodexUserRenewExpiryRecordMapper codexUserRenewExpiryRecordMapper;

	private final CodexService codexService;

	/**
	 * 删除镜像User
	 */
	public void delMirrorUser(Long goodsId, Long relationId, Long clearId) {
		String userToken = null;
		//gpt镜像
		if (goodsId != null && goodsId == 18) {
			ChatgptUser user = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
					.eq(ChatgptUser::getRelationId, relationId).last("limit 1"));
			if (user != null) {
				userToken = user.getUserToken();
				chatgptUserMapper.delete(Wrappers.lambdaQuery(ChatgptUser.class)
						.eq(ChatgptUser::getRelationId, relationId));
			}
		}
		//mj镜像
		if (goodsId != null && goodsId == 26) {
			MidjourneyUser user = midjourneyUserMapper.selectOne(Wrappers.lambdaQuery(MidjourneyUser.class)
					.eq(MidjourneyUser::getRelationId, relationId).last("limit 1"));
			if (user != null) {
				userToken = user.getUserToken();
				midjourneyUserMapper.delete(Wrappers.lambdaQuery(MidjourneyUser.class)
						.eq(MidjourneyUser::getRelationId, relationId));
				redisService.del(RedisService.key.MIDJOURNEY_USER.getName() + user.getUserToken());
			}
		}
		//clause pro
		if (goodsId != null && goodsId == 75) {
			ClaudeUser user = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
					.eq(ClaudeUser::getRelationId, relationId).last("limit 1"));
			if (user != null) {
				userToken = user.getUserToken();
				claudeUserMapper.delete(Wrappers.lambdaQuery(ClaudeUser.class)
						.eq(ClaudeUser::getRelationId, relationId));
			}
		}

		//luma
		if (goodsId != null && goodsId == Constant.LUMA_GOODS_ID) {
			LumaUser user = lumaUserMapper.selectOne(Wrappers.lambdaQuery(LumaUser.class)
					.eq(LumaUser::getRelationId, relationId).last("limit 1"));
			if (user != null) {
				userToken = user.getUserToken();
				lumaUserMapper.delete(Wrappers.lambdaQuery(LumaUser.class)
						.eq(LumaUser::getRelationId, relationId));
				redisService.del(RedisService.key.LUMA_NUM_LIMIT.getName() + user.getId());
			}
		}

		//grok
		if (goodsId != null && goodsId == Constant.GROK_GOODS_ID) {
			GrokUser user = grokUserMapper.selectOne(Wrappers.lambdaQuery(GrokUser.class)
					.eq(GrokUser::getRelationId, relationId).last("limit 1"));
			if (user != null) {
				userToken = user.getUserToken();
				grokUserMapper.delete(Wrappers.lambdaQuery(GrokUser.class)
						.eq(GrokUser::getRelationId, relationId));
			}
		}
		if (clearId != null && StrUtil.isNotBlank(userToken)) {
			userTicketClearedRecordMapper.update(null, Wrappers.lambdaUpdate(UserTicketClearedRecord.class)
					.set(UserTicketClearedRecord::getUserToken, userToken)
					.eq(UserTicketClearedRecord::getId, clearId));
		}
	}

	@Override
	public void handleRenewUpgradeOrders(OrderDon orderDon, GoodsDonSku sku) {
		Long goodsId = orderDon.getGoodsId();
		Long orderId = orderDon.getId();
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
		//codex user
		if (goodsId == Constant.CODEX_GOODS_ID) {
			CodexUserRenewExpiryRecord renewExpiryRecord = codexUserRenewExpiryRecordMapper.selectOne(Wrappers.lambdaQuery(CodexUserRenewExpiryRecord.class).eq(CodexUserRenewExpiryRecord::getOrderId, orderId).eq(CodexUserRenewExpiryRecord::getIsValid, Boolean.FALSE).last("limit 1"));
			if (renewExpiryRecord != null) {
				//将续费有效置为过期
				renewExpiryRecord.setIsValid(true);
				codexUserRenewExpiryRecordMapper.updateById(renewExpiryRecord);
			}
			CodexUser codexUser = codexUserMapper.selectOne(Wrappers.lambdaQuery(CodexUser.class)
					.eq(CodexUser::getRelationId, orderDon.getRelationId())
					.last("limit 1"));
			if (codexUser == null) {
				return;
			}
			Long presentRenewSkuId = codexUser.getRenewSkuId();
			if (presentRenewSkuId == null) {
				return;
			}
			GroupsRelation relation = groupsRelationMapper.selectById(orderDon.getRelationId());
			GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
			GoodsDonSku finalSku = skuMapper.selectById(groupsTrips.getSkuId());
			Date renewExpiryTime = null;
			//当前续费订单id
			Long presentUserCodePackageOrderId = codexUser.getRenewOrderId();
			codexUser.setRenewSkuId(null);
			codexUser.setRenewOrderId(null);
			if (renewExpiryRecord != null) {
				//当前续费
				OrderDon presentRenewOrderDon = orderDonMapper.selectById(presentUserCodePackageOrderId);
				//是否存在其他续费升级
				CodexUserRenewExpiryRecord otherRenewRecord = codexUserRenewExpiryRecordMapper.getOtherRenewSku(orderDon.getId(), relation.getId(), userIdList);
				GoodsDonSku otherRenewSku = null;
				if (otherRenewRecord != null) {
					otherRenewSku = skuMapper.selectById(otherRenewRecord.getRenewSkuId());
				}
				//续费升级
				if (otherRenewSku != null) {
					finalSku = otherRenewSku;
					if (otherRenewSku.getDays() != null && otherRenewSku.getDays() > 0) {
						renewExpiryTime = DateUtil.offsetDay(DateTime.now(), otherRenewSku.getDays());
					} else {
						renewExpiryTime = DateUtil.offsetMonth(DateTime.now(), otherRenewSku.getMonths());
					}
					//相差多少天
					Long betDay = 0l;
					if (presentRenewOrderDon != null && presentRenewOrderDon.getCreatedTime().compareTo(otherRenewRecord.getCreatedTime()) > 0) {
						betDay = DateUtil.betweenDay(otherRenewRecord.getCreatedTime(), presentRenewOrderDon.getCreatedTime(), false);
					}
					renewExpiryTime = DateUtil.offsetDay(renewExpiryTime, -betDay.intValue());

					codexUser.setRenewOrderId(otherRenewRecord.getOrderId());
					codexUser.setRenewSkuId(otherRenewRecord.getRenewSkuId());
				}
			}
			//非当前套餐续费订单id 不修改claudeCode
			if (!ObjectUtil.equal(presentUserCodePackageOrderId, orderId)) {
				return;
			}
			//还原镜像user
			codexUser.setOpenaiDailyLimit(finalSku.getOpenaiDailyLimit());
			codexUser.setOpenaiQuota(finalSku.getOpenaiQuota());
			codexUser.setRenewExpiryTime(renewExpiryTime);
			codexUser.setPlanName(finalSku.getSpecVal());
			codexUserMapper.updateById(codexUser);
			log.info("还原镜像codex user套餐成功");
			//调用api更新codex用户信息
			Date expiryTime = relation.getExpiryTime();
			codexService.updateCodexUserPackageInfo(codexUser, expiryTime, finalSku);
			return;
		}

		//claude code user
		if (goodsId == Constant.CLAUDE_CODE_GOODS_ID) {
			ClaudeCodeUserRenewExpiryRecord renewExpiryRecord = claudeCodeUserRenewExpiryRecordMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUserRenewExpiryRecord.class).eq(ClaudeCodeUserRenewExpiryRecord::getOrderId, orderId).eq(ClaudeCodeUserRenewExpiryRecord::getIsValid, Boolean.FALSE).last("limit 1"));
			if (renewExpiryRecord != null) {
				//将续费有效置为过期
				renewExpiryRecord.setIsValid(true);
				claudeCodeUserRenewExpiryRecordMapper.updateById(renewExpiryRecord);
			}
			ClaudeCodeUser claudeCodeUser = claudeCodeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUser.class)
					.eq(ClaudeCodeUser::getRelationId, orderDon.getRelationId())
					.last("limit 1"));
			if (claudeCodeUser == null) {
				return;
			}
			Long presentRenewSkuId = claudeCodeUser.getRenewSkuId();
			if (presentRenewSkuId == null) {
				return;
			}
			GroupsRelation relation = groupsRelationMapper.selectById(orderDon.getRelationId());
			GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
			GoodsDonSku finalSku = skuMapper.selectById(groupsTrips.getSkuId());
			Date renewExpiryTime = null;
			Integer oriClaudeDailyLimit = claudeCodeUser.getClaudeDailyLimit();
			claudeCodeUser.setOriCodePoints(oriClaudeDailyLimit);
			//当前续费订单id
			Long presentUserCodePackageOrderId = claudeCodeUser.getRenewOrderId();
			claudeCodeUser.setRenewSkuId(null);
			claudeCodeUser.setRenewOrderId(null);
			if (renewExpiryRecord != null) {
				//当前续费
				OrderDon presentRenewOrderDon = orderDonMapper.selectById(presentUserCodePackageOrderId);
				//是否存在其他续费升级
				ClaudeCodeUserRenewExpiryRecord otherRenewRecord = claudeCodeUserRenewExpiryRecordMapper.getOtherRenewSku(orderDon.getId(), relation.getId(), userIdList);
				GoodsDonSku otherRenewSku = null;
				if (otherRenewRecord != null) {
					otherRenewSku = skuMapper.selectById(otherRenewRecord.getRenewSkuId());
				}
				//续费升级
				if (otherRenewSku != null) {
					finalSku = otherRenewSku;
					if (otherRenewSku.getDays() != null && otherRenewSku.getDays() > 0) {
						renewExpiryTime = DateUtil.offsetDay(DateTime.now(), otherRenewSku.getDays());
					} else {
						renewExpiryTime = DateUtil.offsetMonth(DateTime.now(), otherRenewSku.getMonths());
					}
					//相差多少天
					Long betDay = 0l;
					if (presentRenewOrderDon != null && presentRenewOrderDon.getCreatedTime().compareTo(otherRenewRecord.getCreatedTime()) > 0) {
						betDay = DateUtil.betweenDay(otherRenewRecord.getCreatedTime(), presentRenewOrderDon.getCreatedTime(), false);
					}
					renewExpiryTime = DateUtil.offsetDay(renewExpiryTime, -betDay.intValue());

					claudeCodeUser.setRenewOrderId(otherRenewRecord.getOrderId());
					claudeCodeUser.setRenewSkuId(otherRenewRecord.getRenewSkuId());
				}
			}
			//非当前套餐续费订单id 不修改claudeCode
			if (!ObjectUtil.equal(presentUserCodePackageOrderId, orderId)) {
				return;
			}
			//还原镜像user
			claudeCodeUser.setClaudeDailyLimit(finalSku.getClaudeDailyLimit());
			claudeCodeUser.setClaudeQuota(finalSku.getClaudeQuota());
			claudeCodeUser.setRenewExpiryTime(renewExpiryTime);
			claudeCodeUser.setPlanName(finalSku.getSpecVal());
			claudeCodeUserMapper.updateById(claudeCodeUser);
			log.info("还原镜像claude code user套餐成功");
			//调用api更新claude code用户信息
			Date expiryTime = relation.getExpiryTime();
			claudeCodeService.updateClaudeCodeUserPackageInfo(claudeCodeUser, expiryTime, finalSku);
			return;
		}
		OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
				.eq(OrderDonRenewRecord::getOrderId, orderId)
				.eq(OrderDonRenewRecord::getIsValid, Boolean.FALSE)
				.last("limit 1"));
		if (orderDonRenewRecord == null) {
			return;
		}
		//将续费有效置为过期
		orderDonRenewRecord.setIsValid(true);
		orderDonRenewRecordMapper.updateById(orderDonRenewRecord);
		//Claude pro
		if (orderDon.getGoodsId() == 75) {
			ClaudeUser claudeUser = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
					.eq(ClaudeUser::getRelationId, orderDon.getRelationId())
					.last("limit 1"));
			if (claudeUser == null) {
				return;
			}
			Long presentRenewSkuId = claudeUser.getRenewSkuId();
			if (presentRenewSkuId == null) {
				return;
			}
			GroupsRelation relation = groupsRelationMapper.selectById(orderDon.getRelationId());
			GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
			GoodsDonSku finalSku = skuMapper.selectById(groupsTrips.getSkuId());
			//是否存在其他续费升级
			OrderDon otherRenewOrderDon = orderDonRenewRecordMapper.getOtherRenewSku(orderDon.getId(), relation.getId(), userIdList);
			GoodsDonSku otherRenewSku = null;
			if (otherRenewOrderDon != null) {
				otherRenewSku = skuMapper.selectById(otherRenewOrderDon.getSkuId());
			}
			Date renewExpiryTime = null;
			//当前续费订单id
			Long presentUserCodePackageOrderId = claudeUser.getRenewOrderId();
			claudeUser.setRenewSkuId(null);
			claudeUser.setRenewOrderId(null);
			//续费升级
			if (otherRenewSku != null) {
				finalSku = otherRenewSku;
				log.info("claude pro 续费升级订单退款,relation_id:{}存在次级续费升级订单", orderDon.getUserId());
				Date payTime = Optional.ofNullable(otherRenewOrderDon.getPayTime()).orElse(otherRenewOrderDon.getCreatedTime());
				renewExpiryTime = DateUtil.offsetMonth(payTime, otherRenewSku.getMonths());
				//同规格不处理
				if (!ObjectUtil.equal(otherRenewOrderDon.getSkuId(), orderDon.getSkuId())) {
					//相差多少天
					Long betDay = DateUtil.betweenDay(otherRenewOrderDon.getCreatedTime(), orderDon.getCreatedTime(), false);
					renewExpiryTime = DateUtil.offsetDay(renewExpiryTime, -betDay.intValue());
				}
				claudeUser.setRenewOrderId(otherRenewOrderDon.getId());
				claudeUser.setRenewSkuId(otherRenewOrderDon.getSkuId());
			}
			//非当前套餐续费订单id 不修改user
			if (!ObjectUtil.equal(presentUserCodePackageOrderId, orderId)) {
				return;
			}
			//还原镜像user
			claudeUser.setLimitTime(finalSku.getGptLimitTime());
			claudeUser.setLimitNum(finalSku.getGptLimitNum());
			claudeUser.setRenewExpiryTime(renewExpiryTime);
			claudeUserMapper.updateById(claudeUser);
			log.info("还原镜像claude user套餐成功");
			return;
		}

		if (orderDon.getGoodsId() == 18) {
			ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
					.eq(ChatgptUser::getRelationId, orderDon.getRelationId())
					.last("limit 1"));
			if (chatgptUser == null) {
				return;
			}
			Long presentRenewSkuId = chatgptUser.getRenewSkuId();
			if (presentRenewSkuId == null) {
				return;
			}
			GroupsRelation relation = groupsRelationMapper.selectById(orderDon.getRelationId());
			GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
			GoodsDonSku finalSku = skuMapper.selectById(groupsTrips.getSkuId());
			//是否存在其他续费升级
			OrderDon otherRenewOrderDon = orderDonRenewRecordMapper.getOtherRenewSku(orderDon.getId(), relation.getId(), userIdList);
			GoodsDonSku otherRenewSku = null;
			if (otherRenewOrderDon != null) {
				otherRenewSku = skuMapper.selectById(otherRenewOrderDon.getSkuId());
			}
			GoodsDonSku upgradeOrderDonSku = null;
			Date renewExpiryTime = null;
			//是否存在套餐升级包
			Long packageId = chatgptUser.getPackageId();
			if (packageId != null && packageId != 0) {
				UpgradePackage upgradePackage = upgradePackageMapper.selectById(chatgptUser.getPackageId());
				Long upgradeOrderDonSkuId = upgradePackage.getUpgradeSkuId();
				upgradeOrderDonSku = skuMapper.selectById(upgradeOrderDonSkuId);
			}
			//套餐升级
			if (upgradeOrderDonSku != null) {
				log.info("GPT续费升级订单退款,relation_id:{}存在套餐升级", orderDon.getUserId());
				finalSku = upgradeOrderDonSku;
			}
			//当前续费订单id
			Long presentUserCodePackageOrderId = chatgptUser.getRenewOrderId();
			chatgptUser.setRenewSkuId(null);
			chatgptUser.setRenewOrderId(null);
			//续费升级
			if (otherRenewSku != null) {
				finalSku = otherRenewSku;
				log.info("GPT续费升级订单退款,relation_id:{}存在次级续费升级订单", orderDon.getUserId());
				if (upgradeOrderDonSku != null) {
					//套餐升级高于其他续费升级
					if (upgradeOrderDonSku.getMonths() >= otherRenewSku.getMonths() && upgradeOrderDonSku.getGptLimitNum() >= otherRenewSku.getGptLimitNum() && upgradeOrderDonSku.getGptLimitTime() <= otherRenewSku.getGptLimitTime()) {
						log.info("GPT续费升级订单退款,relation_id:{}存在更高级套餐升级", orderDon.getUserId());
						finalSku = upgradeOrderDonSku;
					}
				}
				Date payTime = Optional.ofNullable(otherRenewOrderDon.getPayTime()).orElse(otherRenewOrderDon.getCreatedTime());
				renewExpiryTime = DateUtil.offsetMonth(payTime, otherRenewSku.getMonths());
				//同规格不处理
				if (!ObjectUtil.equal(otherRenewOrderDon.getSkuId(), orderDon.getSkuId())) {
					//相差多少天
					Long betDay = DateUtil.betweenDay(otherRenewOrderDon.getCreatedTime(), orderDon.getCreatedTime(), false);
					renewExpiryTime = DateUtil.offsetDay(renewExpiryTime, -betDay.intValue());
				}
				chatgptUser.setRenewOrderId(otherRenewOrderDon.getId());
				chatgptUser.setRenewSkuId(otherRenewOrderDon.getSkuId());
			}
			//非当前套餐续费订单id 不修改user
			if (!ObjectUtil.equal(presentUserCodePackageOrderId, orderId)) {
				return;
			}
			//还原镜像user
			chatgptUser.setLimitTime(finalSku.getGptLimitTime());
			chatgptUser.setLimitNum(finalSku.getGptLimitNum());
			chatgptUser.setDsLimitNum(finalSku.getDsLimitNum());
			chatgptUser.setDsLimitTime(finalSku.getDsLimitTime());
			chatgptUser.setOtherLimitNum(finalSku.getOtherLimitNum());
			chatgptUser.setOtherLimitTime(finalSku.getOtherLimitTime());
			chatgptUser.setRenewExpiryTime(renewExpiryTime);
			chatgptUserMapper.updateById(chatgptUser);
			log.info("还原镜像gptuser套餐成功");

			if (orderDon.getOrderType() == 2) {
				//退款续费 套餐升级订单
				handleGptMirrorRenewOrderRefund(orderDon, sku);
			}
		}
	}

	/**
	 * 镜像续费订单退款 清除user额外功能时间
	 */
	private void handleGptMirrorRenewOrderRefund(OrderDon orderDon, GoodsDonSku sku) {
		Long id = orderDon.getId();
		OrderDonUpgradeRenewRecord orderDonUpgradeRenewRecord = orderDonUpgradeRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonUpgradeRenewRecord.class)
				.eq(OrderDonUpgradeRenewRecord::getOrderId, id)
				.last("limit 1"));
		ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
				.eq(ChatgptUser::getRelationId, orderDon.getRelationId())
				.last("limit 1"));
		if (chatgptUser == null) {
			return;
		}
		if (orderDonUpgradeRenewRecord != null) {
			Date clearPackageTime = chatgptUser.getClearPackageTime();
			clearPackageTime = DateUtil.offsetMonth(clearPackageTime, -sku.getMonths());
			log.info("GPT镜像续费订单退款,user清除套餐升级过期时间:{} ---> {}", chatgptUser.getClearPackageTime(), clearPackageTime);
			chatgptUser.setClearPackageTime(clearPackageTime);
			chatgptUserMapper.updateById(chatgptUser);
		}
	}
}
