package cn.sikey.tools.service.agora;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.sikey.framework.common.pojo.CommonResult;
import cn.sikey.tools.config.AgoraConfig;
import cn.sikey.tools.config.HttpUtil;
import cn.sikey.tools.controller.app.agora.vo.DabizLicenseV2ActiveReqVO;
import cn.sikey.tools.controller.app.agora.vo.DabizLicenseV2ActiveRespVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: qin
 * @Date: 2025/3/31
 * @Description: 声网服务
 */
@Service
@Slf4j
public class AgoraServiceImpl implements AgoraService {

    @Resource
    private HttpUtil httpUtil;

    @Resource
    private AgoraConfig agoraConfig;

    /**
     * 激活
     *
     * @param dabizLicenseV2ActiveReqVO 激活
     * @return
     */
    @Override
    public CommonResult dabizLicenseV2Active(DabizLicenseV2ActiveReqVO dabizLicenseV2ActiveReqVO) {
        log.info("[声网服务-激活]请求参数：{}", dabizLicenseV2ActiveReqVO);
        Map<String, String> params = new HashMap<>();
        params.put("pid", agoraConfig.getPid());
        params.put("licenseKey", dabizLicenseV2ActiveReqVO.getLicenseKey());
        params.put("appid", agoraConfig.getAppid());

        String plainCredentials = agoraConfig.getApiKey() + ":" + agoraConfig.getSecret();
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));

        String authorizationHeader = "Basic " + base64Credentials;
        Map<String, String> headers = Map.of("Authorization", authorizationHeader);
        String result = httpUtil.doPostWithQueryParams(agoraConfig.getUrl() + agoraConfig.getPath(), params, headers);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        int code = Integer.parseInt(String.valueOf(jsonObject.get("code")));
        String message = String.valueOf(jsonObject.get("message"));
        JSONObject data = jsonObject.getJSONObject("data");

        if (code == HttpStatus.SC_OK) {
            DabizLicenseV2ActiveRespVO.ResponseData responseData = JSONUtil.toBean(data, DabizLicenseV2ActiveRespVO.ResponseData.class);
            log.info("[声网服务-激活]返回数据：{}", dabizLicenseV2ActiveReqVO);
            return CommonResult.success(responseData);
        } else {
            log.warn("[声网服务-激活]声网返回数据失败：{}，message：{}", dabizLicenseV2ActiveReqVO, message);
            return CommonResult.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, message);
        }
    }

}


