package cn.iocoder.yudao.module.system.controller.admin.auth;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.auth.myVo.LoginRequestVo;
import cn.iocoder.yudao.module.system.controller.admin.auth.myVo.LoginUserInfo;
import cn.iocoder.yudao.module.system.controller.admin.auth.myVo.PtResult;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.conf.PtUrlConf;
import cn.iocoder.yudao.module.system.controller.admin.myUtils.MyHttpUtils;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.service.auth.AdminAuthService;
import cn.iocoder.yudao.module.system.service.permission.MenuService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.social.SocialClientService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 认证")
@RestController
@RequestMapping("/system/auth")
@Validated
@Slf4j
public class AuthController {

    @Autowired
    private PtUrlConf ptUrlConf;

    @Resource
    private AdminAuthService authService;
    @Resource
    private AdminUserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private SocialClientService socialClientService;

    @Resource
    private SecurityProperties securityProperties;

    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public CommonResult<AuthLoginRespVO> login(@RequestBody @Valid AuthLoginReqVO reqVO) {
        return success(authService.login(reqVO));
    }

    @GetMapping("/checkPdToken")
    @PermitAll
    @Operation(summary = "验证平台token")
    public CommonResult<PtResult<LoginUserInfo>> checkPdToken(String code, String redirect_uri) {
        if (null != code && !"".equals(code)) {
            return CommonResult.success(authService.checkPdToken(code, redirect_uri));

        }
        return CommonResult.success(null);
    }

