package org.springblade.modules.obs.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

@Service
@Data
public class ObsService {
    @Value("${obs.endpoint}")
    private String endPoint;
    @Value("${obs.access-key}")
    private String ak;
    @Value("${obs.secret-key}")
    private String sk;
    @Value("${obs.bucket-name}")
    private String bucketName;
    private String GENERATE_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode";
    private String GENERATE_CODE_URL_UNLIMIT = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
    public String postObject(MultipartFile file) throws IOException {
        String accessUrl = IdUtil.simpleUUID()+"-"+file.getOriginalFilename();
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
		PutObjectResult putObjectResult = obsClient.putObject(bucketName, accessUrl, file.getInputStream());
		System.out.println("************putObjectResult"+putObjectResult);
//		return "https://"+bucketName+"."+endPoint+"/"+accessUrl;
		return "https://music.nanyue6688.com/obsfile"+"/"+accessUrl;
    }

    public String postObject(InputStream inputStream,String fileName) throws IOException {
        String accessUrl = IdUtil.simpleUUID()+"-"+fileName;
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        obsClient.putObject(bucketName, accessUrl, inputStream);
        return "https://music.nanyue6688.com/obsfile"+"/"+accessUrl;
    }

    public String getCode(Map<String, String> params) throws IOException {
        String url = GENERATE_CODE_URL + "?access_token=" + params.get("access_token");
        params.remove("access_token");
        HttpResponse result = HttpRequest.post(url)
                .body(JSON.toJSONString(params), "application/json")
                .execute();
        InputStream inputStream = result.bodyStream();
        return postObject(inputStream, "code.png");
    }

    public String getUnlimitCode(Map<String, String> params) throws IOException {

        String url = GENERATE_CODE_URL_UNLIMIT + "?access_token=" + params.get("access_token");
        params.remove("access_token");
        HttpResponse result = HttpRequest.post(url)
                .body(JSON.toJSONString(params), "application/json")
                .execute();
        InputStream inputStream = result.bodyStream();
        return postObject(inputStream, "code.png");
    }
}
