package com.red.circle.other.app.listener.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Throwables;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.common.business.enums.SendPropsOrigin;
import com.red.circle.component.mq.MessageEventProcess;
import com.red.circle.component.mq.MessageEventProcessDescribe;
import com.red.circle.component.mq.config.RocketMqMessageListener;
import com.red.circle.component.mq.service.Action;
import com.red.circle.component.mq.service.ConsumerMessage;
import com.red.circle.component.mq.service.MessageListener;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.external.inner.endpoint.message.ImGroupClient;
import com.red.circle.external.inner.model.cmd.message.BroadcastGroupMsgBodyCmd;
import com.red.circle.external.inner.model.enums.message.GroupMessageTypeEnum;
import com.red.circle.mq.business.model.event.task.TaskApprovalEvent;
import com.red.circle.mq.rocket.business.streams.TaskSink;
import com.red.circle.other.app.dto.clientobject.game.GameRoomMessageCO;
import com.red.circle.other.app.service.room.RoomProfileService;
import com.red.circle.other.app.service.task.TaskService;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.gateway.user.ability.InviteUserGateway;
import com.red.circle.other.domain.model.user.UserConsumptionLevel;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.rds.dao.h5.UserInviteTaskRecordDAO;
import com.red.circle.other.infra.database.rds.dao.user.user.UserInviteUserDAO;
import com.red.circle.other.infra.database.rds.entity.family.FamilyMemberInfo;
import com.red.circle.other.infra.database.rds.entity.h5.UserInviteTaskRecord;
import com.red.circle.other.infra.database.rds.entity.sys.EnumConfig;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.entity.user.user.LatestMobileDevice;
import com.red.circle.other.infra.database.rds.entity.user.user.UserInviteUser;
import com.red.circle.other.infra.database.rds.enums.h5.MemberActiveEnum;
import com.red.circle.other.infra.database.rds.service.family.FamilyMemberInfoService;
import com.red.circle.other.infra.database.rds.service.sys.EnumConfigService;
import com.red.circle.other.infra.database.rds.service.sys.GameListConfigService;
import com.red.circle.other.infra.database.rds.service.user.device.LatestMobileDeviceService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.RelationshipFriendService;
import com.red.circle.other.inner.endpoint.activity.PropsActivityClient;
import com.red.circle.other.inner.model.cmd.activity.SendActivityRewardCmd;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.LocalDateUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RocketMqMessageListener(groupId = TaskSink.INPUT, tag = TaskSink.TAG)
@RequiredArgsConstructor
public class TaskListener implements MessageListener {
    private final MessageEventProcess messageEventProcess;
    private final TaskService taskService;
    private final RedisService redisService;
    private final RelationshipFriendService relationshipFriendService;

    private final FamilyMemberInfoService familyMemberInfoService;
    private final CpRelationshipService cpRelationshipService;
    private final UserProfileGateway userProfileGateway;
    private final RoomProfileService roomProfileService;

    private final LatestMobileDeviceService lastestMobileDeviceService;

    private final UserInviteTaskRecordDAO userInviteTaskRecordDAO;
    private final UserInviteUserDAO userInviteUserDAO;

    private final PropsActivityClient propsActivityCnfClient;

    private final EnumConfigService enumConfigService;
    private final ImGroupClient imGroupClient;
    private final GameListConfigService gameListConfigService;
    private final InviteUserGateway inviteUserGateway;

