package com.tashow.cloud.user.controller.app.auth;

import cn.hutool.core.util.StrUtil;
import com.tashow.cloud.common.enums.UserTypeEnum;
import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.user.controller.app.auth.vo.*;
import com.tashow.cloud.security.security.config.SecurityProperties;
import com.tashow.cloud.security.security.core.util.SecurityFrameworkUtils;
import com.tashow.cloud.systemapi.api.social.SocialClientApi;
import com.tashow.cloud.systemapi.api.social.dto.SocialWxJsapiSignatureRespDTO;
import com.tashow.cloud.user.convert.auth.AuthConvert;
import com.tashow.cloud.user.service.auth.MemberAuthService;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.tashow.cloud.common.pojo.CommonResult.success;
import static com.tashow.cloud.security.security.core.util.SecurityFrameworkUtils.getLoginUserId;


/**
 * 用户 APP - 认证
 */
@RestController
@RequestMapping("/member/auth")
@Validated
@Slf4j
public class AppAuthController {

    @Resource
    private MemberAuthService authService;

    @Resource
    private SocialClientApi socialClientApi;

    @Resource
    private SecurityProperties securityProperties;

    /**
     * 使用手机 + 密码登录
     * @param reqVO
     * @return
     */
    @PostMapping("/login")
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> login(@RequestBody @Valid AppAuthLoginReqVO reqVO) {
        return success(authService.login(reqVO));
    }

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

    /**
     * 刷新令牌
     * @param refreshToken 刷新令牌
     * @return
     */
    @PostMapping("/refresh-token")
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return success(authService.refreshToken(refreshToken));
    }

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

    /**
     * 使用手机 + 验证码登录
     * @param reqVO
     * @return
     */
    @PostMapping("/sms-login")
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> smsLogin(@RequestBody @Valid AppAuthSmsLoginReqVO reqVO) {
        return success(authService.smsLogin(reqVO));
    }


    /**
     * 发送手机验证码
     * @param reqVO
     * @return
     */
    @PostMapping("/send-sms-code")
    @PermitAll
    public CommonResult<Boolean> sendSmsCode(@RequestBody @Valid AppAuthSmsSendReqVO reqVO) {
        authService.sendSmsCode(getLoginUserId(), reqVO);
        return success(true);
    }

    /**
     * 校验手机验证码
     * @param reqVO
     * @return
     */
    @PostMapping("/validate-sms-code")
    @PermitAll
    public CommonResult<Boolean> validateSmsCode(@RequestBody @Valid AppAuthSmsValidateReqVO reqVO) {
        authService.validateSmsCode(getLoginUserId(), reqVO);
        return success(true);
    }

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

    /**
     * 社交授权的跳转
     * @param type 社交类型
     * @param redirectUri 回调路径
     * @return
     */
    @GetMapping("/social-auth-redirect")
    @PermitAll
    public CommonResult<String> socialAuthRedirect(@RequestParam("type") Integer type,
                                                   @RequestParam("redirectUri") String redirectUri) {
        return success(authService.getSocialAuthorizeUrl(type, redirectUri));
    }

    /**
     * 社交快捷登录，使用 code 授权码
     * @param reqVO
     * @return
     */
    @PostMapping("/social-login")
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> socialLogin(@RequestBody @Valid AppAuthSocialLoginReqVO reqVO) {
        return success(authService.socialLogin(reqVO));
    }

    /**
     * 微信小程序的一键登录
     * @param reqVO
     * @return
     */
    @PostMapping("/weixin-mini-app-login")
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> weixinMiniAppLogin(@RequestBody @Valid AppAuthWeixinMiniAppLoginReqVO reqVO) {
        return success(authService.weixinMiniAppLogin(reqVO));
    }

    /**
     * 创建微信 JS SDK 初始化所需的签名
     * @param url
     * @return
     */
    @PostMapping("/create-weixin-jsapi-signature")
    @PermitAll
    public CommonResult<SocialWxJsapiSignatureRespDTO> createWeixinMpJsapiSignature(@RequestParam("url") String url) {
        SocialWxJsapiSignatureRespDTO signature = socialClientApi.createWxMpJsapiSignature(
                UserTypeEnum.MEMBER.getValue(), url).getCheckedData();
        return success(AuthConvert.INSTANCE.convert(signature));
    }

}
