package com.yeejoin.amos.boot.module.jxiop.biz.controller;

import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;


/**
 * TODO 临时方案，后续要优化该方案
 *
 * @ProjectName amos-qms
 * @Author yangyang
 * @CreateTime 2024-02-20 10:29
 * @Description
 **/
@RestController
@TycloudResource(module = "OAuth", value = "OAuth")
@RequestMapping(value = "/bigscreen/oauth")
@Api(tags = "大屏对接")
@Slf4j
public class OAuthResource {

    public static final String SECRETKEY = "qaz";
    private final static String AUTHORIZE = "http://%s/authorize?redirect_uri=%s";
    private final static String AUTOLOGIN = "http://%s/autologin?token=%s&userId=%s&redirectURI=%s";
    private final static String BIGSCREEN = "/vizagfun/jepc?appId=jepc1&token=%s&top=monitor&bottom=ovarall";
    @Value("${appKey:AMOS_ADMIN}")
    private String APP_KEY;
    @Value("${product:AMOS-WEB-ADMIN}")
    private String PRODUCT;
    @Value("${redirect.host:iiet-jepcc.powerchina.cn:8088}")
    private String host;

    @TycloudOperation(needAuth = false, ApiLevel = UserType.PUBLIC)
    @GetMapping("/redirect")
    public void getAuth(@RequestParam("loginId") String loginId, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (ValidationUtil.isEmpty(loginId) || ValidationUtil.isEmpty(password)) {
            response.sendRedirect(String.format(AUTHORIZE, host, getRedirectURI(null)));
        }
        String redirectUrl;
        // 已取得认证用户信息，执行相应操作…
        RequestContext.setAppKey(APP_KEY);
        RequestContext.setProduct(PRODUCT);
        // 登录
        IdPasswordAuthModel idPasswordAuthModel = new IdPasswordAuthModel();
        idPasswordAuthModel.setLoginId(loginId);
        idPasswordAuthModel.setPassword(password);
        FeignClientResult<HashMap<String, Object>> feignClientResult = null;
        try {
            feignClientResult = Privilege.authClient.idpassword(idPasswordAuthModel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (feignClientResult == null || feignClientResult.getStatus() != 200) {
            redirectUrl = String.format(AUTHORIZE, host, getRedirectURI(null));
            log.info("用户[{}]未在平台创建。。。", loginId);
            response.sendRedirect(redirectUrl);
        }
        String userId = (String) feignClientResult.getResult().get("userId");
        String amosToken = (String) feignClientResult.getResult().get("token");
        redirectUrl = String.format(AUTOLOGIN, host, amosToken, userId, getRedirectURI(String.format(BIGSCREEN,amosToken)));
        log.info("重定向访问地址：{}", redirectUrl);
        response.sendRedirect(redirectUrl);
    }

    public String getRedirectURI(String redirectUrl) {
        if (StringUtils.isEmpty(redirectUrl)) {
            return "";
        }
        return URLEncoder.encode(redirectUrl);
    }

}
