package com.sw.mes.auth.config;

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.auth.domain.AuthUser;
import com.sw.mes.auth.service.AuthUserService;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 * 晶科sso接入配置
 *
 * @Author：wanjia
 * @Date：2024/3/23 15:43
 */
@Configuration
@Slf4j
public class JinkoSSOConfig {

    private static final RestTemplate restTemplate = new RestTemplate();

    private static String clientId;

    private static String clientSecret;

    private static String host;

    private static AuthUserService authUserService;

    @Autowired
    public void setAuthUserService(AuthUserService authUserService1) {
        authUserService = authUserService1;
    }

    @Value("${jinko.sso.client.id}")
    public void setClientId(String client_id) {
        clientId = client_id;
    }

    @Value("${jinko.sso.client.secret}")
    public void setClientSecret(String client_secret) {
        clientSecret = client_secret;
    }

    @Value("${jinko.sso.client.host}")
    public void setHost(String _host) {
        host = _host;
    }

    public static String composeAuthorization() {
        return "Bearer " + JwtUtil.createJwtToken("MES_LJ_TY_5041-NCJNL58R", "62d4d19d-e40f-4d51-8051-5d040c676eca");
    }

    /**
     * 根据单点登录返回的code获取token等用户信息
     *
     * @param code
     * @return Map<String, String>
     * key1:uid
     * key2:token header中的token
     * key3:jk_token 晶科sso返回的token
     */
    public static Result<Map<String, String>> accessToken(String code) {
        String uri = host + "/JIP/IAM/IAM4_OAuth_getToken_JWT";
        Map<String, String> result = new HashMap<>(3);
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.put("client_id", Collections.singletonList(clientId));
        body.put("client_secret", Collections.singletonList(clientSecret));
        body.put("code", Collections.singletonList(code));
        //设置请求信息
        RequestEntity<MultiValueMap<String, String>> requestEntity = RequestEntity
                .post(URI.create(uri))
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .header("Authorization", composeAuthorization())
                .accept(MediaType.ALL)
                .acceptCharset(StandardCharsets.UTF_8)
                .body(body);
        try {
            ResponseEntity<JSONObject> mapResponseEntity = restTemplate.postForEntity(uri, requestEntity, JSONObject.class);
            //返回状态码
            HttpStatus statusCode = mapResponseEntity.getStatusCode();
            if (null != mapResponseEntity.getBody() && !mapResponseEntity.getBody().containsKey("error") && HttpStatus.OK.equals(statusCode)) {
                String access_token = mapResponseEntity.getBody().getString("access_token");
                result.put("jk_token", access_token);
                Result<String[]> userResult = getUserInfo(access_token);
                if (userResult.getCode() != 200) {
                    return ResultGenerator.fail(userResult.getMessage());
                }
                String[] userInfo = userResult.getData();
                result.put("token", userInfo[0]);
                result.put("uid", userInfo[1]);
                return ResultGenerator.success(result);
            } else {
                return ResultGenerator.fail(mapResponseEntity.getBody().getString("error_description"));
            }
        } catch (Exception e) {
            log.error("error_in_accessToken", e);
            return ResultGenerator.fail(e.getMessage());
        }
    }

    private static Result<String[]> getUserInfo(String accessToken) {
        String uri = host + "/JIP/IAM/IAM4_OAuth_getUserInfo_JWT";
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.put("access_token", Collections.singletonList(accessToken));
        //设置请求信息
        RequestEntity<MultiValueMap<String, String>> requestEntity = RequestEntity
                .post(URI.create(uri))
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .header("Authorization", composeAuthorization())
                .accept(MediaType.ALL)
                .acceptCharset(StandardCharsets.UTF_8)
                .body(body);
        try {
            ResponseEntity<JSONObject> mapResponseEntity = restTemplate.postForEntity(uri, requestEntity, JSONObject.class);
            //返回状态码
            if (null != mapResponseEntity.getBody() && mapResponseEntity.getBody().containsKey("ret")) {
                int ret = mapResponseEntity.getBody().getInteger("ret");
                if (ret < 0) {
                    return ResultGenerator.fail(mapResponseEntity.getBody().getString("msg"));
                }
                String uid = mapResponseEntity.getBody().getString("uid");
                //这边需要set cache 确保后续登录可以通过
                AuthUser user = authUserService.findByLoginName(uid);
                if (user == null) {
                    return ResultGenerator.fail("账号不存在，请联系管理员");
                }
                return ResultGenerator.success(new String[]{authUserService.cacheUser(user, "web"), uid});
            }
        } catch (Exception e) {
            log.error("error_in_accessToken", e);
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.fail(null);
    }

}
