package shop.alien.gateway.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.ActivityInviteConfig;
import shop.alien.entity.store.ActivityInviteLog;
import shop.alien.entity.store.LifeUser;
import shop.alien.gateway.service.ActivityInviteConfigService;
import shop.alien.gateway.service.UserPointService;
import shop.alien.mapper.ActivityInviteConfigMapper;
import shop.alien.mapper.ActivityInviteLogMapper;
import shop.alien.mapper.LifeUserMapper;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ActivityInviteConfigServiceImpl extends ServiceImpl<ActivityInviteConfigMapper, ActivityInviteConfig> implements ActivityInviteConfigService {

    private final UserPointService userPointService;

    private final ActivityInviteConfigMapper activityInviteConfigMapper;

    private final LifeUserMapper lifeUserMapper;

    private final ActivityInviteLogMapper activityInviteLogMapper;


    @Override
    public String bindInviteCode(Integer invitedUserId, String inviteCode) {
        if (StringUtils.isNotBlank(inviteCode) && invitedUserId != null) {
            // 根据邀请码查询邀请用户
            LambdaQueryWrapper<LifeUser> lifeUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            lifeUserLambdaQueryWrapper.eq(LifeUser::getDeleteFlag, 0);
            lifeUserLambdaQueryWrapper.apply("BINARY invite_code = {0}", inviteCode);
            List<LifeUser> lifeUserList = lifeUserMapper.selectList(lifeUserLambdaQueryWrapper);
            if (CollectionUtils.isEmpty(lifeUserList)) {
                return "邀请码异常或邀请用户已注销";
            }
            LifeUser originalLifeUser = lifeUserList.get(0);
            int inviteUserId = originalLifeUser.getId();
            LifeUser invitedLifeUser = lifeUserMapper.selectById(invitedUserId);
            if (invitedLifeUser == null) {
                return "被邀请用户异常";
            } else if (StringUtils.isNotBlank(invitedLifeUser.getBindInviteCode())) {
                return "已经绑定邀请码不能重复绑定";
            } else if (StringUtils.isNotBlank(invitedLifeUser.getInviteCode()) && invitedLifeUser.getInviteCode().equals(inviteCode)) {
                return "不能绑定自己的邀请码";
            } else {
                LambdaQueryWrapper<ActivityInviteConfig> activityInviteConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
                activityInviteConfigLambdaQueryWrapper.eq(ActivityInviteConfig::getDeleteFlag, 0);
                List<ActivityInviteConfig> activityInviteConfigList = activityInviteConfigMapper.selectList(activityInviteConfigLambdaQueryWrapper);
                if (CollectionUtils.isNotEmpty(activityInviteConfigList)) {
                    ActivityInviteConfig activityInviteConfig = activityInviteConfigList.get(0);

                    // 判断是否达到当天邀请最大次数
                    Integer maxInviteNum = activityInviteConfig.getMaxInviteNum();
                    if (maxInviteNum != null) {
                        LambdaQueryWrapper<ActivityInviteLog> activityInviteLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        activityInviteLogLambdaQueryWrapper.eq(ActivityInviteLog::getInviteUserId, inviteUserId);
                        activityInviteLogLambdaQueryWrapper.eq(ActivityInviteLog::getDeleteFlag, 0);
                        // 使用 Date 对象而不是字符串，确保类型匹配
                        LocalDate today = LocalDate.now();
                        LocalDateTime startOfDay = today.atStartOfDay();
                        LocalDateTime endOfDay = today.atTime(23, 59, 59);
                        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
                        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
                        activityInviteLogLambdaQueryWrapper.between(ActivityInviteLog::getInviteTime, startDate, endDate);
                        int todayInviteCount = activityInviteLogMapper.selectCount(activityInviteLogLambdaQueryWrapper);
                        if (todayInviteCount > maxInviteNum) {
                            return "绑定数量已超过当天最大绑定数量";
                        }
                    }

                    ActivityInviteLog activityInviteLog = new ActivityInviteLog();
                    activityInviteLog.setInviteUserId(inviteUserId);
                    activityInviteLog.setInvitedUserId(invitedUserId);
                    activityInviteLog.setActivityId(activityInviteConfig.getId());

                    // 邀请奖励
                    activityInviteLog.setInviteRewardType(activityInviteConfig.getInviteRewardType());
                    activityInviteLog.setInviteRewardCoupon(activityInviteConfig.getInviteRewardCoupon());
                    activityInviteLog.setInviteRewardPoint(activityInviteConfig.getInviteRewardPoint());
                    // 被邀请奖励
                    activityInviteLog.setInvitedRewardType(activityInviteConfig.getInvitedRewardType());
                    activityInviteLog.setInvitedRewardCoupon(activityInviteConfig.getInvitedRewardCoupon());
                    activityInviteLog.setInvitedRewardPoint(activityInviteConfig.getInvitedRewardPoint());
                    activityInviteLog.setInviteTime(Date.from(Instant.now()));
                    activityInviteLogMapper.insert(activityInviteLog);

                    if (activityInviteConfig.getInviteRewardType() == 2) {
                        userPointService.addPoint(inviteUserId, activityInviteConfig.getInviteRewardPoint());
                    }
                    if (activityInviteConfig.getInvitedRewardType() == 2) {
                        userPointService.addPoint(invitedUserId, activityInviteConfig.getInvitedRewardPoint());
                    }
                    LifeUser updateLifeUser = new LifeUser();
                    updateLifeUser.setId(invitedLifeUser.getId());
                    updateLifeUser.setBindInviteCode(inviteCode);
                    lifeUserMapper.updateById(updateLifeUser);
                    return "绑定成功";
                } else {
                    return "活动未开始或已结束";
                }
            }
        }
        return "参数异常";
    }
}
