package cn.pluss.platform.controller;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.common.AliyunService;
import cn.pluss.platform.config.OssConfig;
import cn.pluss.platform.config.StsConfig;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.userApp.UserAppService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.auth.ServiceSignature;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;


/**
 * 阿里云相关接口，获取stsToken等
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("aliyun")
@Slf4j
public class AliyunController {

    private final UserAppService userAppService;

    private final AliyunService aliyunService;

    private final OssConfig ossConfig;

    private final StsConfig stsConfig;

    /**
     * 获取上传图片签名
     * @param content
     * @return
     */
    @GetMapping("/signature")
    public Result<String> getSignature(String content) throws UnsupportedEncodingException {
        String toSign = URLDecoder.decode(content, "UTF-8");
        String s = ServiceSignature.create().computeSignature(ossConfig.getKeysecret(), toSign);

        String result = "OSS " + ossConfig.getKeyid() + ":" + s;
        return ResultGenerator.genSuccessResult(result);
    }

    @GetMapping("/stsToken")
    public Object getStsToken() {
        JSONObject result = new JSONObject();
        UserApp userApp = userAppService.queryUserAppByToken();
        AssumeRoleResponse.Credentials credentials = aliyunService.stsToken(userApp.getUserId() + "");
        JSONObject json = (JSONObject) JSON.toJSON(credentials);
        result.putAll(json);
        result.put("statusCode", 200);
        return result;
    }
}