    @PostMapping("/logout")
    @PermitAll
    @Operation(summary = "登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (StrUtil.isNotBlank(token)) {
            authService.logout(token, LoginLogTypeEnum.LOGOUT_SELF.getType());
        }
        return success(true);
    }

    @PostMapping("/refresh-token")
    @PermitAll
    @Operation(summary = "刷新令牌")
    @Parameter(name = "refreshToken", description = "刷新令牌", required = true)
    public CommonResult<AuthLoginRespVO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return success(authService.refreshToken(refreshToken));
    }

    @GetMapping("/get-permission-info")
    @Operation(summary = "获取登录用户的权限信息")
    public CommonResult<AuthPermissionInfoRespVO> getPermissionInfo() {
        // 1.1 获得用户信息
        AdminUserDO user = userService.getUser(getLoginUserId());
        if (user == null) {
            return success(null);
        }

        // 1.2 获得角色列表
        Set<Long> roleIds = permissionService.getUserRoleIdListByUserId(getLoginUserId());
        if (CollUtil.isEmpty(roleIds)) {
            return success(AuthConvert.INSTANCE.convert(user, Collections.emptyList(), Collections.emptyList()));
        }
        List<RoleDO> roles = roleService.getRoleList(roleIds);
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.getStatus().equals(role.getStatus())); // 移除禁用的角色

        // 1.3 获得菜单列表
        Set<Long> menuIds = permissionService.getRoleMenuListByRoleId(convertSet(roles, RoleDO::getId));
        List<MenuDO> menuList = menuService.getMenuList(menuIds);
        menuList = menuService.filterDisableMenus(menuList);

        // 2. 拼接结果返回
        return success(AuthConvert.INSTANCE.convert(user, roles, menuList));
    }

    @PostMapping("/register")
    @PermitAll
    @Operation(summary = "注册用户")
    public CommonResult<AuthLoginRespVO> register(@RequestBody @Valid AuthRegisterReqVO registerReqVO) {
        return success(authService.register(registerReqVO));
    }

    // ========== 短信登录相关 ==========

    @PostMapping("/sms-login")
    @PermitAll
    @Operation(summary = "使用短信验证码登录")
    public CommonResult<AuthLoginRespVO> smsLogin(@RequestBody @Valid AuthSmsLoginReqVO reqVO) {
        return success(authService.smsLogin(reqVO));
    }

    @PostMapping("/send-sms-code")
    @PermitAll
    @Operation(summary = "发送手机验证码")
    public CommonResult<Boolean> sendLoginSmsCode(@RequestBody @Valid AuthSmsSendReqVO reqVO) {
        authService.sendSmsCode(reqVO);
        return success(true);
    }

    @PostMapping("/reset-password")
    @PermitAll
    @Operation(summary = "重置密码")
    public CommonResult<Boolean> resetPassword(@RequestBody @Valid AuthResetPasswordReqVO reqVO) {
        authService.resetPassword(reqVO);
        return success(true);
    }

    // ========== 社交登录相关 ==========

    @GetMapping("/social-auth-redirect")
    @PermitAll
    @Operation(summary = "社交授权的跳转")
    @Parameters({
            @Parameter(name = "type", description = "社交类型", required = true),
            @Parameter(name = "redirectUri", description = "回调路径")
    })
    public CommonResult<String> socialLogin(@RequestParam("type") Integer type,
                                            @RequestParam("redirectUri") String redirectUri) {
        return success(socialClientService.getAuthorizeUrl(
                type, UserTypeEnum.ADMIN.getValue(), redirectUri));
    }

    @PostMapping("/social-login")
    @PermitAll
    @Operation(summary = "社交快捷登录，使用 code 授权码", description = "适合未登录的用户，但是社交账号已绑定用户")
    public CommonResult<AuthLoginRespVO> socialQuickLogin(@RequestBody @Valid AuthSocialLoginReqVO reqVO) {
        return success(authService.socialLogin(reqVO));
    }












    // =======================================对接平台====================================================
    @PostMapping("/ptLogin")
    @PermitAll
    @Operation(summary = "使用账号密码登录平台")
    public PtResult<LoginUserInfo> ptLogin(HttpServletRequest request,LoginRequestVo reqVO) {
        String appkey = request.getHeader("appkey");
        if (null == appkey || "".equals(appkey)) {
            return new PtResult<>("400", "请求头appkey缺失", null, null, null, null);
        }
        // JSON格式POST请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("appkey", appkey);

        String jsonBody = JSON.toJSONString(reqVO);
        String rStr = MyHttpUtils.postJson(ptUrlConf.getLoginUrl(), headers, jsonBody);

        PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
        return result;
    }

    @GetMapping("/getUserInfoByToken")
    @PermitAll
    @Operation(summary = "接⼊单点登录后，⽤token换取⽤户信息")
    public PtResult<LoginUserInfo> getUserInfoByToken(HttpServletRequest request) {
        String appkey = request.getHeader("appkey");
        String authorization = request.getHeader("Authorization");
        if (null == appkey || "".equals(appkey) || null == authorization || "".equals(authorization)) {
            return new PtResult<>("400", "请求头appkey或Authorization缺失", null, null, null, null);
        }
        // 带参数和请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("appkey", appkey);
        headers.put("Authorization", authorization);


        String rStr = MyHttpUtils.get(ptUrlConf.getGetUserByToken(), headers, null);

        PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
        return result;
    }

    @GetMapping("/getUserInfoByCode")
    @PermitAll
    @Operation(summary = "接⼊单点登录后，⽤code换取⽤户信息")
    public PtResult<LoginUserInfo> getUserInfoByCode(HttpServletRequest request, @RequestParam String code, @RequestParam String redirect_uri) {
        String appkey = request.getHeader("appkey");
        if (null == appkey || "".equals(appkey)) {
            return new PtResult<>("400", "请求头appkey缺失", null, null, null, null);
        }
        // 带参数和请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("appkey", appkey);

        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("redirect_uri", redirect_uri);

        String rStr = MyHttpUtils.get(ptUrlConf.getGetUserByCode(), headers, params);

        PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
        return result;
    }


    @GetMapping("/logOffToken")
    @PermitAll
    @Operation(summary = "注销token")
    public PtResult<LoginUserInfo> logOffToken(HttpServletRequest request) {
        String appkey = request.getHeader("appkey");
        String authorization = request.getHeader("Authorization");
        if (null == appkey || "".equals(appkey) || null == authorization || "".equals(authorization)) {
            return new PtResult<>("400", "请求头appkey或Authorization缺失", null, null, null, null);
        }
        // 带参数和请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("appkey", appkey);
        headers.put("Authorization", authorization);


        String rStr = MyHttpUtils.get(ptUrlConf.getLogOffToken(), headers, null);

        PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
        return result;
    }


    @PostMapping("/refToken")
    @PermitAll
    @Operation(summary = "刷新token")
    public PtResult<LoginUserInfo> refToken(HttpServletRequest request, String refreshToken) {
        String appkey = request.getHeader("appkey");
        if (null == appkey || "".equals(appkey)) {
            return new PtResult<>("400", "请求头appkey缺失", null, null, null, null);
        }
        // JSON格式POST请求
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("appkey", appkey);

        Map<String, Object> params = new HashMap<>();
        params.put("refreshToken", refreshToken);

        String jsonBody = JSON.toJSONString(params);
        String rStr = MyHttpUtils.postJson(ptUrlConf.getRefTokenUrl(), headers, jsonBody);

        PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
        return result;
    }

    @GetMapping("/logOffTokenAndJump")
    @PermitAll
    @Operation(summary = "注销token并跳转指定页面")
    public PtResult<LoginUserInfo> logOffTokenAndJump(HttpServletRequest request, @RequestParam String redirectUri) {
        String appkey = request.getHeader("appkey");
        String authorization = request.getHeader("Authorization");
        if (null == appkey || "".equals(appkey) || null == authorization || "".equals(authorization)) {
            return new PtResult<>("400", "请求头appkey或Authorization缺失", null, null, null, null);
        }
        // 带参数和请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("appkey", appkey);
        headers.put("Authorization", authorization);


        String rStr = MyHttpUtils.get(ptUrlConf.getLogOffTokenAndJump() + redirectUri, headers, null);

        PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
        return result;
    }
}
