package io.hmit.modules.zlb.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.hmit.modules.zlb.constants.Constants;
import io.hmit.modules.zlb.utils.IrsSignRes;
import io.hmit.modules.zlb.utils.IrsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author jie.chen
 * @date 2022-03-30 15:49
 */
@Component
public class AuthService {


    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    private RestTemplate restTemplate;

    @PostConstruct
    void init() {
        restTemplate = restTemplateBuilder.build();
    }


    public String getTokenByTicketId(String ticketId) {

        HttpHeaders headers = getHttpHeaders(Constants.ACCESS_TOKEN_URL);
        JSONObject body = new JSONObject();
        body.put("appId", Constants.APP_ID);
        body.put("ticketId", ticketId);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(Constants.ACCESS_TOKEN_URL, request, String.class);
        return checkResponse(stringResponseEntity).getJSONObject("data").getString("accessToken");
    }


    public JSONObject getUserInfoByToken(String accessToken) {
        HttpHeaders headers = getHttpHeaders(Constants.GET_USER_INFO_URL);
        JSONObject body = new JSONObject();
        body.put("token", accessToken);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(Constants.GET_USER_INFO_URL, request, String.class);
        return checkResponse(stringResponseEntity).getJSONObject("data");
    }

    public JSONObject getZlbRequestId(JSONObject requestBody) {

        HttpHeaders headers = IrsUtils.generateHeader(Constants.GET_ACCEPT_USER_INFO_URL, "POST", Constants.IRS_AK, Constants.IRS_SK);

//        JSONObject body = new JSONObject();
//        body.put("certNo","s");
//        body.put("certName","s");
//        body.put("certType","s");
//        body.put("nation","s");
//        body.put("isNetId","s");
//        body.put("remark","s");
//        body.put("mobile","s");
//        body.put("fkSceneCode","SC-OT01-HT01-a95e63ad-b899-420f-a022-5a180c434b83");
//        body.put("curLoginMetadata","s");

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(Constants.GET_ACCEPT_USER_INFO_URL, request, String.class);
        return checkResponse(stringResponseEntity).getJSONObject("data");
    }

    public JSONObject checkResultByRequestId(String  requestId) {

        HttpHeaders headers = IrsUtils.generateHeader(Constants.GET_REVERIFY_URL, "POST", Constants.IRS_AK, Constants.IRS_SK);

        JSONObject requestBody = new JSONObject();
        requestBody.put("requestId",requestId);


        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(Constants.GET_REVERIFY_URL, request, String.class);
        return checkResponse(stringResponseEntity).getJSONObject("data");
    }

    private JSONObject checkResponse(ResponseEntity<String> stringResponseEntity) {
        if (!stringResponseEntity.getStatusCode().is2xxSuccessful()) {
            //请求失败
            throw new RuntimeException("status:" + stringResponseEntity.getStatusCodeValue() + " " + stringResponseEntity.getBody());
        }
        JSONObject result = JSON.parseObject(stringResponseEntity.getBody());
        if (result.containsKey("errorCode") && result.getString("errorCode") != null && !result.getBooleanValue("success")) {
            //业务错误
            throw new RuntimeException(result.toString());
        }
        return result;
    }

    private HttpHeaders getHttpHeaders(String url) {
        IrsSignRes res = IrsUtils.sign(url, "POST");

        HttpHeaders headers = new HttpHeaders();
        headers.add(Constants.X_BG_HMAC_ACCESS_KEY, res.getAccessKey());
        headers.add(Constants.X_BG_HMAC_ALGORITHM, res.getAlgorithm());
        headers.add(Constants.X_BG_HMAC_SIGNATURE, res.getSignature());
        headers.add(Constants.X_BG_DATE_TIME, res.getDateTime());
        return headers;
    }

}
