package com.cyksj.service.spotify.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.snowflake.Sequence;
import com.cyksj.mapper.*;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.SpotifyUpgradeInfoReq;
import com.cyksj.model.request.SpotifyUpgradeOrderReq;
import com.cyksj.service.spotify.SpotifyUserUpgradeOrderService;
import com.cyksj.service.user.UserBindRelationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 项目名: yhlxj
 * 文件名: SpotifyUserUpgradeOrderServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/12/3 15:40
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SpotifyUserUpgradeOrderServiceImpl implements SpotifyUserUpgradeOrderService {
	private final SpotifyUserUpgradeOrderMapper spotifyUserUpgradeOrderMapper;

	private final GroupsRelationMapper relationMapper;

	private final UserBindRelationService userBindRelationService;

	private final GroupsMapper groupsMapper;

	private final GoodsDonSkuMapper skuMapper;

	private final static Sequence SEQUENCE = new Sequence(0);

	private final SysConfigMapper sysConfigMapper;

	private final SpotifyUserUpgradeSubmitRecordMapper spotifyUserUpgradeSubmitRecordMapper;

	private final OrderDonMapper orderDonMapper;

	@Override
	public SpotifyUserUpgradeOrder upgradeSubmit(SpotifyUpgradeOrderReq spotifyUpgradeOrderReq) {
		Long userId = spotifyUpgradeOrderReq.getUserId();
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		Long relationId = spotifyUpgradeOrderReq.getRelationId();

		GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getId, relationId).in(GroupsRelation::getUserId, userIdList).eq(GroupsRelation::getStatus, GroupsRelation.Status.validity));
		if (relation == null) {
			throw BusinessRuntimeException.getInstance("车票已过期");
		}
		GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
		GoodsDonSku sku = skuMapper.selectById(groupsTrips.getSkuId());
		if (sku.getGoodsId() != Constant.SPOTIFY_GOODS_ID) {
			throw BusinessRuntimeException.getInstance("暂只支持spotify车票");
		}
		SpotifyUserUpgradeOrder order = spotifyUserUpgradeOrderMapper.selectOne(Wrappers.lambdaQuery(SpotifyUserUpgradeOrder.class).eq(SpotifyUserUpgradeOrder::getRelationId, relationId).in(SpotifyUserUpgradeOrder::getUserId, userIdList).eq(SpotifyUserUpgradeOrder::getStatus, SpotifyUserUpgradeOrder.Status.noPayment).last("limit 1"));
		if (order == null) {
			order = new SpotifyUserUpgradeOrder();
		}
		order.setUserId(userId);
		order.setGoodsId(sku.getGoodsId());
		order.setSkuId(sku.getId());
		order.setOrderNo(SEQUENCE.nextId().toString());
		order.setStatus(SpotifyUserUpgradeOrder.Status.noPayment);
		order.setRelationId(relationId);

		OrderDon relateOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
				.in(OrderDon::getUserId, userIdList)
				.eq(OrderDon::getRelationId, relationId)
				.notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
				.orderByDesc(OrderDon::getId)
				.last("limit 1"));
		if (relateOrder != null) {
			order.setRelateOrderNo(relateOrder.getOrderNo());
		}
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, Constant.SPOTIFY_UPGRADE_PRICE_KEY).last("limit 1"));
		order.setMoney(BigDecimal.valueOf(Long.parseLong(sysConfig.getSysValue())));
		if (order.getId() == null) spotifyUserUpgradeOrderMapper.insert(order);
		else spotifyUserUpgradeOrderMapper.updateById(order);
		return order;
	}

	@Override
	public void submitUpgradeInfo(SpotifyUpgradeInfoReq spotifyUpgradeInfoReq) {
		Long relationId = spotifyUpgradeInfoReq.getRelationId();
		Assert.notNull(relationId, "参数错误");
		String account = spotifyUpgradeInfoReq.getAccount();
		if (StrUtil.isEmpty(account) || account.length() > 64) {
			throw BusinessRuntimeException.getInstance("请输入正确的账号信息");
		}
		String password = spotifyUpgradeInfoReq.getPassword();
		if (StrUtil.isEmpty(password) || password.length() > 64) {
			throw BusinessRuntimeException.getInstance("请输入正确的账号信息");
		}
		String email = spotifyUpgradeInfoReq.getEmail();
		if (!Validator.isEmail(email)) {
			throw BusinessRuntimeException.getInstance("请输入正确的邮箱");
		}
		Long userId = spotifyUpgradeInfoReq.getUserId();
		List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
		SpotifyUserUpgradeOrder order = spotifyUserUpgradeOrderMapper.selectOne(Wrappers.lambdaQuery(SpotifyUserUpgradeOrder.class)
				.eq(SpotifyUserUpgradeOrder::getRelationId, relationId)
				.in(SpotifyUserUpgradeOrder::getUserId, userIdList)
				.eq(SpotifyUserUpgradeOrder::getStatus, SpotifyUserUpgradeOrder.Status.hasPayment));
		if (order == null) {
			throw BusinessRuntimeException.getInstance("订单不存在");
		}
		Long orderId = order.getId();
		SpotifyUserUpgradeSubmitRecord upgradeSubmitRecord = Optional.ofNullable(spotifyUserUpgradeSubmitRecordMapper.selectOne(Wrappers.lambdaQuery(SpotifyUserUpgradeSubmitRecord.class)
				.eq(SpotifyUserUpgradeSubmitRecord::getOrderId, orderId)
				.last("limit 1"))).orElse(new SpotifyUserUpgradeSubmitRecord());
		if (upgradeSubmitRecord.getStatus() != null && upgradeSubmitRecord.getStatus() != SpotifyUserUpgradeSubmitRecord.Status.fail) {
			throw BusinessRuntimeException.getInstance("您已提交记录");
		}
		try {
			upgradeSubmitRecord.setUserId(order.getUserId());
			upgradeSubmitRecord.setAccount(account);
			upgradeSubmitRecord.setPassword(password);
			upgradeSubmitRecord.setEmail(email);
			upgradeSubmitRecord.setStatus(SpotifyUserUpgradeSubmitRecord.Status.waiting);
			upgradeSubmitRecord.setOrderId(orderId);
			upgradeSubmitRecord.setRelationId(order.getRelationId());
			if (upgradeSubmitRecord.getId() == null) {
				spotifyUserUpgradeSubmitRecordMapper.insert(upgradeSubmitRecord);
			} else spotifyUserUpgradeSubmitRecordMapper.updateById(upgradeSubmitRecord);
		} catch (DuplicateKeyException e) {

		}
	}
}
