package com.sonic.frog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sonic.bear.lib.client.UserNicknamePoolClient;
import com.sonic.bear.lib.client.UserSearchClient;
import com.sonic.bear.lib.client.UserSetClient;
import com.sonic.bear.lib.input.CompleteUserInfoInput;
import com.sonic.bear.lib.input.EditUserInfoInput;
import com.sonic.bear.lib.output.BaseUserInfoOutput;
import com.sonic.cow.lib.client.NsfwCheckClient;
import com.sonic.frog.domain.entity.AiUser;
import com.sonic.frog.domain.output.UserBaseInfoOutput;
import com.sonic.frog.enums.ToastResultCode;
import com.sonic.frog.service.AiUserSearchService;
import com.sonic.frog.service.AiUserService;
import com.sonic.frog.service.AiUserSetService;
import com.sonic.frog.service.UserService;
import com.sonic.frog.utils.BeanConver;
import com.sonic.frog.utils.MaskUtils;
import com.sonic.shark.lib.client.S3CheckClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static com.sonic.frog.enums.Constants.*;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserSearchClient userSearchClient;
    @Autowired
    private UserSetClient userSetClient;
    @Autowired
    private UserNicknamePoolClient userNicknamePoolClient;
    @Autowired
    private S3CheckClient s3CheckClient;
    @Autowired
    private AiUserSearchService aiUserSearchService;
    @Autowired
    private NsfwCheckClient nsfwCheckClient;
    @Autowired
    private AiUserSetService aiUserSetService;
    @Autowired
    private AiUserService aiUserService;

    @Override
    public BaseUserInfoOutput baseUserInfo(Long userId) {
        return userSearchClient.baseUserInfo(userId);
    }

    @Override
    public UserBaseInfoOutput getbaseUserInfo(Long userId) {
        BaseUserInfoOutput baseUserInfo = userSearchClient.baseUserInfo(userId);
        UserBaseInfoOutput output = BeanConver.copeBean(baseUserInfo, UserBaseInfoOutput.class);
        //已创建的AI数量
        Integer createdAiNum = aiUserSearchService.countAiNumByUserId(userId);
        output.setCreatedAiCount(createdAiNum);
        if (!CREATE_AI_NO_LIMIT_USER_ID_LIST.contains(userId)) {
            //会员与普通用户可创建Ai数量
            Integer totalAiNum = output.getIsMember() != null && output.getIsMember() ? TOTAL_CREATE_AI_NUM : DEFAULT_CREATE_AI_NUM;
            output.setCanCreateAiCount(totalAiNum);
        } else {
            output.setCanCreateAiCount(CREATE_AI_NO_LIMIT_NUM);
        }

        //处理邮箱脱敏
        output.setThirdEmail(MaskUtils.maskEmail(baseUserInfo.getThirdEmail()));
        return output;
    }

    @Override
    public void completeUserInfo(CompleteUserInfoInput input) {
        //年龄校验，不能小于18岁
        ToastResultCode.AGE_CHECK.check(input.getBirthday().isAfter(LocalDateTime.now().minusYears(18)));
        ToastResultCode.PARAM_NOT_NULL.check(StringUtils.isEmpty(input.getNickname()) || StringUtils.isEmpty(input.getNickname().trim()));
        ToastResultCode.PARAM_LEN_MIN_ERROR.check(input.getNickname().length() < 2);
        //昵称敏感词校验，昵称不允许包含敏感词
        nsfwCheckClient.checkContent(input.getNickname());

        //昵称校验，昵称不允许重复
        boolean nicknameExist = userNicknamePoolClient.userNicknameExistCheck(input.getUserId(), input.getNickname());
        ToastResultCode.USER_NICKNAME_EXIST.check(nicknameExist);

        //头像地址设置为空
        input.setHeadImage(null);
        userSetClient.completeUserInfo(input);
    }

    @Override
    public void editUserInfo(EditUserInfoInput input) {
        //年龄校验，不能小于18岁
        ToastResultCode.AGE_CHECK.check(input.getBirthday() != null && input.getBirthday().isAfter(LocalDateTime.now().minusYears(18)));
        if (StringUtils.isNotEmpty(input.getNickname())) {
            //昵称敏感词校验，昵称不允许包含敏感词
            nsfwCheckClient.checkContent(input.getNickname());
            //昵称校验，昵称不允许重复
            boolean nicknameExist = userNicknamePoolClient.userNicknameExistCheck(input.getUserId(), input.getNickname());
            ToastResultCode.USER_NICKNAME_EXIST.check(nicknameExist);
        }
        if (StringUtils.isNotEmpty(input.getHeadImage())) {
            //头像校验，头像地址是否是符合规范，鉴黄是否通过
            s3CheckClient.checkImage(input.getHeadImage());
        }
        //执行更新操作
        userSetClient.editUserInfo(input);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delAccount(Long userId) {
        //查询当前用户的所有 AI 列表
        List<Long> aiIdList = aiUserService.list(Wrappers.<AiUser>lambdaQuery()
                        .select(AiUser::getAiId)
                        .eq(AiUser::getUserId, userId).eq(AiUser::getIsDelete, false))
                .stream().map(e -> e.getAiId()).collect(Collectors.toList());
        for (Long aiId : aiIdList) {
            //删除AI数据
            aiUserSetService.delAiUser(aiId, userId);
        }
        //删除账号
        userSetClient.delAccount(userId);
    }

}
