package com.sonic.frog.controller.mock;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.frog.domain.entity.AiUser;
import com.sonic.frog.domain.entity.AiUserExt;
import com.sonic.frog.domain.entity.AiUserHeartbeatRelation;
import com.sonic.frog.domain.input.GetRandomLockImageInput;
import com.sonic.frog.domain.input.MockInput;
import com.sonic.frog.domain.output.SignInRoundOutput;
import com.sonic.frog.lib.output.AIUserAlbumApiOutput;
import com.sonic.frog.service.*;
import com.sonic.frog.utils.RedisKeyUtils;
import com.sonic.sdk.api.annotation.IgnoreAuth;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.InvalidKeyException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Mock测试
 */
@Slf4j
@RestController
public class MockController {

    @Autowired
    private SignInRecordService signInRecordService;
    @Autowired
    private SignInStatSearchService signInStatSearchService;
    @Autowired
    private RankService rankService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private AiUserHeartbeatRelationService aiUserHeartbeatRelationService;
    @Autowired
    private AiUserAlbumService aiUserAlbumService;
    @Autowired
    private AiUserSearchService aiUserSearchService;
    @Autowired
    private CommonSendMqService commonSendMqService;
    @Autowired
    private MockService mockService;
    @Autowired
    private AiUserExtService aiUserExtService;

    @IgnoreAuth
    @ApiOperation(value = "签到", tags = {"Mock-签到"})
    @PostMapping("/mock/si/asi")
    public Result<Boolean> signIn(@ApiParam(hidden = true) Session session, @ApiParam(hidden = true) HttpServletRequest request) {
        session.setUserId(1L);
        return Result.success(signInRecordService.signIn(session.getUserId()));
    }

    @IgnoreAuth
    @ApiOperation(value = "七天签到列表", tags = {"Mock-签到"})
    @PostMapping("/mock/si/list")
    public Result<SignInRoundOutput> signInList(@ApiParam(hidden = true) Session session, @ApiParam(hidden = true) HttpServletRequest request) {
        session.setUserId(1L);
        return Result.success(signInStatSearchService.signInList(session.getUserId()));
    }

    @IgnoreAuth
    @ApiOperation(value = "聊天热榜定时任务", tags = {"Mock-签到"})
    @PostMapping("/mock/rank/chat")
    public Result<Integer> chatJob() {
        return Result.success(rankService.chatRankJob());
    }

    @IgnoreAuth
    @ApiOperation(value = "心动值榜定时任务", tags = {"Mock-签到"})
    @PostMapping("/mock/rank/heartbeat")
    public Result<Integer> aiHeartbeatRankJob() {
        return Result.success(rankService.aiHeartbeatRankJob());
    }

    @IgnoreAuth
    @ApiOperation(value = "初始化用户与ai的心动等级", tags = {"Mock-签到"})
    @PostMapping("/mock/heartbeat/initUserAiHeartbeatLevel")
    public Result<Integer> initUserAiHeartbeatLevel() {
        List<AiUserHeartbeatRelation> list = aiUserHeartbeatRelationService.list(Wrappers.<AiUserHeartbeatRelation>lambdaQuery().gt(AiUserHeartbeatRelation::getHeartbeatVal, 0));
        for (AiUserHeartbeatRelation aiUserHeartbeatRelation : list) {
            if (aiUserHeartbeatRelation.getHeartbeatLevel() == null) {
                continue;
            }
            redisTemplate.delete(redisKeyUtils.aiUserHeartbeatLevelCacheKey(aiUserHeartbeatRelation.getUserId(), aiUserHeartbeatRelation.getAiId()));
            stringRedisTemplate.delete(redisKeyUtils.aiUserHeartbeatLevelCacheKey(aiUserHeartbeatRelation.getUserId(), aiUserHeartbeatRelation.getAiId()));
            stringRedisTemplate.opsForValue().set(redisKeyUtils.aiUserHeartbeatLevelCacheKey(aiUserHeartbeatRelation.getUserId(), aiUserHeartbeatRelation.getAiId()), aiUserHeartbeatRelation.getHeartbeatLevel().name(), 3650, TimeUnit.DAYS);
        }
        return Result.success();
    }

    @IgnoreAuth
    @ApiOperation(value = "获取未解锁的图片", tags = {"Mock-相册"})
    @PostMapping("/mock/ai-user-album/random-lock-image")
    public Result<AIUserAlbumApiOutput> getRandomLockImage(@RequestBody GetRandomLockImageInput input) throws InvalidKeyException {
        return Result.success(aiUserAlbumService.getRandomLockImage(input));
    }

    @IgnoreAuth
    @ApiOperation(value = "初始化ai开场白声音和辅助聊天", tags = {"Mock-相册"})
    @PostMapping("/mock/initAiDialoguePrologueSoundAndSupportingContent")
    public Result<Void> initAiDialoguePrologueSoundAndSupportingContent(@RequestBody GetRandomLockImageInput input) throws InvalidKeyException {
        //获取未删除的ai
        List<AiUser> list = aiUserSearchService.list(Wrappers.<AiUser>lambdaQuery().eq(AiUser::getIsDelete, false));
        //发送MQ初始化
        for (AiUser aiUser : list) {
            commonSendMqService.aiChangeMq(aiUser.getAiId(), true, true);
        }
        return Result.success();
    }


    @IgnoreAuth
    @ApiOperation(value = "更新AI基础信息", tags = {"Mock-相册"})
    @PostMapping("/mock/updateAiUserExt")
    public Result<Void> updateAiUserExt(@RequestBody MockInput input) throws UnirestException {
        if(input.getAiId() != null) {
            mockService.updateAiUserExt(input.getAiId());
            return Result.success();
        }
        if(CollectionUtils.isNotEmpty(input.getAiIdList())) {
            //查询出未删除的ai进行处理
            List<AiUserExt> list = aiUserExtService.list(Wrappers.<AiUserExt>lambdaQuery()
                    .eq(AiUserExt::getIsDelete, false)
                    .in(CollectionUtils.isNotEmpty(input.getAiIdList()), AiUserExt::getAiId, input.getAiIdList()));
            for (AiUserExt aiUserExt : list) {
                mockService.updateAiUserExt(aiUserExt.getAiId());
            }
            return Result.success();
        }
        //查询出未删除的ai进行处理
        List<AiUserExt> list = aiUserExtService.list(Wrappers.<AiUserExt>lambdaQuery()
                .eq(AiUserExt::getIsDelete, false)
                .isNull(AiUserExt::getUserProfileExtJson));
        for (AiUserExt aiUserExt : list) {
            mockService.updateAiUserExt(aiUserExt.getAiId());
        }
        return Result.success();
    }

}
