package com.red.circle.other.app.service.h5;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.redis.service.RedisService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.dto.h5.InviteInfo;
import com.red.circle.other.app.dto.h5.MemberActiveDTO;
import com.red.circle.other.app.dto.h5.TaskInfo;
import com.red.circle.other.app.service.user.user.UserInviteService;
import com.red.circle.other.infra.database.mongo.entity.user.profile.UserSpecialId;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamProfileService;
import com.red.circle.other.infra.database.mongo.service.user.profile.UserSpecialIdService;
import com.red.circle.other.infra.database.rds.dao.h5.FamilyActiveRecordDAO;
import com.red.circle.other.infra.database.rds.dao.h5.UserInviteTaskRecordDAO;
import com.red.circle.other.infra.database.rds.dao.user.user.BaseInfoDAO;
import com.red.circle.other.infra.database.rds.dao.user.user.UserInviteUserDAO;
import com.red.circle.other.infra.database.rds.entity.family.FamilyBaseInfo;
import com.red.circle.other.infra.database.rds.entity.family.FamilyMemberInfo;
import com.red.circle.other.infra.database.rds.entity.h5.FamilyActiveRecord;
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.BaseInfo;
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.FamilyBaseInfoService;
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.user.user.BaseInfoService;
import com.red.circle.other.inner.asserts.ActivityErrorCode;
import com.red.circle.other.inner.endpoint.activity.PropsActivityClient;
import com.red.circle.other.inner.model.cmd.activity.SendActivityRewardCmd;
import com.red.circle.other.inner.model.dto.pet.UserBaseInfoDTO;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MemberActiveServiceImpl implements MemberActiveService {

    private final UserInviteUserDAO userInviteUserDAO;
    private final UserInviteTaskRecordDAO userInviteTaskRecordDAO;

    private final PropsActivityClient propsActivityCnfClient;


    private final EnumConfigService enumConfigService;

    private final BaseInfoService baseInfoService;

    private final RedisService redisService;

    private final FamilyActiveRecordDAO familyActiveRecordDAO;
    private final FamilyBaseInfoService familyBaseInfoService;
    private final TeamProfileService teamProfileService;
    private final UserSpecialIdService userSpecialIdService;

    public void joinActive(AppExtCommand cmd) {
//        // 检查是否是工会长
//        Map<Long, FamilyBaseInfo> map = familyBaseInfoService.mapByUserIds(Collections.singleton(cmd.getReqUserId()));
//        FamilyBaseInfo familyBaseInfo = map.get(cmd.getReqUserId());
//        ResponseAssert.isFalse(CommonErrorCode.SAVE_FAILURE,
//                "Permission denied: Not a guild leader", Objects.isNull(familyBaseInfo));

        //判断是否是 agent

        ResponseAssert.isFalse(CommonErrorCode.SAVE_FAILURE,
                "Permission denied: Not a Agent", !teamProfileService.existsOwnUserId(cmd.getReqUserId()));

        // 检查工会是否已参与
        LambdaQueryWrapper<FamilyActiveRecord> query = new LambdaQueryWrapper<>();
        query.eq(FamilyActiveRecord::getFamilyId, cmd.getReqUserId());
        boolean hasJoined = familyActiveRecordDAO.selectCount(query)>0L;
        ResponseAssert.isFalse(CommonErrorCode.SAVE_FAILURE,  "Agent has already participated",hasJoined);

        // 创建活动记录
        FamilyActiveRecord record = new FamilyActiveRecord();
        record.setId(IdWorkerUtils.getId());
        record.setFamilyId(cmd.getReqUserId());
        record.setMemberAdminId(cmd.getReqUserId());
        record.setCreateTimestamp(new Timestamp(System.currentTimeMillis()));
        record.setSysOrigin(cmd.getReqSysOrigin().getOrigin());
        familyActiveRecordDAO.insert(record);
    }

    @Override
    public MemberActiveDTO activeList(AppExtCommand cmd) {
        MemberActiveDTO result = new MemberActiveDTO();
        Long reqUserId = cmd.getReqUserId();
        List<UserInviteUser> inviteUsers = getInviteUser(cmd, reqUserId);
        Set<Long> ids = new HashSet<>();
        ids.add(reqUserId);
        ids.addAll(inviteUsers.stream().map(UserInviteUser::getUserId).collect(Collectors.toSet()));
        Map<Long, UserBaseInfoDTO> userInfoMap = baseInfoService.mapUserBaseInfoDTO(ids);
        if (!CollectionUtils.isEmpty(inviteUsers)) {

            LambdaQueryWrapper<UserInviteTaskRecord> query = new LambdaQueryWrapper<>();
            query.in(UserInviteTaskRecord::getUserId, ids);
            List<UserInviteTaskRecord> tasks = userInviteTaskRecordDAO.selectList(query);
            Map<Long, List<UserInviteTaskRecord>> groupedTasks = tasks.stream()
                    .collect(Collectors.groupingBy(UserInviteTaskRecord::getUserId));
            List<InviteInfo> inviteInfos = new ArrayList<>();
            inviteUsers.forEach(userInviteUser -> {
                InviteInfo inviteInfo = new InviteInfo();
                List<UserInviteTaskRecord> userInviteTaskRecords = groupedTasks.get(userInviteUser.getUserId());
                //不为空
                if (!CollectionUtils.isEmpty(userInviteTaskRecords)) {

                    List<TaskInfo> resultTaskList = userInviteTaskRecords.stream().map(record ->
                            {
                                TaskInfo taskInfo = new TaskInfo();
                                taskInfo.setTaskId(record.getTaskId());
                                taskInfo.setStatus(record.getTaskStatus());
                                return taskInfo;
                            }

                    ).toList();
                    inviteInfo.setUserName(userInfoMap.get(userInviteUser.getUserId()).getUserNickname());
                    inviteInfo.setUserAvatar(userInfoMap.get(userInviteUser.getUserId()).getUserAvatar());
                    inviteInfo.setTasks(resultTaskList);
                    inviteInfos.add(inviteInfo);

                }

                //判断是够5 10 30 人奖励  //单独查一次吧
//                List<UserInviteTaskRecord> reqUserTask = groupedTasks.get(reqUserId);
//                reqUserTask.stream().filter(task->task.getTaskType()==2 && task.getTaskStatus()==0)



            });
            result.setInviteList(inviteInfos);
            checkTask(cmd, reqUserId, inviteInfos.size());

        }
        result.setAccountId(String.valueOf(userInfoMap.get(reqUserId).getAccount()));
        UserSpecialId userSpecialId = userSpecialIdService.getByUserId(reqUserId);
        if (checkOwnSpecialIdAvailable(userSpecialId)) {
            result.setAccountId(userSpecialId.getAccount());
        }
        result.setUserAvatar(userInfoMap.get(reqUserId).getUserAvatar());
//cmd.ge
        return result;
    }

    /**
     * 检查靓号是否可用.
     */
    private boolean checkOwnSpecialIdAvailable(UserSpecialId userSpecialId) {
        boolean exists = Objects.nonNull(userSpecialId)
                && Objects.nonNull(userSpecialId.getAccount());

        if (!exists) {
            return false;
        }

        return Objects.isNull(userSpecialId.getExpiredTime())
                || userSpecialId.getExpiredTime().after(TimestampUtils.now());
    }

    private void checkTask(AppExtCommand cmd, Long reqUserId,Integer size) {
        String lockKey = "task::member-active:reward:" + cmd.getReqUserId();
        try {
            if (redisService.lock(lockKey, 20)) {
                List<UserInviteTaskRecord> reqUserTask = getReqUserInviteTaskRecords(reqUserId);
                if (!Objects.isNull(reqUserTask)) {
                    //
                    reqUserTask.forEach(task -> {

                        if (size >= 30 && task.getTaskId() == MemberActiveEnum.TASK_4.getTaskId() && task.getTaskStatus() == 0) {
                            // 发送道具
                            propsActivityCnfClient.sendActivityReward(new SendActivityRewardCmd()
                                    .setTrackId(IdWorkerUtils.getId())
                                    .setSysOrigin(SysOriginPlatformEnum.valueOf(cmd.getReqSysOrigin().getOrigin()))
                                    .setAcceptUserId(cmd.getReqUserId())
                                    .setSourceGroupId(MemberActiveEnum.TASK_4.getRewardId())
                                    .setOrigin(SendPropsOrigin.MEMBER_ACTIVE_TASK_REWARD)

                            );
                            //修改状态
                            task.setTaskStatus(1);
                            userInviteTaskRecordDAO.updateById(task);
                        }
                        if (size >= 10 && task.getTaskId() == MemberActiveEnum.TASK_5.getTaskId() && task.getTaskStatus() == 0) {
                            // 发送道具
                            propsActivityCnfClient.sendActivityReward(new SendActivityRewardCmd()
                                    .setTrackId(IdWorkerUtils.getId())
                                    .setSysOrigin(SysOriginPlatformEnum.valueOf(cmd.getReqSysOrigin().getOrigin()))
                                    .setAcceptUserId(cmd.getReqUserId())
                                    .setSourceGroupId(MemberActiveEnum.TASK_5.getRewardId())
                                    .setOrigin(SendPropsOrigin.MEMBER_ACTIVE_TASK_REWARD));
                            //修改状态
                            task.setTaskStatus(1);
                            userInviteTaskRecordDAO.updateById(task);

                        }
                        if (size >= 5 && task.getTaskId() == MemberActiveEnum.TASK_6.getTaskId() && task.getTaskStatus() == 0) {
                            // 发送道具
                            propsActivityCnfClient.sendActivityReward(new SendActivityRewardCmd()
                                    .setTrackId(IdWorkerUtils.getId())
                                    .setSysOrigin(SysOriginPlatformEnum.valueOf(cmd.getReqSysOrigin().getOrigin()))
                                    .setAcceptUserId(cmd.getReqUserId())
                                    .setSourceGroupId(MemberActiveEnum.TASK_6.getRewardId())
                                    .setOrigin(SendPropsOrigin.MEMBER_ACTIVE_TASK_REWARD));
                            //修改状态
                            task.setTaskStatus(1);
                            userInviteTaskRecordDAO.updateById(task);
                        }
                    });

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

    private List<UserInviteTaskRecord> getReqUserInviteTaskRecords(Long reqUserId) {
        LambdaQueryWrapper<UserInviteTaskRecord> query = new LambdaQueryWrapper<>();
        query.in(UserInviteTaskRecord::getUserId, reqUserId);
        query.eq(UserInviteTaskRecord::getTaskType, 2);
        query.eq(UserInviteTaskRecord::getTaskStatus, 0);
        return userInviteTaskRecordDAO.selectList(query);
    }

    private List<UserInviteUser> getInviteUser(AppExtCommand cmd, Long reqUserId) {
        //获取配置
        EnumConfig enumConfig = enumConfigService.getByEnumConfig("MEMBER_ACTIVE_TIME", cmd.getReqSysOrigin().getOrigin());
        ResponseAssert.isTrue(ActivityErrorCode.ACTIVITY_PENDING_START,
                !Objects.isNull(enumConfig));
        //2025-01-02
        String start_date = enumConfig.getVal().split(",")[0];
        String end_date = enumConfig.getVal().split(",")[1];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = sdf.parse(start_date);
            endDate = sdf.parse(end_date);
        } catch (ParseException e) {
            // 处理日期解析异常
            e.printStackTrace();
        }

        LambdaQueryWrapper<UserInviteUser> query = new LambdaQueryWrapper<>();
        query.eq(UserInviteUser::getInviteUserId, reqUserId);
        if (startDate != null && endDate != null) {
            query.between(UserInviteUser::getCreateTime, new Timestamp(startDate.getTime()), new Timestamp(endDate.getTime()));
        }
        return userInviteUserDAO.selectList(query);
    }
}
