package com.ruoyi.common.core.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.GatewayUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;

/**
 * web层通用数据处理
 *
 * @author ruoyi
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 返回成功
     */
    public AjaxResult<Void> success() {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult<Void> error() {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult<Void> success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult<Void> error(String message) {
        return AjaxResult.error(message);
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult<Void> toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected AjaxResult<Void> toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }

    /**
     * 获取用户缓存信息
     */
    public LoginUser getLoginUser() {
        return SecurityUtils.getLoginUser();
    }

    /**
     * 获取登录用户id
     */
    public String getUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取登录部门id
     */
    public String getDeptId() {
        return getLoginUser().getDeptId();
    }

    /**
     * 获取登录用户名
     */
    public String getUsername() {
        return getLoginUser().getUsername();
    }

    /**
     * 网关
     * user：
     * %7B%22principal%22%3A%7B%22userName%22%3A%22zhangsan%22%2C%22orgId%22%3Anull%2C%22orgName%22%3Anull%2C%22permissions%22%3A%5B%5D%7D%2C%22user_name%22%3A%22zhangsan%22%2C%22scope%22%3A%5B%22all%22%2C%22PRODUCT_API%22%2C%22MEMBER_READ%22%5D%2C%22id%22%3A%22f744fda7453e479993ac66748011f922%22%2C%22exp%22%3A1640833535%2C%22jti%22%3A%22aba7beff-b10b-4da8-becc-b673f015464f%22%2C%22user_group_id%22%3A2%2C%22client_id%22%3A%22tpbd%22%7D
     *
     * @return
     */
    public GatewayUser getGateWayUser() {
        try {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String userStr = request.getHeader("user");
            if (StrUtil.isNotBlank(userStr)) {
                userStr = URLDecoder.decode(userStr, "UTF-8");
                JSONObject userJsonObject = JSONUtil.parseObj(userStr);
                JSONObject principalObject = userJsonObject.getJSONObject("principal");
                GatewayUser userDTO = new GatewayUser();
                userDTO.setUserId(userJsonObject.getStr("id"));
                userDTO.setUsername(principalObject.getStr("userName"));
                userDTO.setOrgId(principalObject.getStr("orgId"));
                userDTO.setOrgName(principalObject.getStr("orgName"));
                userDTO.setUserGroupId(userJsonObject.getStr("user_group_id"));
                userDTO.setRoles(Convert.toList(String.class, principalObject.get("permissions")));
                logger.info("当前网关请求用户：{}", userDTO);
                return userDTO;
            }
            return null;
        } catch (Exception e) {
            return null;
        }

    }

}
