package cn.ysk.cashier.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.ysk.cashier.domain.QiniuContent;
import cn.ysk.cashier.service.QiNiuService;
import cn.ysk.cashier.service.WxService;
import cn.ysk.cashier.utils.CacheKey;
import cn.ysk.cashier.utils.RedisUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class WxServiceImpl implements WxService {

    private final QiNiuService qiNiuService;

    private final RedisUtils redisUtils;
    private static final String APP_ID = "wxd88fffa983758a30";
    private static final String APP_SECRET = "a34a61adc0602118b49400baa8812454";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String QR_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode";

    @Override
    public String getFetchQRCode(Map<String, Object> params) {
        InputStream qrCodeStream = fetchQRCode(params);
        QiniuContent qiniuContent = qiNiuService.uploadByte(IoUtil.readBytes(qrCodeStream),qiNiuService.findCloud());
        redisUtils.set(CacheKey.VIPCODE + params.get("shopId"),qiniuContent.getUrl());
        return qiniuContent.getUrl();
    }

    @Override
    public String getSmallQrcode(String shopId) {
        InputStream shopQRCodeStream = smallQrcode(shopId);
        QiniuContent qiniuContent = qiNiuService.uploadByte(IoUtil.readBytes(shopQRCodeStream),qiNiuService.findCloud());
        return qiniuContent.getUrl();
    }


   public InputStream fetchQRCode(Map<String, Object> params) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("path", "pages/member/index?shopId="+params.get("shopId"));//路径
        jsonObject.addProperty("is_hyaline", true);//是否需要透明底色，为 true 时，生成透明底色的小程序码
        if (params.containsKey("env_version")) jsonObject.addProperty("env_version", "trial");//正式版为 release，体验版为 trial，开发版为 develop
        String accessToken = getAccessToken();
        String url = String.format("%s?access_token=%s", QR_CODE_URL, accessToken);
        return HttpUtil.createPost(url)
                .body(jsonObject.toString(), "application/json")
                .execute()
                .bodyStream();
    }

    public InputStream smallQrcode(String shopId) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("path", "pages/index/index?shopId="+shopId);//路径
        jsonObject.addProperty("is_hyaline", true);//是否需要透明底色，为 true 时，生成透明底色的小程序码
        String accessToken = getAccessToken();
        String url = String.format("%s?access_token=%s", QR_CODE_URL, accessToken);
        return HttpUtil.createPost(url)
                .body(jsonObject.toString(), "application/json")
                .execute()
                .bodyStream();
    }

    private String getAccessToken() {
        String url = String.format("%s?grant_type=client_credential&appid=%s&secret=%s", TOKEN_URL, APP_ID, APP_SECRET);
        String response = HttpUtil.get(url);
        JSONObject jsonResponse = JSONObject.parseObject(response);
        if (!jsonResponse.containsKey("access_token")) {
            throw new RuntimeException("Failed to retrieve access token: " + response);
        }
        return jsonResponse.getString("access_token");
    }
}
