package edu.whut.smilepicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.whut.smilepicturebackend.api.aliyunai.AliYunAiApi;
import edu.whut.smilepicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import edu.whut.smilepicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import edu.whut.smilepicturebackend.api.imagesearch.ImageSearchApiFacade;
import edu.whut.smilepicturebackend.api.imagesearch.model.ImageSearchResult;
import edu.whut.smilepicturebackend.exception.BusinessException;
import edu.whut.smilepicturebackend.exception.ErrorCode;
import edu.whut.smilepicturebackend.exception.ThrowUtils;
import edu.whut.smilepicturebackend.manager.CosManager;
import edu.whut.smilepicturebackend.manager.FileManager;
import edu.whut.smilepicturebackend.manager.cache.MyCacheManager;
import edu.whut.smilepicturebackend.manager.upload.FilePictureUpload;
import edu.whut.smilepicturebackend.manager.upload.PictureUploadTemplate;
import edu.whut.smilepicturebackend.manager.upload.UrlPictureUpload;
import edu.whut.smilepicturebackend.mapper.PictureMapper;
import edu.whut.smilepicturebackend.model.dto.picture.*;
import edu.whut.smilepicturebackend.model.entity.Picture;
import edu.whut.smilepicturebackend.model.entity.Space;
import edu.whut.smilepicturebackend.model.entity.User;
import edu.whut.smilepicturebackend.model.enums.PictureReviewStatusEnum;
import edu.whut.smilepicturebackend.model.file.UploadPictureResult;
import edu.whut.smilepicturebackend.model.vo.PictureVO;
import edu.whut.smilepicturebackend.model.vo.UserVO;
import edu.whut.smilepicturebackend.service.PictureService;
import edu.whut.smilepicturebackend.service.SpaceService;
import edu.whut.smilepicturebackend.service.UserService;
import edu.whut.smilepicturebackend.utils.ColorSimilarUtils;
import edu.whut.smilepicturebackend.utils.ColorTransformUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;


import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
* @author 张三
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-06-11 11:23:11
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService {
    private final FileManager fileManager;

    private final UserService userService;

    private final FilePictureUpload filePictureUpload;

    private final UrlPictureUpload urlPictureUpload;

    private final MyCacheManager cacheManager;

    private final CosManager cosManager;

    private final SpaceService spaceService;

    private final TransactionTemplate transactionTemplate;

    private final AliYunAiApi aliYunAiApi;

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        // 如果传递了 url，才校验
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 改为使用统一的权限校验
            // 校验是否有空间的权限，仅空间管理员才能上传
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // 判断是创建还是替换
        Long pictureId = pictureUploadRequest == null ? null : pictureUploadRequest.getId();
        Picture oldPicture = null;

        // 如果是更新，判断图片是否存在
        if (pictureId != null) {
            oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 改为使用统一的权限校验
            // 仅本人或管理员可编辑图片
//            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId（这样也兼容了公共图库）
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原图片的空间 id 一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }
        // 上传图片，得到图片信息
        // 按照用户 id 划分目录 => 按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            // 公共图库+用户id
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            // 私人空间+空间id
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 根据 inputSource 的类型区分上传方式!!
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            log.info("收到 upload/url 请求，url = {}", inputSource);
            pictureUploadTemplate = urlPictureUpload;
        }
        //上传到腾讯云COS上
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造要入库的图片信息，将图片信息存入数据库中。
        Picture picture = new Picture();

        // 复制同名属性（url、name、picSize、picWidth、picHeight、picScale、picFormat）
        BeanUtils.copyProperties(uploadPictureResult, picture);

        // 支持外层pictureUploadRequest传递图片名称
        picture.setName(
                StrUtil.blankToDefault(
                        pictureUploadRequest == null ? null : pictureUploadRequest.getPicName(),
                        uploadPictureResult.getName()
                )
        );
        if (pictureUploadRequest.getTags() != null) {
            String rawTags = pictureUploadRequest.getTags();
            picture.setTags(normalizeTags(rawTags));
        }
        picture.setUserId(loginUser.getId());
        picture.setSpaceId(spaceId);
        // 转换为标准颜色
