package com.ruoyi.gysl.login.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.gysl.login.dto.request.UserInfoRequestDTO;
import com.ruoyi.gysl.login.dto.response.ChiefResponse;
import com.ruoyi.gysl.login.dto.response.ThirdUserInfoResponse;
import com.ruoyi.gysl.login.service.LoginTokenService;
import com.ruoyi.gysl.login.util.HMAC256Config;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;

/**
 * 政务端登录
 *
 * @author du
 * @since 2024/6/4 9:53
 */
@Api(tags = "政务端单点登录")
@RequestMapping("/system/chief")
@RestController
public class ChiefController {

    @Value("${clientId}")
    private String clientId;

    @Value("${clientSecret}")
    private String clientSecret;


    @Value("${appkey}")
    private String appkey;

    @Value("${getInfoId}")
    private String getInfoId;

    @Value("${getAllInfo}")
    private String getAllInfo;

    @Resource
    private LoginTokenService loginTokenService;

    @ApiOperation("政务端登录")
    @GetMapping
    public AjaxResult login(
            @RequestParam("userToken") String userToken,
            @RequestParam("timespan") String timespan,
            @RequestParam("signature") String signature
    ) throws Exception {
        String encode = Base64.encode((HMAC256Config.HmacSHA256(clientId + timespan + userToken, clientSecret)));
        if (encode.equals(signature)) {
            //经济大脑（政务端）获取用户信息接口
            UserInfoRequestDTO req = new UserInfoRequestDTO();
            req.setClientId(clientId);
            req.setUserToken(userToken);
            //请求头
            HashMap<String, String> headers = new HashMap<>();//存放请求头，可以存放多个请求头
            headers.put("signature", Base64.encode(HMAC256Config.HmacSHA256(JSONUtil.parse(req).toString() + timespan, clientSecret)));
            headers.put("timespan", timespan);
            //请求体
            JSONObject jsonObject = new JSONObject();//存放参数
            jsonObject.set("clientId", clientId);
            jsonObject.set("userToken", userToken);
            HttpResponse response = HttpRequest.post(getInfoId)
                    .addHeaders(headers)
                    .body(jsonObject.toString())
                    .execute();
            // 获取响应状态码
            if (response.getStatus() == 200) {
                //经济大脑（政务端）获取用户信息接口
                JSONObject jsonObj = JSONUtil.parseObj(response.body());
                ThirdUserInfoResponse res = JSONUtil.toBean(jsonObj.get("data").toString(), ThirdUserInfoResponse.class);
                //政务通获取用户信息接口（可选）
                String getInfo = getAllInfo + "?id=" + res.getUserId() + "&appkey=" + appkey;
                HttpResponse getMain = HttpRequest.get(getInfo).execute();
                if (getMain.getStatus() == 200) {
                    JSONObject dataJson = JSONUtil.parseObj(getMain.body());
                    ChiefResponse bean = JSONUtil.toBean(dataJson, ChiefResponse.class);
                    //判断几个政务端用户,等待商量结果
                    bean.setToken(loginTokenService.singleLogin(bean.getAccountName(),
                            bean.getName(),
                            "01", bean.getMobile(),bean.getEmail()));
                    return AjaxResult.success(bean);
                } else {
                    throw new ServiceException("登陆失败");
                }
            }
        } else {
            throw new ServiceException("登陆失败");
        }
        throw new ServiceException("登陆失败");
    }


//    @ApiOperation("政务根据信用代码返回跳转路由")
//    @GetMapping("/returnUrl")
//    public AjaxResult returnUrl(@RequestParam("code") String code,
//                                @RequestParam("userToken") String userToken) throws Exception {
//        //请求的地址
//        StringBuilder url = new StringBuilder("http://172.21.10.12/sipsg-enterprise-mobile-manage/#/loginVerify?");
//        //当前时间的时间戳
//        String timespan = Long.toString(System.currentTimeMillis());
//        UserInfoRequestDTO req = new UserInfoRequestDTO();
//        req.setClientId(clientId);
//        req.setUserToken(userToken);
//        String signature = Base64.encode(HMAC256Config.HmacSHA256(JSONUtil.parse(req).toString() + timespan, clientSecret));
//        url.append("signature=").append(signature);
//        url.append("&timespan=").append(timespan);
//        url.append("&userToken=").append(userToken);
//        url.append("&gourl=")
//                .append(URLEncoder.encode("https://172.21.10.12/sipsg-enterprise-mobile-manage/#/workPlat/search/enterprise/detail?id="+code,"UTF-8"));
//        url.append("&clientid=").append(clientId);
//        return AjaxResult.success(url.toString());
//    }
}
