package com.dora.util;

import com.dora.mapper.GiftCodeUsageMapper;
import com.dora.mapper.OrderMapper;
import com.dora.mapper.UserMapper;
import com.dora.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 会员类型判断工具类
 * 用于区分兑换会员、付费会员等不同类型的会员
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MembershipUtil {

    private final GiftCodeUsageMapper giftCodeUsageMapper;
    private final OrderMapper orderMapper;
    private final UserMapper userMapper;

    /**
     * 判断用户是否为不参与收益分成的会员类型
     * 包括：纯兑换会员、赠送会员
     * 
     * @param userId 用户ID
     * @return true-不参与收益，false-可以参与收益
     */
    public boolean isExchangeMemberWithoutRevenue(Long userId) {
        if (userId == null) {
            return false;
        }

        try {
            // 1. 检查用户是否有兑换会员的记录（type=2表示会员卡）
            boolean hasExchangeRecord = giftCodeUsageMapper.countByUserAndType(userId, 2) > 0;
            
            // 2. 检查用户是否有付费记录（status=1表示支付成功的订单）
            boolean hasPaidOrder = orderMapper.countSuccessOrdersByUserId(userId) > 0;
            
            if (hasExchangeRecord && !hasPaidOrder) {
                // 有兑换记录但没有付费记录，是纯兑换会员，不参与收益
                log.info("用户是纯兑换会员，不参与收益分成 - userId: {}", userId);
                return true;
            }
            
            // 3. 检查是否为赠送会员（注册2天内的VIP用户且无付费和兑换记录）
            if (isGiftMember(userId)) {
                log.info("用户是赠送会员，不参与收益分成 - userId: {}", userId);
                return true;
            }
            
            // 其他情况可以参与收益
            return false;

        } catch (Exception e) {
            log.error("检查用户会员类型失败，默认允许参与收益 - userId: {}", userId, e);
            // 异常情况下默认允许参与收益，避免影响业务
            return false;
        }
    }

    /**
     * 判断用户是否为赠送会员
     * 赠送会员：注册2天内的VIP用户，且没有付费记录和兑换记录
     * 
     * @param userId 用户ID
     * @return true-是赠送会员，false-不是赠送会员
     */
    public boolean isGiftMember(Long userId) {
        if (userId == null) {
            return false;
        }

        try {
            // 获取用户信息
            User user = userMapper.selectById(userId);
            if (user == null || user.getRole() <= 1) {
                return false; // 用户不存在或不是VIP
            }

            // 检查是否有兑换记录
            boolean hasExchangeRecord = giftCodeUsageMapper.countByUserAndType(userId, 2) > 0;
            if (hasExchangeRecord) {
                return false; // 有兑换记录，不是赠送会员
            }

            // 检查是否有付费记录
            boolean hasPaidOrder = orderMapper.countSuccessOrdersByUserId(userId) > 0;
            if (hasPaidOrder) {
                return false; // 有付费记录，不是赠送会员
            }

            // 检查创建时间是否在2天内
            LocalDateTime twoDaysAgo = LocalDateTime.now().minusDays(2);
            boolean isWithin2Days = user.getCreateTime() != null && 
                                   user.getCreateTime().isAfter(twoDaysAgo);

            if (isWithin2Days) {
                log.debug("用户是赠送会员 - userId: {}, createTime: {}", userId, user.getCreateTime());
                return true;
            }

            return false;

        } catch (Exception e) {
            log.error("检查赠送会员状态失败 - userId: {}", userId, e);
            return false;
        }
    }

    /**
     * 获取用户会员类型描述（用于日志）
     * 
     * @param userId 用户ID
     * @return 会员类型描述
     */
    public String getMembershipTypeDescription(Long userId) {
        if (userId == null) {
            return "非会员";
        }

        try {
            // 获取用户信息
            User user = userMapper.selectById(userId);
            if (user == null || user.getRole() <= 1) {
                return "非会员";
            }

            boolean hasExchangeRecord = giftCodeUsageMapper.countByUserAndType(userId, 2) > 0;
            boolean hasPaidOrder = orderMapper.countSuccessOrdersByUserId(userId) > 0;

            if (hasExchangeRecord && hasPaidOrder) {
                return "兑换后付费会员";
            } else if (hasExchangeRecord && !hasPaidOrder) {
                return "纯兑换会员";
            } else if (!hasExchangeRecord && hasPaidOrder) {
                return "付费会员";
            } else {
                // 没有兑换记录也没有付费记录，但是VIP用户，检查是否为赠送会员
                LocalDateTime twoDaysAgo = LocalDateTime.now().minusDays(2);
                boolean isWithin2Days = user.getCreateTime() != null && 
                                       user.getCreateTime().isAfter(twoDaysAgo);
                
                if (isWithin2Days) {
                    return "赠送会员";
                } else {
                    return "非会员"; // 2天外的VIP但无任何记录，可能是数据异常
                }
            }

        } catch (Exception e) {
            log.error("获取用户会员类型描述失败 - userId: {}", userId, e);
            return "未知类型";
        }
    }
}
