package shop.alien.store.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.ActivityInviteConfigVo;
import shop.alien.entity.store.vo.ActivityInviteInfoVo;
import shop.alien.entity.store.vo.ActivityInviteLogVo;
import shop.alien.mapper.ActivityInviteConfigMapper;
import shop.alien.mapper.ActivityInviteLogMapper;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.store.service.ActivityInviteConfigService;
import shop.alien.store.service.LifeDiscountCouponService;
import shop.alien.store.service.UserPointService;
import shop.alien.util.common.RandomCreateUtil;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@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;

   private final LifeDiscountCouponService lifeDiscountCouponService;

    @Override
    public ActivityInviteConfigVo createOrUpdateInviteActivity(ActivityInviteConfigVo activityInviteConfigVo) {

        log.info("创建邀请活动开始执行，请求参数: {}", activityInviteConfigVo);
        if(activityInviteConfigVo == null) {
            log.error("创建邀请活动activityInviteConfigVo为空。");
            activityInviteConfigVo = new ActivityInviteConfigVo();
            activityInviteConfigVo.setErrorMessage("参数为空");
            return activityInviteConfigVo;
        }

        ActivityInviteConfig activityInviteConfig = new ActivityInviteConfig();
        if(activityInviteConfigVo.getId() == null) {
            LambdaQueryWrapper<ActivityInviteConfig> activityInviteConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
            activityInviteConfigLambdaQueryWrapper.eq(ActivityInviteConfig::getDeleteFlag, 0);
            int count = activityInviteConfigMapper.selectCount(activityInviteConfigLambdaQueryWrapper);
            if(count > 0){
                log.error("存在有效的邀请活动。");
                activityInviteConfigVo = new ActivityInviteConfigVo();
                activityInviteConfigVo.setErrorMessage("存在有效的邀请活动");
                return activityInviteConfigVo;
            }

            BeanUtils.copyProperties(activityInviteConfigVo, activityInviteConfig);
            int insertCount = activityInviteConfigMapper.insert(activityInviteConfig);
            if(insertCount == 0){
                //插入活动配置数据失败，返回
                log.error("插入邀请活动配置数据失败, {}", activityInviteConfigVo);
                activityInviteConfigVo.setErrorMessage("插入邀请活动配置数据失败");
                return activityInviteConfigVo;
            }
        } else {
            BeanUtils.copyProperties(activityInviteConfigVo, activityInviteConfig);
            int updateCount = activityInviteConfigMapper.updateById(activityInviteConfig);
            if(updateCount == 0){
                //更新活动配置数据失败，返回
                log.error("更新邀请活动配置数据失败, {}", activityInviteConfigVo);
                activityInviteConfigVo.setErrorMessage("更新邀请活动配置数据失败");
                return activityInviteConfigVo;
            }
        }

        return activityInviteConfigVo;
    }

    @Override
    public ActivityInviteConfigVo getInviteActivitySignInConfigById(Long id) {
        ActivityInviteConfig activityInviteConfig = null;
        if(id != null && id > 0){
            activityInviteConfig = activityInviteConfigMapper.selectById(id);
        } else {
            LambdaQueryWrapper<ActivityInviteConfig> activityInviteConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
            activityInviteConfigLambdaQueryWrapper.eq(ActivityInviteConfig::getDeleteFlag, 0);
            activityInviteConfigLambdaQueryWrapper.orderByDesc(ActivityInviteConfig::getCreatedTime);
            List<ActivityInviteConfig> activityInviteConfigList = activityInviteConfigMapper.selectList(activityInviteConfigLambdaQueryWrapper);
            if(CollectionUtils.isNotEmpty(activityInviteConfigList)){
                activityInviteConfig = activityInviteConfigList.get(0);
            }
        }
        ActivityInviteConfigVo activityInviteConfigVo = new ActivityInviteConfigVo();
        if(activityInviteConfig != null){
            BeanUtils.copyProperties(activityInviteConfig, activityInviteConfigVo);
        }
        return activityInviteConfigVo;
    }

    @Override
    public IPage<ActivityInviteConfig> getInviteActivityConfigList(int pageNum, int pageSize, String createdTime, Integer activityType, Integer status) {
        IPage<ActivityInviteConfig> iPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ActivityInviteConfig> activityInviteConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(createdTime)){
            activityInviteConfigLambdaQueryWrapper.between(ActivityInviteConfig::getCreatedTime,createdTime + " 00:00:00", createdTime + " 23:59:59");
        }
        if(activityType != null) {
            activityInviteConfigLambdaQueryWrapper.eq(ActivityInviteConfig::getActivityType, activityType);
        }

        if(status != null) {
            activityInviteConfigLambdaQueryWrapper.eq(ActivityInviteConfig::getStatus, status);
        }
        activityInviteConfigLambdaQueryWrapper.eq(ActivityInviteConfig::getDeleteFlag, 0 );
        return activityInviteConfigMapper.selectPage(iPage, activityInviteConfigLambdaQueryWrapper);
    }

    @Override
    public boolean updateInviteActivityStatus(Integer id, Integer status) {
        if(id == null || status == null){
            return false;
        }
        ActivityInviteConfig activityInviteConfig = new ActivityInviteConfig();
        activityInviteConfig.setId(id);
        activityInviteConfig.setStatus(status);
        int updateResult = activityInviteConfigMapper.updateById(activityInviteConfig);
        return updateResult > 0;
    }

    @Override
    public boolean deleteInviteActivity(Integer id) {
        if(id != null){
            int deleteResult =  activityInviteConfigMapper.deleteById(id);
            if(deleteResult == 0){
                return false;
            }
        }
        return false;
    }

    @Override
    public ActivityInviteInfoVo getInviteInfo(Integer userId) {
        LifeUser lifeUser = lifeUserMapper.selectById(userId);
        String inviteCode = "";

        if(lifeUser != null && StringUtils.isNotBlank(lifeUser.getInviteCode())){
            inviteCode = lifeUser.getInviteCode();
        } else{
            int count = 1;
            while (count <= 5) {
                count++;
                inviteCode = RandomCreateUtil.getRandomNStr(6);
                LambdaQueryWrapper<LifeUser> lifeUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                lifeUserLambdaQueryWrapper.eq(LifeUser::getInviteCode, inviteCode);
                lifeUserLambdaQueryWrapper.eq(LifeUser::getDeleteFlag, 0);
                int repeatCount = lifeUserMapper.selectCount(lifeUserLambdaQueryWrapper);
                if(repeatCount == 0) {
                    LifeUser updateLifeUser = new LifeUser();
                    updateLifeUser.setId(userId);
                    updateLifeUser.setInviteCode(inviteCode);
                    lifeUserMapper.updateById(updateLifeUser);
                    break;
                }
            }
        }

        LambdaQueryWrapper<ActivityInviteLog> activityInviteLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        activityInviteLogLambdaQueryWrapper.eq(ActivityInviteLog::getInviteUserId, userId);
        activityInviteLogLambdaQueryWrapper.eq(ActivityInviteLog::getDeleteFlag, 0);
        List<ActivityInviteLog> activityInviteLogList = activityInviteLogMapper.selectList(activityInviteLogLambdaQueryWrapper);
        int inviteCount = 0;
        int invitePoint = 0;
        if(CollectionUtils.isNotEmpty(activityInviteLogList)){
            inviteCount = activityInviteLogList.size();
            for(ActivityInviteLog activityInviteLog : activityInviteLogList){
                int inviteRewardType = activityInviteLog.getInviteRewardType();
                if(inviteRewardType == 2 && activityInviteLog.getInviteRewardPoint() != null){
                    invitePoint = activityInviteLog.getInviteRewardPoint() + invitePoint;
                }
            }
        }
        ActivityInviteInfoVo activityInviteInfoVo = new ActivityInviteInfoVo();
        activityInviteInfoVo.setInviteCode(inviteCode);
        activityInviteInfoVo.setInviteCount(inviteCount);
        activityInviteInfoVo.setInvitePoint(invitePoint);

        return activityInviteInfoVo;
    }

    @Override
    public IPage<ActivityInviteLogVo> getInviteActivityLogList(int pageNum, int pageSize, Integer userId, String invitePhone, String inviteStartTime, String inviteEndTime) {

        IPage<ActivityInviteLogVo> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<ActivityInviteLogVo> queryWrapper = new QueryWrapper<>();
        if(userId != null) {
            queryWrapper.eq("ail.invite_user_id", userId);
        }
        if(StringUtils.isNotBlank(invitePhone)) {
            queryWrapper.eq("lu.user_phone", invitePhone);
        }
        if(StringUtils.isNotBlank(inviteStartTime) && StringUtils.isNotBlank(inviteEndTime) ) {
            queryWrapper.between("ail.invite_time", inviteStartTime + " 00:00:00",inviteEndTime + " 23:59:59");
        }

        return activityInviteLogMapper.getInviteActivityLogList(iPage, queryWrapper);
    }

    @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()));
                   activityInviteLog.setDistributionStatus(0);
                   activityInviteLogMapper.insert(activityInviteLog);

                   //邀请奖励类型:2 积分
                   if(activityInviteConfig.getInviteRewardType() == 2){
                       userPointService.addPoint(inviteUserId, activityInviteConfig.getInviteRewardPoint());
                   }
                   //邀请奖励类型:1 优惠券
                   else if(activityInviteConfig.getInviteRewardType() == 1 && activityInviteConfig.getInviteRewardCoupon() > 0){
                       lifeDiscountCouponService.issuePlatformCoupon(Collections.singletonList(inviteUserId), activityInviteConfig.getInviteRewardCoupon());
                   }
                   //被邀请奖励类型:2 积分
                   if(activityInviteConfig.getInvitedRewardType() == 2){
                       userPointService.addPoint(invitedUserId, activityInviteConfig.getInvitedRewardPoint());
                   }
                   //被邀请奖励类型:1 优惠券
                   else if (activityInviteConfig.getInvitedRewardType() == 1 && activityInviteConfig.getInvitedRewardCoupon() > 0) {
                       lifeDiscountCouponService.issuePlatformCoupon(Collections.singletonList(invitedUserId), activityInviteConfig.getInvitedRewardCoupon());
                   }

                   LifeUser updateLifeUser = new LifeUser();
                   updateLifeUser.setId(invitedLifeUser.getId());
                   updateLifeUser.setBindInviteCode(inviteCode);
                   lifeUserMapper.updateById(updateLifeUser);
                   return "绑定成功";
               } else {
                   return "活动未开始或已结束";
               }
           }
        }
        return "参数异常";
    }

    public boolean distributionInviteReward(String invitedUserId, int inviteCondition){

        LambdaQueryWrapper<ActivityInviteLog> activityInviteLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        activityInviteLogLambdaQueryWrapper.eq(ActivityInviteLog::getInvitedUserId, invitedUserId);
        activityInviteLogLambdaQueryWrapper.eq(ActivityInviteLog::getDeleteFlag, 0);
        activityInviteLogLambdaQueryWrapper.eq(ActivityInviteLog::getDistributionStatus, 0);

        // 未发放的邀请记录
        List<ActivityInviteLog> activityInviteLogList = activityInviteLogMapper.selectList(activityInviteLogLambdaQueryWrapper);
        if(CollectionUtils.isEmpty(activityInviteLogList)){
            return false;
        }

        List<Integer> logIdList = activityInviteLogList.stream()
                .map(ActivityInviteLog::getId)
                .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(logIdList)){
            return false;
        }

        // 邀请记录对应的活动
        List<Integer> activityIdList = activityInviteLogList.stream()
                .map(ActivityInviteLog::getActivityId)
                .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(activityIdList)){
            return false;
        }
        List<ActivityInviteConfig> activityInviteConfigList =  activityInviteConfigMapper.selectBatchIds(activityIdList);
        if(CollectionUtils.isEmpty(activityInviteConfigList)){
            return false;
        }

        Map<Integer, Integer> inviteConditionMap = activityInviteConfigList.stream()
                .collect(Collectors.toMap(
                        ActivityInviteConfig::getId,
                        ActivityInviteConfig::getInviteCondition
                ));

        for(ActivityInviteLog activityInviteLog : activityInviteLogList){
            Integer activityId = activityInviteLog.getActivityId();
            if(inviteConditionMap.containsKey(activityId)){
                Integer inviteConditionValue = inviteConditionMap.get(activityId);
                if(inviteConditionValue != null && !inviteConditionValue.equals(inviteCondition)){
                    continue;
                }
               if(activityInviteLog.getInviteRewardType() == 2){
                   userPointService.addPoint(activityInviteLog.getInviteUserId(), activityInviteLog.getInviteRewardPoint());
               } else if(activityInviteLog.getInviteRewardType() == 1 && activityInviteLog.getInviteRewardCoupon() > 0){
                   lifeDiscountCouponService.issuePlatformCoupon(Collections.singletonList(activityInviteLog.getInviteUserId()), activityInviteLog.getInviteRewardCoupon());
               }
               if(activityInviteLog.getInvitedRewardType() == 2){
                   userPointService.addPoint(activityInviteLog.getInvitedUserId(), activityInviteLog.getInvitedRewardPoint());
               } else if (activityInviteLog.getInvitedRewardType() == 1 && activityInviteLog.getInvitedRewardCoupon() > 0) {
                   lifeDiscountCouponService.issuePlatformCoupon(Collections.singletonList(activityInviteLog.getInvitedUserId()), activityInviteLog.getInvitedRewardCoupon());
               }

            }
        }
        LambdaUpdateWrapper<ActivityInviteLog> activityInviteLogLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        activityInviteLogLambdaUpdateWrapper.in(ActivityInviteLog::getId, logIdList);
        activityInviteLogLambdaUpdateWrapper.set(ActivityInviteLog::getDistributionStatus, 1);
        activityInviteLogMapper.update(null, activityInviteLogLambdaUpdateWrapper);
        return true;
    }
}
