package com.sooka.sponest.monitor.dahua.login;//package com.dahuatch.Login;


import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.ruoyi.common.core.domain.R;
import com.sooka.sponest.monitor.dahua.login.bean.LoginFirst;
import com.sooka.sponest.monitor.dahua.login.bean.LoginSecond;
import com.sooka.sponest.monitor.dahua.utils.HttpEnum;
import com.sooka.sponest.monitor.dahua.utils.HttpTestUtils;

import java.util.Map;

/**
 * 创建会话接口
 */
public class Login {

    public static final String ACTION = "/videoService/accounts/authorize";

    //第一次登陆，客户端只传用户名，服务端返回realm、readomKey和encryptType信息。
    private static String firstLogin(String ip, int port, String userName) {
        LoginFirst loginFirst = new LoginFirst();
        loginFirst.setClientType("winpc");
        loginFirst.setUserName(userName);
        String rsp = HttpTestUtils.httpRequest(HttpEnum.POST, ip, port, ACTION, "", new Gson().toJson(loginFirst));
        return rsp;
    }

    //第二次登录，客户端根据返回的信息，按照指定的加密算法计算签名，再带着用户名和签名登陆一次。
    private static String secondLogin(String ip, int port, String userName, String password, String realm, String randomKey) throws Exception {
        LoginSecond snd = new LoginSecond();
        snd.setUserName(userName);
        snd.setClientType("winpc");
        snd.setRandomKey(randomKey);
        snd.setEncryptType("MD5");
        String signature = snd.calcSignature(password, realm);
        snd.setSignature(signature);
        Gson gson = new Gson();
        String ctx = gson.toJson(snd);
        String rsp = HttpTestUtils.httpRequest(HttpEnum.POST, ip, port, ACTION, "", ctx);
        return rsp;
    }

    @SuppressWarnings("unchecked")
    public static String login(String ip, int port, String userName, String password) throws Exception {
        String response = firstLogin(ip, port, userName);
        Map<String, String> responseMap = new Gson().fromJson(response, Map.class);
        String random = responseMap.get("randomKey");
        String realm = responseMap.get("realm");
        response = secondLogin(ip, port, userName, password, realm, random);
        return response;
    }


    /**
     * 调用该登陆方法之前需要修改 baseinfo.properties中ip,port，name，password为当前对接环境
     * 登录的方法，运行之后即可获取到token，进行登录,登陆完成后，必须调用KeepLogin保活接口，否则，2分钟后会登陆过期
     */
    public static void main(String[] args) throws Exception {
        R<?> result = HttpTestUtils.getToken("10.254.1.20", Integer.valueOf(8320), "system", "Admin123");
        String token = result.getData().toString();
        System.out.println("登录成功，token=" + token);
    }
}



