package com.cyksj.service.relation.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.mapper.*;
import com.cyksj.mapper.claudecode.OAuthTokenMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.manage.views.GroupsRelationView;
import com.cyksj.service.claude.ClaudeCodeService;
import com.cyksj.service.mange.MirrorUserCleatService;
import com.cyksj.service.relation.GroupRelationClearService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/*
 *项目名: netflix
 *文件名: GroupRelationClearServiceImpl
 *创建者: JavaZou
 *创建时间:2023/2/23 15:31
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GroupRelationClearServiceImpl implements GroupRelationClearService {
	private final GroupsRelationMapper groupsRelationMapper;

	private final GroupsMapper groupsMapper;

	private final BeanSearcher beanSearcher;

	private final UserTicketClearedRecordMapper userTicketClearedRecordMapper;

	private final GoodsDonSkuMapper goodsDonSkuMapper;

	private final MirrorUserCleatService mirrorUserCleatService;

	private final ClaudeCodeService claudeCodeService;

	private final ClaudeCodeUserMapper claudeCodeUserMapper;

	private final OAuthTokenMapper oAuthTokenMapper;

	private final NanoUserQuotaMapper nanoUserQuotaMapper;

	private final CodexUserMapper codexUserMapper;

	@Override
	public void clearTicket(GroupsRelation relation, UserTicketClearedRecord.Source source) {
		Long relationId = relation.getId();
		Long newRelationId = relation.getNewRelationId();
		Integer num = relation.getNum();
		final GroupsRelation.Status relationStatus = relation.getStatus();
		//记录用户被清除车票历史记录
		GroupsRelationView groupsRelation = beanSearcher.searchFirst(GroupsRelationView.class,
				MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
		if (groupsRelation != null) {
			Long userId = relation.getUserId();
			Date startTime = relation.getStartTime();
			Date expireTime = relation.getExpiryTime();
			relation.setStartTime(null);
			relation.setExpiryTime(null);
			relation.setUserId(0l);
//			Boolean isFlag = false;
//			//非chatGpt独立会员规格车队
//			if (!groupsRelation.getSkuId().equals(177l)) {
//				relation.setUserId(0l);
//				isFlag = true;
//			}
			if (relationStatus != GroupsRelation.Status.outside) {
				relation.setStatus(GroupsRelation.Status.none);
			}
			relation.setIsHandle(false);
			relation.setRenewStatus(false);
			relation.setAccount(null);
			Integer success = groupsRelationMapper.updateExpiryTime(relation, expireTime);
			if (success == 1) {
				//2023-06-07 GPT账号座位大于20
				if (relationStatus != GroupsRelation.Status.outside) {
					log.info("开始清除过期子账号,座位号:{}", relation.getId());
					int count = groupsMapper.incrAvailableNum(relation.getGroupsId());
					if (count == 0) {
						log.error("车位异常 groupId:{}", relation.getGroupsId());
						groupsMapper.updateAvailableNum(relation.getGroupsId());
					}
				}
				UserTicketClearedRecord userTicketClearedRecord = new UserTicketClearedRecord();
				userTicketClearedRecord.setAccountId(groupsRelation.getAccountId());
				userTicketClearedRecord.setAccount(groupsRelation.getTripsAccount());
				userTicketClearedRecord.setRelationId(relationId);
				userTicketClearedRecord.setNum(num);
				userTicketClearedRecord.setUserId(userId);
				userTicketClearedRecord.setSource(source);
				if (groupsRelation.getGoodsId() == null) {
					GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(groupsRelation.getSkuId());
					if (goodsDonSku != null) {
						groupsRelation.setGoodsId(goodsDonSku.getGoodsId());
					}
				}
				userTicketClearedRecord.setGoodsId(groupsRelation.getGoodsId());
				userTicketClearedRecord.setSkuId(groupsRelation.getSkuId());
				userTicketClearedRecord.setStartTime(startTime);
				userTicketClearedRecord.setExpiryTime(expireTime);
				userTicketClearedRecord.setNewRelationId(newRelationId);
				userTicketClearedRecord.setYhsId(groupsRelation.getYhsId());
				if (source != UserTicketClearedRecord.Source.self) {
					userTicketClearedRecord.setDeleted(false);
				}
				userTicketClearedRecordMapper.insert(userTicketClearedRecord);
//				if (!isFlag) {
//					//清除之前规格的车队
//					groupService.close(groupsRelation.getGroupsId());
//					if (groupsRelation.getAccountId() != null) {
//						//生成10人月付新规格车队
//						Account account = accountService.getById(groupsRelation.getAccountId());
//						account.setSkuId(161l);
//						accountService.updateById(account);
//						GroupsTrips gt = new GroupsTrips();
//						gt.setSkuId(account.getSkuId());
//						gt.setAccountId(account.getId());
//						groupService.issuance(gt, null);
//
//						GroupsTripsDeleteRecord record = new GroupsTripsDeleteRecord();
//						record.setAccountId(gt.getAccountId());
//						record.setAccount(gt.getAccount());
//						record.setBeforeGroupsId(groupsRelation.getId());
//						record.setBeforeSkuId(groupsRelation.getSkuId());
//						record.setAfterGroupsId(gt.getId());
//						record.setAfterSkuId(gt.getSkuId());
//						groupsTripsDeleteRecordMapper.insert(record);
//						log.info("ChatGPT 独立会员账号车票过期,删除原先车队id:{}并生成一个10人月付规格的车队id:{}", groupsRelation.getId(), gt.getId());
//					}
//				}
				if (source != UserTicketClearedRecord.Source.vip_deduct) {
					mirrorUserCleatService.delMirrorUser(groupsRelation.getGoodsId(), groupsRelation.getId(), userTicketClearedRecord.getId());
				}
				//claude code
				if (groupsRelation.getGoodsId() != null && groupsRelation.getGoodsId() == Constant.CLAUDE_CODE_GOODS_ID) {
					//用户失效 车票用户id
					claudeCodeService.invalidateUserCache(groupsRelation.getUserId());
					//删除用户套餐
					claudeCodeService.delUserPackages(groupsRelation.getUserId());
					//清除claude code user
					claudeCodeUserMapper.delete(Wrappers.lambdaQuery(ClaudeCodeUser.class).eq(ClaudeCodeUser::getRelationId, relationId));
					//清除claude code tokens
					oAuthTokenMapper.delete(Wrappers.lambdaQuery(OAuthToken.class).eq(OAuthToken::getUserId, userId));
					//清除codex
					codexUserMapper.delete(Wrappers.lambdaQuery(CodexUser.class).eq(CodexUser::getRelationId, relationId));
				}
				//nano
				if (source != UserTicketClearedRecord.Source.vip_deduct && groupsRelation.getGoodsId() != null && groupsRelation.getGoodsId() == Constant.NANO_GOODS_ID) {
					nanoUserQuotaMapper.delete(Wrappers.lambdaQuery(NanoUserQuota.class).eq(NanoUserQuota::getRelationId, relationId));
				}

				//codex
				if (groupsRelation.getGoodsId() != null && groupsRelation.getGoodsId() == Constant.CODEX_GOODS_ID) {
					//清除codex
					codexUserMapper.delete(Wrappers.lambdaQuery(CodexUser.class).eq(CodexUser::getRelationId, relationId));
				}
			}
		}
	}

	@Override
	public void clearRenewGroupRelation(GroupsRelation relation) {
		Date expireTime = relation.getExpiryTime();
		relation.setStartTime(null);
		relation.setExpiryTime(null);
		relation.setUserId(0l);
		relation.setStatus(GroupsRelation.Status.none);
		relation.setIsHandle(false);
		relation.setRenewStatus(false);
		relation.setAccount(null);
		Integer success = groupsRelationMapper.updateExpiryTime(relation, expireTime);
		if (success == 1) {
			log.info("续费后更换车票,座位号:{}", relation.getId());
			int count = groupsMapper.incrAvailableNum(relation.getGroupsId());
			if (count == 0) {
				groupsMapper.updateAvailableNum(relation.getGroupsId());
				log.error("续费更换车位异常 groupId:{}", relation.getGroupsId());
			}
		}
	}
}