    @Override
    public Action consume(ConsumerMessage message) {
        return messageEventProcess.consume(
                MessageEventProcessDescribe.builder()
                        .logTag("任务审核")
                        .consumeMsgTimeoutMinute(1)
                        .repeatConsumeMinute(1)
                        .repeatConsumeTag("task_approval")
                        .checkConsumeTag(TaskSink.TAG)
                        .message(message)
                        .build(),
                TaskApprovalEvent.class,
                eventBody -> {
                    log.warn("任务审核 event {}", eventBody);
                    Integer taskId = eventBody.getTaskId();
                    switch (taskId) {
                        case 1:
                            // 处理任务-1 的逻辑 上麦10分钟
                            handleTask1(eventBody);
                            break;
                        case 2:
                            // 处理任务-2 的逻辑 在房间内赠送礼物
                            handleTask2(eventBody);
                            break;
                        case 3:
                            // 处理任务-3 的逻辑 添加3个好友
                            handleTask3(eventBody);
                            // 处理任务-12 的逻辑 添加20个好友
                            eventBody.setTaskId(12);
                            handleTask12(eventBody);
                            break;
                        case 4:
                            // 处理任务-4 的逻辑 玩一局游戏
                            handleTask4(eventBody);
                            break;
                        case 5:
                            // 处理任务-5 的逻辑 发布一条动态
                            handleTask5(eventBody);
                            break;
                        case 6:
                            // 处理任务-6 的逻辑 创建或加入一个家族
                            handleTask6(eventBody);
                            break;
                        case 7:
                            // 处理任务-7 的逻辑 组成一对CP
                            handleTask7(eventBody);
                            break;
                        case 8:
                            // 处理任务-8 的逻辑 在商店购买任意商品
                            handleTask8(eventBody);
                            break;
                        case 9:
                            // 处理任务-9 的逻辑 首次充值
                            handleTask9(eventBody);
                            break;
                        case 10:
                            // 处理任务-10 的逻辑 加入3个房间
                            handleTask10(eventBody);
                            break;
                        case 11:
                            // 处理任务-11 的逻辑 创建我的房间
                            handleTask11(eventBody);
                            break;
                        case 12:
                            // 处理任务-12 的逻辑 添加20个好友
                            handleTask12(eventBody);
                            break;
                        case 13:
                            // 处理任务-13 的逻辑 财富等级达到10级
                            handleTask13(eventBody);
                            break;
                        case 14:
                            // 处理任务-14 的逻辑 魅力等级达到10级
                            handleTask14(eventBody);
                            break;
//                        case 99:
//                            // 处理任务-99  裂变任务 的逻辑  注册
//                            handleTask99(eventBody);
//                            break;

                        default:
                            // 处理未知任务 ID 的情况
                            handleUnknownTask(taskId);
                    }
                }
        );
    }

    private void handleTask1(TaskApprovalEvent eventBody) {
        //    // 增加心跳次数 放一天
        String redisKey = "mic:heartbeat:" + eventBody.getUserId();
        String inc = redisService.getString(redisKey);
        if (StringUtils.isEmpty(inc)) {
            redisService.increment(redisKey, 1, 1, TimeUnit.DAYS);
        } else {
            //大于10次发一个消息
            if ("10".equals(inc) || Integer.parseInt(inc) >= 10) {
                // 更新任务状态的逻辑 直接更新
                updateTaskStatus(eventBody);
                //判断一下是否有工会裂变任务
//                checkMemberActive(eventBody.getUserId(), MemberActiveEnum.TASK_2);
            } else {
                redisService.increment(redisKey, 1);
            }
        }

//        System.out.println("处理任务-1上麦10分钟: " + eventBody);
        // task list 接口单独处理
    }

