package com.gxwebsoft.auto.controller;

import com.gxwebsoft.auto.dto.QrLoginBindPhoneRequest;
import com.gxwebsoft.auto.dto.QrLoginConfirmRequest;
import com.gxwebsoft.auto.dto.QrLoginGenerateResponse;
import com.gxwebsoft.auto.dto.QrLoginStatusResponse;
import com.gxwebsoft.auto.dto.WechatScanRequest;
import com.gxwebsoft.auto.dto.WechatScanResponse;
import com.gxwebsoft.auto.service.QrLoginService;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证模块
 *
 * @author 科技小王子
 * @since 2025-03-06 22:50:25
 */
@Tag(name = "认证模块")
@RestController
@RequestMapping("/api/qr-login")
public class QrLoginController extends BaseController {

    @Autowired
    private QrLoginService qrLoginService;

    @Autowired
    private com.gxwebsoft.common.system.service.WxService wxService;

    @Autowired
    private javax.servlet.http.HttpServletRequest request;

    /**
     * 生成扫码登录token
     */
    @Operation(summary = "生成扫码登录token")
    @PostMapping("/generate")
    public ApiResult<?> generateQrLoginToken() {
        try {
            QrLoginGenerateResponse response = qrLoginService.generateQrLoginToken(getTenantId());
            return success("生成成功", response);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    /**
     * 检查扫码登录状态
     */
    @Operation(summary = "检查扫码登录状态")
    @GetMapping("/status/{token}")
    public ApiResult<?> checkQrLoginStatus(
            @Parameter(description = "扫码登录token") @PathVariable String token) {
        try {
            QrLoginStatusResponse response = qrLoginService.checkQrLoginStatus(token);
            return success("查询成功", response);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    /**
     * 确认扫码登录
     */
    @Operation(summary = "确认扫码登录")
    @PostMapping("/confirm")
    public ApiResult<?> confirmQrLogin(@Valid @RequestBody QrLoginConfirmRequest request) {
        try {
            QrLoginStatusResponse response = qrLoginService.confirmQrLogin(request);
            return success("确认成功", response);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    /**
     * 扫码操作(可选接口，用于移动端扫码后更新状态)
     */
    @Operation(summary = "扫码操作")
    @PostMapping("/scan/{token}")
    public ApiResult<?> scanQrCode(@Parameter(description = "扫码登录token") @PathVariable String token) {
        try {
            boolean result = qrLoginService.scanQrCode(token);
            return success("操作成功", result);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    /**
     * 公众号关注注册后绑定手机号
     */
    @Operation(summary = "绑定手机号并完成扫码登录")
    @PostMapping("/bind-phone")
    public ApiResult<?> bindPhone(@Valid @RequestBody QrLoginBindPhoneRequest request) {
        try {
            QrLoginStatusResponse response = qrLoginService.bindPhone(request);
            return success("绑定成功", response);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    /**
     * 微信扫码登录确认（H5页面调用）
     */
    @Operation(summary = "微信扫码登录确认")
    @PostMapping("/wechat-scan")
    public ApiResult<?> wechatScanConfirm(@Valid @RequestBody WechatScanRequest request) {
        try {
            WechatScanResponse response = qrLoginService.wechatScanConfirm(request);
            return success("操作成功", response);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    /**
     * 获取微信网页授权 URL（用于 H5 扫码页面重定向）
     */
    @Operation(summary = "获取微信网页授权URL")
    @GetMapping("/wechat-oauth-url")
    public ApiResult<?> getWechatOAuthUrl(@Parameter(description = "扫码登录token") @RequestParam String token) {
        try {
            String appId = wxService.getOfficialAppId(getTenantId());
            // 回调地址，指向 H5 扫码确认页面
            String redirectUri = java.net.URLEncoder.encode(
                "https://" + request.getHeader("Host") + "/wx-scan?token=" + token,
                java.nio.charset.StandardCharsets.UTF_8);
            // 构造微信 OAuth 授权 URL
            String oauthUrl = String.format(
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect",
                appId, redirectUri, token);
            return success("获取成功", oauthUrl);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

}
