package com.red.circle.other.app.command.user.query;

import com.red.circle.common.business.core.AppBusinessUtils;
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.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.user.UserProfileCardCO;
import com.red.circle.other.app.dto.cmd.user.user.UserCardQryCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.domain.gateway.user.ability.UserSVipGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.common.game.GameKtvCommon;
import com.red.circle.other.infra.database.mongo.entity.live.RoomProfileManager;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamMember;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamMemberService;
import com.red.circle.other.infra.database.rds.service.live.RoomMemberService;
import com.red.circle.other.inner.enums.live.RoomUserRolesEnum;
import com.red.circle.other.inner.enums.team.TeamMemberRole;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.json.JacksonUtils;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.other.inner.asserts.user.UserErrorCode;

import java.util.Objects;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 用户资料,卡片查询查询.
 *
 * @author pengliang on 2021/4/14
 */
@Component
@RequiredArgsConstructor
public class UserProfileCardQryExe {

    private final GameKtvCommon gameKtvCommon;
    private final UserSVipGateway userSVipGateway;
    private final RoomMemberService roomMemberService;
    private final UserProfileGateway userProfileGateway;
    private final UserProfileAppConvertor userProfileAppConvertor;
    private final TeamMemberService teamMemberService;
    private final RedisService redisService;
    private final RoomProfileManagerService roomProfileManagerService;
    private final UserRegionGateway userRegionGateway;

    public UserProfileCardCO execute(UserCardQryCmd cmd) {

        UserProfile userProfile = getUserProfile(cmd);
        ResponseAssert.notNull(UserErrorCode.USER_INFO_NOT_FOUND, userProfile);
        ResponseAssert.isTrue(CommonErrorCode.SYSTEM_DOES_NOT_SUPPORT,
                AppBusinessUtils.eqSysOrigin(cmd.requireReqSysOrigin()));
        TeamMember teamMember = teamMemberService.getByMemberId(cmd.getUserId());

        Boolean agent = Objects.nonNull(teamMember) && TeamMemberRole.OWN.eq(teamMember.getRole());
        Boolean anchor = Objects.nonNull(teamMember);
        UserProfileDTO userProfileDTO = userProfileAppConvertor.toUserProfileDTO(userProfile);
        boolean eqRegion = userRegionGateway.checkEqRegion(userProfile.getId(), cmd.requiredReqUserId());
        userProfileDTO.setSameRegion(eqRegion);
        UserProfileCardCO result = new UserProfileCardCO()
                .setUserProfile(userProfileDTO)
                .setFollow(checkFollow(cmd, userProfile))
                .setFriend(checkFriend(cmd, userProfile))
                .setAgent(agent)
                .setAnchor((Boolean.TRUE.equals(agent) && Boolean.TRUE.equals(anchor)) ? Boolean.FALSE : anchor)
                .setUserLevel(
                        userProfileAppConvertor.toUserLevelCO(userProfileGateway.getUserConsumptionLevel(
                                cmd.requireReqSysOriginEnum(), cmd.getUserId()))
                )
                .setSupperVip(userSVipGateway.checkSVipIdentity(cmd.getUserId()))
                .setUseProps(userProfile.getUseProps())
                .setUseBadge(userProfile.getWearBadge())
                .setRoomRole(getRoomRole(cmd))
                .setKtvIntegral(gameKtvCommon.getPopularityValue(userProfile.getId()));
        //放入redis  key IN_ROOM:userId  v 是roomId 是 放1分钟30秒每次来了都刷新过期时间
        String inRoomId = redisService.getString("IN_ROOM:" + cmd.getUserId());
        if (StringUtils.isNotBlank(inRoomId) && eqRegion) {
            RoomProfileManager byId = roomProfileManagerService.getById(Long.valueOf(inRoomId));
            if (!Objects.isNull(byId)) {
                result.getUserProfile().setInRoomId(inRoomId);
                result.getUserProfile().setRoomIcon(byId.getRoomCover());
            }
        }
        String isUpdateCountry = redisService.getString("IS_UPDATE_COUNTRY:" + cmd.requiredReqUserId());
        result.getUserProfile().setIsUpdateCountry(StringUtils.isNotBlank(isUpdateCountry) ? isUpdateCountry : "0");

        return result;

    }

    private String getRoomRole(UserCardQryCmd cmd) {
        if (Objects.isNull(cmd.getRoomId())) {
            return null;
        }
        RoomUserRolesEnum rolesEnum = roomMemberService.getRoomUserRoles(cmd.getUserId(),
                cmd.getRoomId());

        if (Objects.isNull(rolesEnum)) {
            return null;
        }

        return rolesEnum.name();
    }

    private boolean checkFollow(UserCardQryCmd cmd, UserProfile userProfile) {
        return checkSelf(cmd, userProfile)
                ? Boolean.FALSE
                : userProfileGateway.checkFollow(cmd.requiredReqUserId(), userProfile.getId());
    }

    private boolean checkFriend(UserCardQryCmd cmd, UserProfile userProfile) {
        return checkSelf(cmd, userProfile)
                ? Boolean.FALSE
                : userProfileGateway.checkFriend(cmd.requiredReqUserId(), userProfile.getId());
    }

    private UserProfile getUserProfile(UserCardQryCmd cmd) {
        if (Objects.nonNull(cmd.getUserId())) {
            return userProfileGateway.getByUserId(cmd.getUserId());
        }

        if (StringUtils.isNotBlank(cmd.getAccount())) {
            return userProfileGateway.getByAccount(cmd.requireReqSysOrigin(), cmd.getAccount());
        }

        return null;
    }

    private boolean checkSelf(UserCardQryCmd cmd, UserProfile userProfile) {

        if (Objects.equals(userProfile.getId(), cmd.requiredReqUserId())) {
            return true;
        }

        if (Objects.equals(userProfile.getAccount(), cmd.getAccount())) {
            return true;
        }

        if (Objects.nonNull(userProfile.getOwnSpecialId())
                && Objects.equals(userProfile.getOwnSpecialId().getAccount(), cmd.getAccount())) {
            return true;
        }

        return false;
    }

}