    private void handleTask99(TaskApprovalEvent eventBody) {
        log.warn("处理任务-99 裂变注册任务: {}", eventBody);
//        LatestMobileDevice userDevice = lastestMobileDeviceService.getByUserId(eventBody.getUserId());
//        if (Objects.isNull(userDevice)) {
//            log.warn("裂变注册任务 用户设备未注册: {}", eventBody.getUserId());
//            return;
//        }
//        Long ipCount = lastestMobileDeviceService.getCountByImeiAndIp(eventBody.getImei(), eventBody.getIp(),SysOriginPlatformEnum.valueOf("LOTFUN").getSysOrigin());
//        if (ipCount>1) {
//            log.warn("裂变注册任务 用户设备已注册: {}", eventBody.getUserId());
//            return;
//        }
//        lastestMobileDeviceService.getByUserId(eventBody.getUserId());
//        //判断当前user ip  和 imei是否注册
//        //初始化任务

        LambdaQueryWrapper<UserInviteUser> query = new LambdaQueryWrapper<>();
        query.eq(UserInviteUser::getUserId, eventBody.getUserId());
        UserInviteUser userInviteUser = userInviteUserDAO.selectList(query).get(0);
        if (!Objects.isNull(userInviteUser)) {
            List<UserInviteUser> userInviteUserList = userInviteUserDAO.selectList(new LambdaQueryWrapper<UserInviteUser>().eq(UserInviteUser::getInviteUserId, userInviteUser.getInviteUserId()));
            if (!CollectionUtils.isEmpty(userInviteUserList)) {

                List<LatestMobileDevice> devices = lastestMobileDeviceService.getByUserId(userInviteUserList.stream().map(UserInviteUser::getUserId).collect(Collectors.toSet()));
                if (!CollectionUtils.isEmpty(devices)) {
                    // 判断ip是否注册
                    boolean ipExists = devices.stream()
                            .anyMatch(device -> device.getIp().equals(eventBody.getIp()));
                    if (ipExists) {
                        log.warn("裂变注册任务 用户ip已注册: {}", eventBody);
                        return;
                    }

                    // 判断imei是否注册
                    boolean imeiExists = devices.stream()
                            .anyMatch(device -> device.getImei().equals(eventBody.getImei()));
                    if (imeiExists) {
                        log.warn("裂变注册任务 用户设备已注册: {}", eventBody);
                        return;
                    }


                }
            }
            List<UserInviteTaskRecord> taskRecordList = MemberActiveEnum.getTasksByType(1).stream().map(active -> {
                UserInviteTaskRecord record = new UserInviteTaskRecord();
                record.setUserId(eventBody.getUserId());
                record.setInviteUserId(userInviteUser.getInviteUserId());
                record.setTaskId((long) active.getTaskId());
                record.setTaskStatus(0);
                record.setRewardId(active.getRewardId());
                record.setTaskType(1);
                record.setCreateTimestamp(TimestampUtils.now());
                return record;
            }).toList();
            List<UserInviteTaskRecord> insertList = new ArrayList<>(taskRecordList);
            long l = checkInitInviteUserTask(userInviteUser);
            if (l == 0) {
                //初始化邀请人任务
                List<UserInviteTaskRecord> taskInviteUserRecordList = MemberActiveEnum.getTasksByType(2).stream().map(active -> {
                    UserInviteTaskRecord record = new UserInviteTaskRecord();
                    record.setUserId(userInviteUser.getInviteUserId());
//                record.setInviteUserId();
                    record.setTaskId((long) active.getTaskId());
                    record.setRewardId(active.getRewardId());
                    record.setTaskStatus(0);
                    record.setTaskType(2);
                    record.setCreateTimestamp(TimestampUtils.now());
                    return record;
                }).toList();
                insertList.addAll(taskInviteUserRecordList);
            }
            userInviteTaskRecordDAO.insertBatchSomeColumn(insertList);
            checkMemberActive(eventBody.getUserId(), MemberActiveEnum.TASK_1);
        }


    }

    private long checkInitInviteUserTask(UserInviteUser userInviteUser) {
        //是否初始化过
        LambdaQueryWrapper<UserInviteTaskRecord> inviteUserquery = new LambdaQueryWrapper<>();
        inviteUserquery.eq(UserInviteTaskRecord::getUserId, userInviteUser.getInviteUserId());
        inviteUserquery.eq(UserInviteTaskRecord::getTaskType, 2);
        return userInviteTaskRecordDAO.selectCount(inviteUserquery);
    }


    //裂变任务校验
    private void checkMemberActive(Long userId, MemberActiveEnum activeEnum) {
        LambdaQueryWrapper<UserInviteTaskRecord> query = new LambdaQueryWrapper<>();
        int taskId = activeEnum.getTaskId();
        query.in(UserInviteTaskRecord::getUserId, userId);
        query.eq(UserInviteTaskRecord::getTaskId, taskId);
        query.eq(UserInviteTaskRecord::getTaskStatus, 0);
        LocalDate localDate = LocalDate.of(2025, 6, 25);
        Timestamp timestamp = LocalDateUtils.convertTimestamp(localDate);
        query.ge(UserInviteTaskRecord::getCreateTimestamp, timestamp);
        String lockKey = "task::member-active:reward:" + userId + "-" + taskId;
        try {
            if (redisService.lock(lockKey, 20)) {
                List<UserInviteTaskRecord> record = userInviteTaskRecordDAO.selectList(query);
                if (!record.isEmpty()) {
                    record.get(0).setTaskStatus(1);
                    record.get(0).setCompletedTime(TimestampUtils.now());
                    userInviteTaskRecordDAO.updateById(record.get(0));

                    // 发送道具
                    propsActivityCnfClient.sendActivityReward(new SendActivityRewardCmd()
                            .setTrackId(IdWorkerUtils.getId())
                            .setSysOrigin(SysOriginPlatformEnum.valueOf(SysOriginPlatformEnum.valueOf("LOTFUN").getSysOrigin()))
                            .setAcceptUserId(record.get(0).getInviteUserId())
                            .setSourceGroupId(activeEnum.getRewardId())
                            .setOrigin(SendPropsOrigin.MEMBER_ACTIVE_TASK_REWARD)
                    );

                }
            }
        } finally {
            redisService.unlock(lockKey);
        }


    }

    private void handleTask2(TaskApprovalEvent eventBody) {
        log.warn("处理任务-2 在房间内赠送礼物: {}", eventBody);
        // 更新任务状态的逻辑 直接更新
        updateTaskStatus(eventBody);
    }

