package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.zxing.WriterException;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.WechatService;

import me.chanjar.weixin.common.error.WxErrorException;

/**
 * 微信登录控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/wechat")
public class WechatLoginController extends BaseController
{
    @Autowired
    private WechatService wechatService;

    /**
     * 生成微信登录二维码
     */
    @GetMapping("/qrcode")
    public AjaxResult generateQrCode()
    {
        try
        {
            Map<String, Object> result = wechatService.generateLoginQrCode();
            return AjaxResult.success(result);
        }
        catch (WxErrorException | IOException | WriterException e)
        {
            return AjaxResult.error("生成二维码失败: " + e.getMessage());
        }
    }

    /**
     * 检查登录状态
     */
    @GetMapping("/status")
    public AjaxResult checkLoginStatus(@RequestParam String loginId)
    {
        Map<String, Object> result = wechatService.checkLoginStatus(loginId);
        return AjaxResult.success(result);
    }

    /**
     * 微信回调接口
     */
    @GetMapping("/callback")
    public AjaxResult wechatCallback(
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String state)
    {
        return wechatService.handleWechatCallback(code, state);
    }
}