package com.cyksj.service.mange.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.mapper.*;
import com.cyksj.model.entity.*;
import com.cyksj.redis.RedisService;
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 OrderDonUpgradeRenewRecordMapper orderDonUpgradeRenewRecordMapper;

	@Override
	public void delMirrorUser(Long goodsId, Long relationId) {
		//gpt镜像
		if (goodsId != null && goodsId == 18) {
			Integer selectCount = chatgptUserMapper.selectCount(Wrappers.lambdaQuery(ChatgptUser.class)
					.eq(ChatgptUser::getRelationId, relationId));
			if (selectCount > 0) {
				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) {
				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) {
				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) {
				lumaUserMapper.delete(Wrappers.lambdaQuery(LumaUser.class)
						.eq(LumaUser::getRelationId, relationId));
				redisService.del(RedisService.key.LUMA_NUM_LIMIT.getName() + user.getId());
			}
		}
	}

	@Override
	public void handleRenewUpgradeOrders(OrderDon orderDon, GoodsDonSku sku) {
		Long orderId = orderDon.getId();
		OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
				.eq(OrderDonRenewRecord::getOrderId, orderId)
				.last("limit 1"));
		if (orderDonRenewRecord == null) {
			return;
		}
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
		//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;
			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());
				claudeUser.setRenewOrderId(otherRenewOrderDon.getId());
				claudeUser.setRenewSkuId(otherRenewOrderDon.getSkuId());
			}
			//还原镜像user
			claudeUser.setLimitTime(finalSku.getGptLimitTime());
			claudeUser.setLimitNum(finalSku.getGptLimitNum());
			claudeUser.setRenewExpiryTime(renewExpiryTime);
			claudeUserMapper.updateById(claudeUser);
			log.info("还原镜像claude user套餐成功");
			//将续费有效置为过期
			orderDonRenewRecord.setIsValid(true);
			orderDonRenewRecordMapper.updateById(orderDonRenewRecord);
			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;
			}
			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());
				chatgptUser.setRenewOrderId(otherRenewOrderDon.getId());
				chatgptUser.setRenewSkuId(otherRenewOrderDon.getSkuId());
			}
			//还原镜像user
			chatgptUser.setLimitTime(finalSku.getGptLimitTime());
			chatgptUser.setLimitNum(finalSku.getGptLimitNum());
			chatgptUser.setRenewExpiryTime(renewExpiryTime);
			chatgptUserMapper.updateById(chatgptUser);
			log.info("还原镜像gptuser套餐成功");

			//将续费有效置为过期
			orderDonRenewRecord.setIsValid(true);
			orderDonRenewRecordMapper.updateById(orderDonRenewRecord);

			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);
		}
	}
}