    private void handleTask3(TaskApprovalEvent eventBody) {
        log.warn("处理任务-3 添加3个好友: {}", eventBody);
        // 更新任务状态的逻辑
        if (relationshipFriendService.todayFlowSize(eventBody.getUserId()) >= 3) {
            updateTaskStatus(eventBody);
        }
        //判断用户是否添加了3个好友
    }


    private void handleTask4(TaskApprovalEvent eventBody) {
        // 具体的任务 4 处理逻辑
        log.warn("处理任务-4 玩一局游戏: {}", eventBody);
        // 更新任务状态的逻辑
        updateTaskStatus(eventBody);
        // 增加IM通知
        sendImGroup(eventBody);
    }

    /**
     * 当玩家中奖大于一定金币数量时,发通知
     * @param eventBody
     */
    private void sendImGroup(TaskApprovalEvent eventBody) {
        log.warn("{} 发送游戏获奖通知:金币数量= {}", eventBody.getGameName(), eventBody.getCurrencyDiff());
        if (eventBody.getCurrencyDiff() == null || eventBody.getCurrencyDiff() < 0) {
            return;
        }
        EnumConfig enumConfig = enumConfigService.getByEnumConfig("GAME_IM_NOTIFICATION_PRICE", eventBody.getSysOrigin());
        Long value = convertStringToLong(enumConfig.getVal());
        log.warn("发送游戏获奖通知--配置数据:{}", value);
        if (value == null) {
            log.warn("{} 发送游戏获奖通知:未查询到配置数据", eventBody.getGameName());
            return;
        }
        if (eventBody.getCurrencyDiff() < value) {
            log.warn("{} 发送游戏获奖通知:游戏获奖金币低于配置值,不发送通知", eventBody.getGameName());
            return;
        }
        UserProfile userProfile = userProfileGateway.getByUserId(eventBody.getUserId());

        if (userProfile == null || StringUtils.isBlank(userProfile.getUserAvatar())) {
            log.warn("{} 发送游戏获奖通知:用户头像为空 = {}", eventBody.getGameName(), eventBody.getUserId());
        }
        // 查询游戏头像
        String gameCover = gameListConfigService.getCoverByGameId(String.valueOf(eventBody.getGameId()),
                mapGameName(eventBody.getGameName()), eventBody.getSysOrigin());

        log.warn("发送游戏获奖通知--游戏头像:{}", gameCover);

        imGroupClient.sendMessageBroadcast(
                BroadcastGroupMsgBodyCmd
                        .builder()
                        .type(GroupMessageTypeEnum.GAME_BROADCAST)
                        .data(new GameRoomMessageCO()
                                .setGameCover(gameCover)
                                .setCurrencyDiff(eventBody.getCurrencyDiff())
                                .setUserCover(userProfile != null ? userProfile.getUserAvatar() : "")
                                .setMsgType(GroupMessageTypeEnum.GAME_BROADCAST.name()))
                        .toPlatform(SysOriginPlatformEnum.valueOf(eventBody.getSysOrigin()))
                        .build()
        );
        log.warn("{} 发送游戏获奖通知 成功,用户ID = {}", eventBody.getGameName(), eventBody.getUserId());
    }

