package com.ruoyi.abuwx.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.web.client.RestTemplate;

/**
 * 微信用户登录Controller
 *
 * @author lujie
 * @date 2025-02-11
 */
@RestController
@RequestMapping("/api/wechat")
public class WeChatController extends BaseController {

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysLoginService loginService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestParam String code) {
        AjaxResult ajax = AjaxResult.success();
        // 使用code获取openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(response);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        if (StrUtil.isBlank(openid)) {
            return AjaxResult.error("登录失败，openid未能获取");
        }
        // 根据openid查询用户信息
        SysUser user = userService.selectUserByOpenid(openid);
        if (user == null) {
            // 新用户，注册逻辑
            user = new SysUser();
            user.setOpenid(openid);
            user.setUserName("微信用户_" + System.currentTimeMillis());
            user.setNickName("微信用户_" + System.currentTimeMillis());
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            userService.insertUser(user);
        }

        String token = loginService.login(user.getUserName(), "123456", "", "");
        ajax.put(Constants.TOKEN, token);
        ajax.put("openid", openid);
        return ajax;
    }
}