//        log.info("颜色"+uploadPictureResult.getPicColor());
        picture.setPicColor(ColorTransformUtils.getStandardColor(uploadPictureResult.getPicColor()));
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 计算差值，保证 oldPicture 为空时不抛异常
        long sizeDelta   = picture.getPicSize() - (oldPicture == null ? 0 : oldPicture.getPicSize());
        long countDelta  = (oldPicture == null ? 1 : 0);
        // 开启事务,图片上传成功和修改额度一定要同时成功或失败
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            log.info("uploadPicture | spaceId={}, sizeDelta={}, countDelta={}",
                    finalSpaceId, sizeDelta, countDelta);

            /* ---------- 1. 保存 / 更新图片记录 ---------- */
            boolean saved = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR, "图片上传失败，数据库操作失败");

            /* ---------- 2. 更新空间额度（只有有变化时才执行 UPDATE） ---------- */
            if (finalSpaceId != null && (sizeDelta != 0 || countDelta != 0)) {
                LambdaUpdateChainWrapper<Space> wrapper = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId);

                // 组装可变 SQL，不生成空 SET
                StringBuilder setSql = new StringBuilder();
                if (sizeDelta != 0) {
                    setSql.append("total_size = total_size + ").append(sizeDelta);
                }
                if (countDelta != 0) {
                    if (setSql.length() > 0) setSql.append(", ");
                    setSql.append("total_count = total_count + ").append(countDelta);
                }
                wrapper.setSql(setSql.toString());

                boolean updated = wrapper.update();
                ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }

            return picture;   // 事务块返回结果
        });
        //如果是更新，清理旧的图片
        if (oldPicture != null) {
            this.clearPictureFile(oldPicture);
        }
        return PictureVO.objToVo(picture);
    }

    @Override
    public LambdaQueryWrapper<Picture> getQueryWrapper(PictureQueryRequest req) {
        LambdaQueryWrapper<Picture> qw = Wrappers.lambdaQuery(Picture.class);
        if (req == null) {
            return qw;
        }

        // 精简版条件构造
        qw.eq(ObjUtil.isNotEmpty(req.getId()),          Picture::getId,          req.getId())
                .eq(ObjUtil.isNotEmpty(req.getUserId()),      Picture::getUserId,      req.getUserId())
                .eq(ObjUtil.isNotEmpty(req.getSpaceId()),     Picture::getSpaceId,     req.getSpaceId()) //指定 spaceId → 查该空间图片。
                .isNull(req.isNullSpaceId(),                  Picture::getSpaceId)                    //不传则查公共图库
                .like(StrUtil.isNotBlank(req.getName()),      Picture::getName,        req.getName())
                .like(StrUtil.isNotBlank(req.getIntroduction()), Picture::getIntroduction, req.getIntroduction())
                .like(StrUtil.isNotBlank(req.getPicFormat()), Picture::getPicFormat,   req.getPicFormat())
                .eq(ObjUtil.isNotEmpty(req.getReviewMessage()), Picture::getReviewMessage, req.getReviewMessage())
                .eq(StrUtil.isNotBlank(req.getCategory()),    Picture::getCategory,    req.getCategory())
                .eq(ObjUtil.isNotEmpty(req.getPicWidth()),    Picture::getPicWidth,    req.getPicWidth())
                .eq(ObjUtil.isNotEmpty(req.getPicHeight()),   Picture::getPicHeight,   req.getPicHeight())
                .eq(ObjUtil.isNotEmpty(req.getPicSize()),     Picture::getPicSize,     req.getPicSize())
                .eq(ObjUtil.isNotEmpty(req.getPicScale()),    Picture::getPicScale,    req.getPicScale())
                .eq(ObjUtil.isNotEmpty(req.getReviewStatus()), Picture::getReviewStatus, req.getReviewStatus())
                .eq(ObjUtil.isNotEmpty(req.getReviewerId()),  Picture::getReviewerId,  req.getReviewerId())
                .ge(ObjUtil.isNotEmpty(req.getStartEditTime()), Picture::getEditTime,  req.getStartEditTime())  // >=
                .lt(ObjUtil.isNotEmpty(req.getEndEditTime()),   Picture::getEditTime,  req.getEndEditTime());   // <=

        // 全字段模糊搜索
        if (StrUtil.isNotBlank(req.getSearchText())) {
            qw.and(w -> w
                    .like(Picture::getName, req.getSearchText())
                    .or()
                    .like(Picture::getIntroduction, req.getSearchText())
            );
        }

        // JSON 数组 tags 查询
        if (CollUtil.isNotEmpty(req.getTags())) {
            req.getTags().forEach(tag ->
                    qw.like(Picture::getTags, "\"" + tag + "\"")
            );
        }

        // 动态排序：转下划线字段名并手工拼接
        if (StrUtil.isNotBlank(req.getSortField())) {
            String column = StrUtil.toUnderlineCase(req.getSortField());
            String direction = "ascend".equalsIgnoreCase(req.getSortOrder()) ? "ASC" : "DESC";
            qw.last("ORDER BY " + column + " " + direction);
        }

        return qw;
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或者管理员可删除
        if (!oldPicture.getUserId().equals(loginUser.getId())
                && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 事务：删除记录 + 私有空间额度更新
        // 只有属于私有空间（spaceId != null）才更新额度
        boolean txSuccess = Boolean.TRUE.equals(transactionTemplate.execute(status -> {
            boolean removed = this.removeById(pictureId);
            ThrowUtils.throwIf(!removed, ErrorCode.OPERATION_ERROR);

            // 只有属于私有空间（spaceId != null）才更新额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("total_size = total_size - " + oldPicture.getPicSize())
                        .setSql("total_count = total_count - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        }));

        // 事务成功后再清理物理文件
        if (Boolean.TRUE.equals(txSuccess)) {
            this.clearPictureFile(oldPicture);
        }
    }


    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限，已改为注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 补充审核 参数,每次编辑图片都要重新过审
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        //从 Page<Picture> 中拿到原始记录和分页元数据
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 实体到 VO 的基本映射
        List<PictureVO> pictureVOList = pictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
        //批量拉取关联的用户信息
        //先从所有 Picture 里摘出不重复的 userId。
        //调 userService.listByIds(...) 一次性把这些用户都查出来，避免 N+1 查询。
        //再把结果按 userId 分组，方便快速根据 ID 拿到对应的 User 对象。
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        // 1 => user1, 2 => user2
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 把用户信息填充到 VO
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 判断图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 3. 校验审核状态是否重复，已是改状态
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        // 4. 数据库操作
        Picture updatePicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());   //审核人
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 填充审核参数
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，无论是编辑还是创建默认都是待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    //爬取网落图片，可以用ai分析标签
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 1) 校验参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        ThrowUtils.throwIf(StrUtil.isBlank(searchText), ErrorCode.PARAMS_ERROR, "关键词不能为空");
        Integer count = ObjUtil.defaultIfNull(pictureUploadByBatchRequest.getCount(), 10);
        ThrowUtils.throwIf(count <= 0 || count > 30, ErrorCode.PARAMS_ERROR, "数量范围应为 1 ~ 30");

        // 名称前缀默认等于搜索关键词
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }

        // 2) 构造抓取 URL：加入随机偏移 first，扩大抓取条数以便去重（抓 N 的 2 倍，最多 50）
        int first = ThreadLocalRandom.current().nextInt(0, 201); // 0~200 的随机起始
        int fetchSize = Math.min(Math.max(count * 2, count), 50);
        String fetchUrl = String.format(
                "https://cn.bing.com/images/async?q=%s&mmasync=1&first=%d&count=%d&setlang=zh-cn&mkt=zh-CN",
                URLEncoder.encode(searchText, StandardCharsets.UTF_8), first, fetchSize
        );

        // 3) 抓取页面
        Document document;
        try {
            document = Jsoup.connect(fetchUrl)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")      // 随机 UA 提升多样性
                    .header("Cache-Control", "no-cache")
                    .timeout(10_000)
                    .get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }

        // 4) 解析内容
        Element container = document.selectFirst(".dgControl");
        if (container == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElements = container.select("img.mimg");

        // 打乱顺序，减少总是取到相同前几张
        List<Element> candidates = new ArrayList<>(imgElements);
        Collections.shuffle(candidates);

        // 5) 本次任务内去重（按 URL）
        Set<String> seen = new HashSet<>();

        // 6) 遍历并上传
        int uploadCount = 0;
        for (Element img : candidates) {
            // 优先从最近的 <a class="iusc"> 的 m 属性中取原图 murl
            String fileUrl = null;
            Element a = img.closest("a.iusc");
            if (a != null && StrUtil.isNotBlank(a.attr("m"))) {
                try {
                    JSONObject mObj = JSONUtil.parseObj(a.attr("m"));
                    fileUrl = mObj.getStr("murl"); // 原图地址
                } catch (Exception ignore) {
                    // 解析失败走后备
                }
            }
            // 后备：从 img 上取 src / data-src / data-src-hq
            if (StrUtil.isBlank(fileUrl)) {
                fileUrl = StrUtil.firstNonNull(
                        img.attr("src"),
                        img.attr("data-src"),
                        img.attr("data-src-hq"),
                        img.attr("data-url")
                );
            }

            if (StrUtil.isBlank(fileUrl)) {
                log.info("未获取到图片链接，跳过");
                continue;
            }

            // 规范化 URL（去掉 ? 之后的参数，去空白）
            fileUrl = normalizeUrl(fileUrl);

            // 本次任务内去重
            if (!seen.add(fileUrl)) {
                log.info("重复链接（本次任务），已跳过：{}", fileUrl);
                continue;
            }

            // 7) 上传
            PictureUploadRequest req = new PictureUploadRequest();
            req.setFileUrl(fileUrl);
            req.setPicName(namePrefix + (uploadCount + 1));
            req.setTags(namePrefix);

            try {
                log.info("爬取图片 url：{}", fileUrl);
                PictureVO pictureVO = this.uploadPicture(fileUrl, req, loginUser);
                log.info("图片上传成功，id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                // 不中断，继续下一张
            }

            if (uploadCount >= count) {
                break;
            }
        }

        return uploadCount;
    }

    /** 规范化图片 URL：去掉查询参数，trim 空白 */
    private String normalizeUrl(String url) {
        if (StrUtil.isBlank(url)) return url;
        int i = url.indexOf('?');
        if (i > -1) {
            url = url.substring(0, i);
        }
        return url.trim();
    }

    /**
     * 查询图片带缓存
     * @param queryRequest
     * @param httpRequest
     * @return
     */
    @Override
    public Page<PictureVO> listPictureVOByPageWithCache(PictureQueryRequest queryRequest, HttpServletRequest httpRequest) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();

        // 参数校验
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        // 构造 cacheKey
        String condJson = JSONUtil.toJsonStr(queryRequest);
        String hash = DigestUtils.md5DigestAsHex(condJson.getBytes());
        String cacheKey = "smilepicture:listPictureVOByPage:" + hash;

        // 随机过期：300–600s
        int expire = 300 + RandomUtil.randomInt(0, 300);

        // 调用通用缓存方法
        return cacheManager.getFromCacheOrDatabase(
                cacheKey,
                Page.class,
                () -> {
                    Page<Picture> picturePage = this.page(new Page<>(current, size),
                            this.getQueryWrapper(queryRequest));
                    return this.getPictureVOPage(picturePage, httpRequest);
                },
                expire
        );
    }

    @Async   //异步执行
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用(图片秒传的情况可能一个cos地址对应多个数据库url)
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        // 删除图片
        cosManager.deleteIfNotBlank(pictureUrl);

        //删除原图
        String originalUrl=oldPicture.getOriginalUrl();
        cosManager.deleteIfNotBlank(originalUrl);

        // 删除缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        cosManager.deleteIfNotBlank(thumbnailUrl);
    }
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        Long loginUserId = loginUser.getId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUserId) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUserId)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public List<ImageSearchResult> getSimilarPicture(SearchPictureByPictureRequest request) throws IOException {
        // 1.校验参数
        Long pictureId = request.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0 ,ErrorCode.NOT_FOUND_ERROR);

        // 2.查询数据库
        Picture picture = this.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        // 3.提取图片在COS中的key

        String pictureKey = cosManager.extractUploadPath(picture.getUrl());

        // 4.下载文件 文件地址 = 当前项目路径 + 图片key（图片key带时间戳本来是唯一）
        String suffix = pictureKey.replace('/', '\\');
        String localPath = System.getProperty("user.dir") + "\\images\\" + suffix;
        cosManager.downloadPicture(pictureKey, localPath);

        // 5.返回结果
        try {
            return ImageSearchApiFacade.searchImage(localPath);
        } finally {
            // 删除本地文件及文件夹
            File dir = new File(System.getProperty("user.dir") + "\\images\\");

            if (dir.isDirectory()) {
                // 清空目录
                FileUtil.clean(dir);
                log.info("Directory cleaned successfully.");
            } else {
                log.info("The provided path is not a directory.");
            }
        }
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询该空间下的所有图片（必须要有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return new ArrayList<>();
        }
        // 将颜色字符串转换为主色调
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<Picture> sortedPictureList = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片会默认排序到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 计算相似度
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                .limit(12) // 取前 12 个
                .collect(Collectors.toList());
        // 5. 返回结果
        return sortedPictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        // 1. 获取和校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询指定图片（仅选择需要的字段）
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 5. 操作数据库进行批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量编辑失败");
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = this.getById(pictureId);
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        // 校验权限，已经改为使用注解鉴权
//        checkPictureAuth(loginUser, picture);
        // 创建扩图任务
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        createOutPaintingTaskRequest.setInput(input);
        createOutPaintingTaskRequest.setParameters(createPictureOutPaintingTaskRequest.getParameters());
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }

    /**
     * nameRule 格式：图片-{序号}  =>图片-1  图片-2 ...
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule) || CollUtil.isEmpty(pictureList)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

    // 工具方法：把任意传入的 tags 字符串规范为 JSON 数组字符串
    private static String normalizeTags(String raw) {
        if (cn.hutool.core.util.StrUtil.isBlank(raw)) {
            return "[]";
        }
        String t = raw.trim();
        try {
            // 已经是 JSON 数组
            if (t.startsWith("[")) {
                // 校验一下能不能 parse
                cn.hutool.json.JSONUtil.parseArray(t);
                return t;
            }
            // 逗号/顿号/空白分隔（中英文逗号都支持）
            String[] parts = t.split("[,，、\\s]+");
            java.util.List<String> list = java.util.Arrays.stream(parts)
                    .map(String::trim)
                    .filter(cn.hutool.core.util.StrUtil::isNotBlank)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());
            return cn.hutool.json.JSONUtil.toJsonStr(list);
        } catch (Exception e) {
            // 兜底：当成一个元素
            return cn.hutool.json.JSONUtil.toJsonStr(
                    java.util.Collections.singletonList(t));
        }
    }

}