    public static String mapGameName(String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }
        char firstChar = Character.toUpperCase(input.charAt(0));
        return switch (firstChar) {
            case 'B' -> "BAISHUN";
            case 'H' -> "HOTGAME";
            case 'L' -> "LINGXIAN";
            default -> "";
        };
    }

    public static Long convertStringToLong(String str) {
        try {
            return Long.parseLong(str);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private void handleTask5(TaskApprovalEvent eventBody) {
        // 具体的任务 5 处理逻辑 直接更新
        log.warn("处理任务-5 发布一条动态: {}", eventBody);
        // 更新任务状态的逻辑
        updateTaskStatus(eventBody);
    }

    private void handleUnknownTask(Integer taskId) {
        log.warn("未知任务Id {}", taskId);
    }

    // 日常任务 更新任务状态的方法示例
    private void updateTaskStatus(TaskApprovalEvent event) {
        if (taskService.checkTaskStatus(event.getUserId(), Long.valueOf(event.getTaskId()), event.getDay())) {
            taskService.updateTaskStatus(1, event.getUserId(), Long.valueOf(event.getTaskId()), event.getDay());
        }
        log.warn("任务已完成 {}", event);
    }

    // 成长任务 更新任务状态的方法示例
    private void updateTaskStatusV2(TaskApprovalEvent event) {
        if (taskService.checkTaskStatus(event.getUserId(), Long.valueOf(event.getTaskId()))) {
            taskService.updateTaskStatus(1, event.getUserId(), Long.valueOf(event.getTaskId()));
        }
        log.warn("任务已完成 {}", event);
    }

    private void handleTask6(TaskApprovalEvent eventBody) {
        log.warn("处理任务6 创建或加入一个家族: {}", eventBody);
        FamilyMemberInfo familyMemberInfo = familyMemberInfoService.getFamilyMemberByUserId(eventBody.getUserId());
        if (!Objects.isNull(familyMemberInfo)) {
            updateTaskStatusV2(eventBody);
        }

    }

    private void handleTask7(TaskApprovalEvent eventBody) {
        log.warn("处理任务-7 组成一对CP:  {}", eventBody);
//        CpRelationship cp = cpRelationshipService.getByUserId(eventBody.getUserId());
//        if (!Objects.isNull(cp)) {
//        }
        updateTaskStatusV2(eventBody);
    }

    private void handleTask8(TaskApprovalEvent eventBody) {
        log.warn("处理任务-8: {}", eventBody);
        // 在商店购买任意商品
        updateTaskStatusV2(eventBody);
    }

    private void handleTask9(TaskApprovalEvent eventBody) {
        log.warn("处理任务-9: {}", eventBody);
        // 首次充值
//        updateTaskStatusV2(eventBody);
//        checkMemberActive(eventBody.getUserId(), MemberActiveEnum.TASK_3);
        // 如果是币商给用户充值
        dealRechargeCommission(eventBody);
    }

    private void dealRechargeCommission(TaskApprovalEvent eventBody) {
        if (StringUtils.isNotBlank(eventBody.getSysOrigin()) && eventBody.getCurrencyDiff() > 0L) {
            try {
                inviteUserGateway.getRechargeCommission(BigDecimal.valueOf(eventBody.getCurrencyDiff()), eventBody.getSysOrigin(), eventBody.getUserId());
            } catch (Exception e) {
                log.error("被邀请人充值邀请人获得佣金累计错误: {}", Throwables.getStackTraceAsString(e));
            }
        }
    }

    private void handleTask10(TaskApprovalEvent eventBody) {
        log.warn("处理任务-10 加入3个房间: {}", eventBody);
        //    // 进入一次 +1
        String redisKey = "task:add-room::" + eventBody.getUserId();
        String inc = redisService.getString(redisKey);
        if (StringUtils.isEmpty(inc)) {
            redisService.increment(redisKey, 1);
        } else {
            //大于3次完成
            if ("3".equals(inc)) {
                // 更新任务状态的逻辑 直接更新
                updateTaskStatusV2(eventBody);
            } else {
                redisService.increment(redisKey, 1);
            }
        }
    }

    private void handleTask11(TaskApprovalEvent eventBody) {
        log.warn("处理任务-11 创建我的房间: {}", eventBody);
//        AppExtCommand appExtCommand = new AppExtCommand();
//        appExtCommand.setReqUserId(eventBody.getUserId());
//        if (!Objects.isNull(roomProfileService.getRoomProfile(appExtCommand))) {
//        }
        updateTaskStatusV2(eventBody);

    }

    private void handleTask12(TaskApprovalEvent eventBody) {
        log.warn("处理任务-12 添加20个好友: {}", eventBody);
        // 更新任务状态的逻辑
        if (relationshipFriendService.flowSize1000(eventBody.getUserId(), null, null).size() >= 20) {
            updateTaskStatusV2(eventBody);
        }

    }

    private void handleTask13(TaskApprovalEvent eventBody) {
        log.warn("处理任务-13 财富等级达到10级: {}", eventBody);
        UserConsumptionLevel userLevel = userProfileGateway.getUserConsumptionLevel(
                SysOriginPlatformEnum.valueOf("LIKEI"),
                eventBody.getUserId());
        if (userLevel.getWealthLevel() >= 10) {
            updateTaskStatusV2(eventBody);
        }


    }

    private void handleTask14(TaskApprovalEvent eventBody) {
        log.warn("处理任务-14 魅力等级达到10级: {}", eventBody);
        UserConsumptionLevel userLevel = userProfileGateway.getUserConsumptionLevel(
                SysOriginPlatformEnum.valueOf("LIKEI"),
                eventBody.getUserId());
        //魅力等级逻辑
        if (userLevel.getCharmLevel() >= 10) {
            updateTaskStatusV2(eventBody);
        }

    }
}
