package com.sonic.frog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.sonic.cow.lib.client.ImageClient;
import com.sonic.frog.dao.ChatUserBackgroundDao;
import com.sonic.frog.domain.entity.AiUser;
import com.sonic.frog.domain.entity.ChatUserBackground;
import com.sonic.frog.domain.input.AddBackgroundInput;
import com.sonic.frog.domain.input.AiAlbumImageInfo;
import com.sonic.frog.domain.input.BatchAddBackgroundInput;
import com.sonic.frog.domain.input.SetBackgroundInput;
import com.sonic.frog.domain.output.BackgroundImgListOutput;
import com.sonic.frog.enums.HeartbeatLevelEnum;
import com.sonic.frog.enums.ToastResultCode;
import com.sonic.frog.service.*;
import com.sonic.frog.utils.RegexUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

/**
 * 对话用户聊天背景服务实现类
 */
@Service
@Slf4j
public class ChatUserBackgroundServiceImpl extends ServiceImpl<ChatUserBackgroundDao, ChatUserBackground> implements ChatUserBackgroundService {
    @Autowired
    private AiUserSearchService aiUserSearchService;
    @Autowired
    private ChatSetService chatSetService;
    @Autowired
    private ImageClient imageClient;
    @Autowired
    private AiUserHeartbeatRelationService aiUserHeartbeatRelationService;
    @Autowired
    private HeartbeatLevelDictService heartbeatLevelDictService;

    @Override
    public List<Long> batchAddBackground(Long currentUserId, BatchAddBackgroundInput input) {
        List<AddBackgroundInput> images = input.getImages().stream().filter(info -> RegexUtil.isOssStartUrl(info.getUrl())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(images)) {
            return null;
        }
        //最多添加一张
        ToastResultCode.BACKGROUND_ADD_MAX_ONE.check(images.size() > 1);
        //判断添加的图片是否是ai生成的6张图之一
        imageClient.checkImageIsAIGenerated(currentUserId, input.getImages().stream().map(AddBackgroundInput::getUrl).collect(Collectors.toList()));
        //权限检验，只有主人才能修改
        AiUser aiUser = aiUserSearchService.getAiUserByAiId(input.getAiId());
        ToastResultCode.SYS_PERMISSION_DENIED.check(aiUser == null);
        //等级10才能添加
        HeartbeatLevelEnum heartbeatLevel = aiUserHeartbeatRelationService.getHeartbeatLevel(currentUserId, input.getAiId());
        List<HeartbeatLevelEnum> unlockHearbeatLevelList = heartbeatLevelDictService.getUnlockListByCode(heartbeatLevel);
        ToastResultCode.SYS_PERMISSION_DENIED.check(!unlockHearbeatLevelList.contains(HeartbeatLevelEnum.LEVEL_10));
        //判断添加的图片是否是ai生成的6张图
        imageClient.checkImageIsAIGenerated(currentUserId, images.stream().map(AddBackgroundInput::getUrl).collect(Collectors.toList()));
        //TODO 校验提交的图片地址是不是符合规范的,是否已经鉴黄通过
//        s3CheckClient.checkImage(images.stream().map(AiAlbumImageInfo::getUrl).collect(Collectors.toList()));
        List<Long> idList = Lists.newArrayList();
        for (AddBackgroundInput imageInfo : images) {
            ChatUserBackground chatUserBackground = ChatUserBackground.builder()
                    .imgUrl(imageInfo.getUrl())
                    .width(imageInfo.getWidth())
                    .height(imageInfo.getHeight())
                    .aiId(input.getAiId())
                    .userId(currentUserId)
                    .isDelete(false)
                    .createTime(LocalDateTime.now())
                    .editTime(LocalDateTime.now())
                    .build();
            save(chatUserBackground);
            idList.add(chatUserBackground.getId());
        }
        return idList;
    }

    @Override
    public List<BackgroundImgListOutput> getBackgroundImgList(Long userId, Long aiId) {
        List<ChatUserBackground> list = list(Wrappers.<ChatUserBackground>lambdaQuery()
                .eq(ChatUserBackground::getUserId, userId)
                .eq(ChatUserBackground::getAiId, aiId)
                .eq(ChatUserBackground::getIsDelete, false)
                .orderByDesc(ChatUserBackground::getId)
        );
        List<BackgroundImgListOutput> outputList = Lists.newArrayList();
        //获取用户设备的背景
        String chatSetBackgroundImg = chatSetService.getChatSetBackground(userId, aiId);
        //默认背景图片 添加第一个
        AiUser aiUser = aiUserSearchService.getAiUserByAiId(aiId);
        if (aiUser != null && StringUtils.isNotEmpty(aiUser.getHomeImageUrl())) {
            Boolean isSelected = chatSetBackgroundImg == null || aiUser.getHomeImageUrl().equals(chatSetBackgroundImg);
            outputList.add(BackgroundImgListOutput.builder()
                    .backgroundId(null)
                    .imgUrl(aiUser.getHomeImageUrl())
                    .width("720")
                    .height("1024")
                    .isDefault(true)
                    .isSelected(isSelected)
                    .build());
        }
        list.forEach(background -> {
            outputList.add(BackgroundImgListOutput.builder()
                    .backgroundId(background.getId())
                    .imgUrl(background.getImgUrl())
                    .width(background.getWidth())
                    .height(background.getHeight())
                    .isDefault(false)
                    .isSelected(chatSetBackgroundImg != null && chatSetBackgroundImg.equals(background.getImgUrl()))
                    .build());
        });
        return outputList;
    }

    @Override
    public void setBackground(Long currentUserId, SetBackgroundInput input) {
        //默认背景图片
        if (input.getBackgroundId() == null) {
            chatSetService.setBackground(currentUserId, input.getAiId(), DEFAULT_BACKGROUND);
            return;
        }
        //权限检验，只有主人才能修改
        ChatUserBackground chatUserBackground = getOne(Wrappers.<ChatUserBackground>lambdaQuery().eq(ChatUserBackground::getId, input.getBackgroundId()));
        ToastResultCode.SYS_PERMISSION_DENIED.check(chatUserBackground == null);
        ToastResultCode.SYS_PERMISSION_DENIED.check(!chatUserBackground.getUserId().equals(currentUserId));
        //设置图片为用户与AI的聊天背景
        chatSetService.setBackground(currentUserId, input.getAiId(), chatUserBackground.getImgUrl());
    }

    @Override
    public void delBackground(Long currentUserId, Long backgroundId) {
        //权限检验，只有主人才能修改
        ChatUserBackground chatUserBackground = getOne(Wrappers.<ChatUserBackground>lambdaQuery().eq(ChatUserBackground::getId, backgroundId));
        ToastResultCode.BACKGROUND_NOT_EXIST.check(chatUserBackground == null);
        ToastResultCode.SYS_PERMISSION_DENIED.check(!chatUserBackground.getUserId().equals(currentUserId));
        ToastResultCode.BACKGROUND_IS_DELETED.check(chatUserBackground.getIsDelete());
        //软删除
        update(Wrappers.<ChatUserBackground>lambdaUpdate().set(ChatUserBackground::getIsDelete, true).eq(ChatUserBackground::getId, backgroundId));
        //如果删除的是设置背景，需要默认为默认背景
        chatSetService.setBackground(currentUserId, chatUserBackground.getAiId(), null);
    }
}