package com.mosty.common.core.business.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.core.business.entity.vo.LoginResponseVO;
import com.mosty.common.core.util.HttpClientUtil;
import com.mosty.common.core.util.RSAUtil;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Objects;

import static com.google.common.base.Charsets.UTF_8;

/**
 * <p>
 * 应用信息表 前端控制器
 * </p>
 *
 * @author kevin
 * @since 2022-04-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("yjxx/token")
@Api(tags = "获取托尔思预警token")
@Slf4j
public class TokenController {

    /**
     * 获取预警token
     *
     * @param idCard 添加应用信息请求
     * @return 添加结果
     */
    @GetMapping("getToken")
    public ResponseResult<LoginResponseVO> getToken(@RequestParam("idCard") String idCard) throws Exception {
        String rsa = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCKtrYCRHk/++b/yZteGW5pSfKynGjfNZ9TkC/+v8SrAZ8Gb24lEbB0zUp/rXabNHfSY6X3z6tCCA7pCig0TQIQT5iIz1eBuMPWcY61U1sySqVANu4IxchLzaPmKamttz2GXKby94rVa71eTVZ2kC0Vi424PjfL7C/iBQsgvoPV8wIDAQAB";
        String url = "https://80.35.1.27:7001/login/app?key=";
        log.info("公钥：{}", rsa);
        log.info("身份证号：{}", idCard);
        String rsaStr = RSAUtil.encryptByPubKey(idCard, rsa);
        String idCardRas = URLEncoder.encode(rsaStr, "UTF-8");
        String urls = url + idCardRas;

        HashMap<String, String> loginMap = Maps.newHashMap();
        loginMap.put("Content-Type", "multipart/form-data");
        loginMap.put("Authorization", "Basic eXE6YWRtaW4=");
        loginMap.put("User-Agent", "trs");

        HttpResponse response = HttpClientUtil.postRequest(urls, loginMap);
        String body = EntityUtils.toString(response.getEntity(), UTF_8);

        JSONObject jsonObject = JSONObject.parseObject(body);
        String accessToken = jsonObject.getString("access_token");
        log.info("获取到的access_token={}", accessToken);

        if (response.getStatusLine().getStatusCode() != 200) {
            log.warn("调用登陆服务异常{}", JSON.toJSONString(response));
            throw new RuntimeException("POST调用异常 : " + response.getStatusLine().getStatusCode());
        }


        HashMap<String, String> cookieMap = Maps.newHashMap();
        cookieMap.put("Authorization", "Bearer " + accessToken);

        String getCookieUrl = "http://80.35.1.27:7000/dispatchWarning/yjxx/getYjxxList?page=2&pageSize=10&type=9&lev=0&datasource=&datetype=nolimit&startdate=&enddate=&bklx=0&emphasiscode=&searchType=1&otherinfo=&yjlx=0";
        HttpResponse cookieResponse = HttpClientUtil.postRequest(getCookieUrl, cookieMap);
        Header firstHeader = cookieResponse.getFirstHeader("Set-Cookie");

        log.warn("调用cookie接口的 Http status = {}", response.getStatusLine().getStatusCode());

        if (Objects.isNull(firstHeader)) {
            log.warn("响应体cookie为空 ------{}", JSON.toJSONString(response.getAllHeaders()));
            throw new RuntimeException("POST调用异常 : " + response.getStatusLine().getStatusCode());
        }
        log.info("获取到的cookie={}", firstHeader.getValue());

        LoginResponseVO loginResponseVO = new LoginResponseVO();
        loginResponseVO.setLoginResponseBody(body);
        loginResponseVO.setLoginResponseCookie(firstHeader.getValue());

        log.info("响应体 ------{}", JSON.toJSONString(loginResponseVO));
        return ResponseResult.success(loginResponseVO);

    }

    public static void main(String[] args) {
        try {
            LoginResponseVO vo = new TokenController().getToken("510603198807207837").getData();
            System.err.println(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
