package cn.qihangerp.service.external.sph;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 微信小店「上传图片」：{@code upload_type=1}（URL）、{@code resp_type=1}（返回 {@code img_url}）。
 * <p>文档：{@code https://developers.weixin.qq.com/doc/store/shop/API/apimgnt/resource/api_img_upload.html}</p>
 *
 * @author guochengyu
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WeixinShopEcImageUploadService {

    private final ExternalSphProperties props;
    private final WeixinShopEcHttpClient httpClient;

    /**
     * 将业务侧 HTTPS 图链转为微信侧 {@code img_url}；已是 {@code mmecimage.cn/p/} 前缀则原样返回。
     */
    public String ensureImgUrl(String accessToken, String sourceUrl) throws Exception {
        if (!StringUtils.hasText(sourceUrl)) {
            throw new IllegalArgumentException("图片 URL 为空");
        }
        String u = sourceUrl.trim();
        if (u.startsWith("https://mmecimage.cn/p/") || u.startsWith("http://mmecimage.cn/p/")) {
            return u.startsWith("http://") ? u.replace("http://", "https://") : u;
        }
        String base = props.getImageUploadUrl();
        if (!StringUtils.hasText(base)) {
            throw new IllegalStateException("external.sph.image-upload-url 未配置");
        }
        String token = accessToken.trim();
        String q = base
                + (base.contains("?") ? "&" : "?")
                + "access_token=" + URLEncoder.encode(token, StandardCharsets.UTF_8)
                + "&upload_type=1&resp_type=1";
        JSONObject body = new JSONObject();
        body.put("img_url", u);
        String raw = httpClient.postJson(q, body.toJSONString(), Duration.ofSeconds(props.getHttpReadTimeoutSeconds()));
        if (!WeixinShopEcHttpClient.isBizOk(raw)) {
            throw new IllegalStateException("微信上传图片失败: " + WeixinShopEcHttpClient.formatWxError(raw));
        }
        JSONObject root = JSON.parseObject(raw);
        JSONObject pic = root.getJSONObject("pic_file");
        if (pic == null || !StringUtils.hasText(pic.getString("img_url"))) {
            throw new IllegalStateException("微信上传图片未返回 img_url: " + WeixinShopEcLogSupport.snippet(raw, 400));
        }
        return pic.getString("img_url").trim();
    }

    /**
     * 按出现顺序上传并去重（同一源 URL 只上传一次）。
     */
    public java.util.List<String> uploadDistinctInOrder(String accessToken, java.util.List<String> sourceUrls) throws Exception {
        if (sourceUrls == null || sourceUrls.isEmpty()) {
            return java.util.List.of();
        }
        Set<String> done = new LinkedHashSet<>();
        java.util.List<String> out = new java.util.ArrayList<>();
        for (String s : sourceUrls) {
            if (!StringUtils.hasText(s)) {
                continue;
            }
            String key = s.trim();
            if (done.contains(key)) {
                continue;
            }
            done.add(key);
            out.add(ensureImgUrl(accessToken, key));
        }
        return out;
    }
}
