package cn.qinys.platform.mobile.service.impl;

import cn.qinys.platform.entity.wishing.ChatMessage;
import cn.qinys.platform.entity.wishing.SpringAiChatMemory;
import cn.qinys.platform.entity.wishing.UserWish;
import cn.qinys.platform.mobile.constants.MsgTypeEnum;
import cn.qinys.platform.mobile.mapper.ChatMessageMapper;
import cn.qinys.platform.mobile.mapper.SpringAiChatMemoryMapper;
import cn.qinys.platform.mobile.mapper.UserWishMapper;
import cn.qinys.platform.mobile.service.ImageService;
import cn.qinys.platform.mobile.util.QwenImage;
import cn.qinys.platform.properties.SystemProperties;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * @author lie tan
 * @description 图片服务：调用 AI 生成图片，下载到本地目录，返回本地访问 URL
 * @date 2026-06-13 23:46
 **/
@Slf4j
@Service
public class ImageServiceImpl implements ImageService {

    @Resource
    private SystemProperties systemProperties;

    @Resource
    SpringAiChatMemoryMapper memoryMapper;
    @Resource
    UserWishMapper userWishMapper;
    @Resource
    ChatMessageMapper messageMapper;

    @Override
    @Async("mobileTaskExecutor")
    public void appendWishImage(UserWish wish) {
        QueryWrapper<SpringAiChatMemory> wrapper = new QueryWrapper<>();
        wrapper.eq("conversation_id", wish.getUserId())
                .orderByDesc("timestamp")
                .last("limit 10");
        List<SpringAiChatMemory> memoryList = memoryMapper.selectList(wrapper);
        if (memoryList == null || memoryList.isEmpty()) {
            return;
        }

        String sb = "请根据用户许下的愿望，以及最近几轮对话的内容，生成一张与许愿相关的图片，图片不要太大，控制在500k以内。用户的愿望为" +
                "content:" + wish.getContent() +
                "tag:" + wish.getTags() +
                "最近的聊天记录内容为：" + JSON.toJSONString(memoryList);

        String imageUrl = this.getImageUrl(sb);

        if (StringUtils.hasText(imageUrl)) {
            wish.setImages(JSON.toJSONString(List.of(imageUrl)));
            userWishMapper.updateById(wish);
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setUserId(wish.getUserId());
            chatMessage.setTreeId(wish.getTreeId());
            chatMessage.setType(MsgTypeEnum.TEXT.getValue());
            chatMessage.setContent("小愿已为您的愿望生成了一张图片，您可以到许愿树下查看哦~~");
            chatMessage.setRole("ai");
            messageMapper.insert(chatMessage);
        }


    }


    @Override
    public String getImageUrl(String msg) {
        // 调用 Qwen 生成图片
        String imageUrl = QwenImage.call(msg);
        if (imageUrl == null) {
            log.error("QwenImage.call returned null");
            return null;
        }
        log.info("Qwen generated image url: {}", imageUrl);

        // 下载图片到本地目录
        try {
            String ym = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
            String fileName = UUID.randomUUID().toString().replace("-", "") + ".png";
            Path targetDir = Path.of(systemProperties.getFileDirectory(), ym);
            Files.createDirectories(targetDir);
            Path targetFile = targetDir.resolve(fileName);

            try (InputStream in = URI.create(imageUrl).toURL().openStream()) {
                Files.copy(in, targetFile, StandardCopyOption.REPLACE_EXISTING);
            }

            String localUrl = systemProperties.getBaseUrl() + ym + "/" + fileName;
            log.info("Image saved to: {}", localUrl);
            return localUrl;
        } catch (Exception e) {
            log.error("Failed to download image from: {}", imageUrl, e);
            return imageUrl;
        }
    }
}
