package com.ruoyi.system.service.video.impl;


import com.alibaba.fastjson2.JSONObject;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.IccClient;
import com.dahuatech.icc.oauth.http.IccTokenResponse;
import com.dahuatech.icc.oauth.model.v202010.OauthConfigUserPwdInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.video.ext.RestTemplateConfig;
import com.ruoyi.system.domain.video.ext.TokenDTO;
import com.ruoyi.system.domain.video.util.RSAUtil;
import com.ruoyi.system.service.video.IccTokenService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Properties;

@Service
public class IccTokenServiceImpl implements IccTokenService {

    //基础信息
    private String host;
    private int port;
    private String username;
    private String password;
    private String clientId;
    private String clientSecret;
    private boolean isHttp;
    private String token;

    //从icc设置中获取信息
    public void setInfo(){
        Properties properties = new Properties();
        InputStream in=null;
        try{
            in = getClass().getResourceAsStream("/config/icc.properties");
            if(in == null){
                throw new IOException();
            }
            properties.load(in);
            host = properties.getProperty("host");
            port = Integer.parseInt(properties.getProperty("port"));
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            clientId = properties.getProperty("clientId");
            clientSecret = properties.getProperty("clientSecret");
            isHttp = Boolean.parseBoolean(properties.getProperty("isHttp"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //信息填充后获取key
    public String getKey() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        setInfo();
        //拼接url
        String url = "https://"+host+":"+port+"/evo-apigw/evo-oauth/1.0.0/oauth/public-key";
        //调用http接口访问url，调用icc密钥接口，返回密钥
        RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        Map data = (Map)jsonObject.get("data");
        String key = data.get("publicKey").toString();
        return key;
    }

    //Token获取
    public String getToken() throws Exception {
        setInfo();
        String url ="https://"+host+":"+port+"/evo-apigw/evo-oauth/1.0.0/oauth/extend/token";
        TokenDTO getTokenRequest = new TokenDTO();
        String publicKey = getKey();
        getTokenRequest.setGrant_type("password");
        getTokenRequest.setUsername(username);
        //新版没找到icc中RSAUtil
        getTokenRequest.setPassword(RSAUtil.encrypt(password, publicKey));
        getTokenRequest.setClient_id(clientId);
        getTokenRequest.setClient_secret(clientSecret);
        getTokenRequest.setPublic_key(publicKey);

        RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
        //Request作为JSON数据传入
        ResponseEntity<String> response = restTemplate.postForEntity(url, getTokenRequest, String.class);
        Map data = (Map) JSONObject.parseObject(response.getBody()).get("data");
        token = data.get("access_token").toString();
        return token;
    }


    //通过sdk获取token
    public IccTokenResponse.IccToken getTokenInfo(String host, String clientId, String clientSecret, String username, String password, boolean isHttp, String port) throws ClientException {
        OauthConfigUserPwdInfo oauthConfigUserPwdInfo = new OauthConfigUserPwdInfo(host, clientId, clientSecret, username, password, isHttp, port);
        IccClient iccClient = new IccClient(oauthConfigUserPwdInfo);
        return iccClient.getAccessToken();
    }


}
