package com.ruoyi.gysl.login.controller;

/**
 * @author dong
 * @since 2024/5/22 15:50
 */

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
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.entity.BasicInformation;
import com.ruoyi.gysl.login.dto.response.UserMainResponse;
import com.ruoyi.gysl.login.dto.response.UserResponse;
import com.ruoyi.gysl.login.service.LoginTokenService;
import com.ruoyi.gysl.service.BasicInformationService;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 单点登陆
 */
@Api(tags = "企业端单点登陆")
@RestController
@RequestMapping("/system/singlelogin")
public class SingleLoginController {


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

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

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

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


    @Resource
    private LoginTokenService loginTokenService;

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

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

    @Resource
    private BasicInformationService basicInformationService;

    /**
     * 统一登陆
     */
    @ApiOperation("统一登陆")
    @GetMapping("/login")
    public void login(HttpServletResponse response) throws IOException {
        //变成参数模式,appid 用于校验提交的来源地址，生产环境会校验，试用环境暂不校验
        String scUrl = "clientUrl=" + URLEncoder.encode(returnUrl, "UTF-8") + "&appid=" + enterpriseAppId;
        //加密后的客户端地址
        scUrl = Base64.getEncoder().encodeToString(scUrl.getBytes());
        //最终跳转地址
        String jumpurl = url + "?scUrl=" + URLEncoder.encode(scUrl, "UTF-8");
        // 添加请求头
        response.setHeader("Content-Type", "application/json");
        response.setHeader("X-Requested-With", "XMLHttpRequest");
        response.sendRedirect(jumpurl);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户信息", response = UserResponse.class)
    @GetMapping("/getInfo")
    public AjaxResult getInfo(String clientToken) throws Exception {
        HttpResponse response = HttpRequest.get(infoUrl)
                .form("clienttoken", clientToken)
                .addHeaders(generationHeader())
                .execute();
        System.out.println(response.body());
        String responseBody;
        int statusCode = response.getStatus();
        if (statusCode == 200) {
            // 获取响应内容
            responseBody = response.body();
            JSONObject jsonObj = JSONUtil.parseObj(responseBody);
            JSONObject dataObj = jsonObj.getJSONObject("data");
            //判断是法人用户
            if ("ep".equals(dataObj.get("usertype"))) {
                JSONObject mainobj = dataObj.getJSONObject("mainbody");
                UserResponse res = JSONUtil.toBean(dataObj, UserResponse.class);
                UserMainResponse req = JSONUtil.toBean(mainobj, UserMainResponse.class);
                Long count = basicInformationService.lambdaQuery()
                        .eq(BasicInformation::getTyshxydm, req.getUscc())
                        .or()
                        .eq(BasicInformation::getXmfrdwxz, req.getEpname()).count();
                if (count > 0) {
                    String token = loginTokenService.singleLogin(req.getUscc(), req.getEpname(),
                            "02", null, null);
                    res.setToken(token);
                    res.setMain(req);
                    return AjaxResult.success(res);
                }else {
                    throw new ServiceException("贵公司无需参与苏州工业园区工业上楼相关填报工作。系统将即刻为您返回企业服务综合平台界面，以便您处理其他业务事宜!");
                }
            } else {
                throw new ServiceException("该用户不是企业法人");
            }
        } else {
            throw new ServiceException("未知异常请联系管理员");
        }
    }


    /**
     * 退出登录
     *
     * @param clienttoken clienttoken
     * @return 响应类
     */
    @ApiOperation(value = "退出登录")
    @GetMapping("/enterpriseLogout")
    public AjaxResult enterpriseLogout(@RequestParam("clienttoken") String clienttoken) {
        String url = logoutUrl + "?clienttoken=" + clienttoken;
        HttpResponse execute = HttpUtil.createGet(url)
                .addHeaders(generationHeader())
                .execute();
        String str;
        // 获取响应状态码
        int statusCode = execute.getStatus();
        if (statusCode == 200) {
            str = "退出成功";
        } else {
            str = "退出失败";
        }
        return AjaxResult.success(str);
    }

    /**
     * 正式环境需要的请求头
     *
     * @return 请求头
     */
    private Map<String, String> generationHeader() {
        // 定义时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String format = LocalDateTime.now().format(formatter);
        //正式端需要请求头
        HashMap<String, String> headers = new HashMap<>();//存放请求头，可以存放多个请求头
        headers.put("appid", enterpriseAppId);
        headers.put("time", format);
        headers.put("sign", DigestUtil.md5Hex(enterpriseAppId + enterpriseAppsecret + format));
        return headers;
    }
}