package com.corewing.app.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.corewing.app.common.Result;
import com.corewing.app.dto.SysLoginRequest;
import com.corewing.app.entity.SysUser;
import com.corewing.app.service.SysUserService;
import com.corewing.app.util.I18nUtil;
import com.corewing.app.util.IpUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台管理用户 Controller
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    private final SysUserService sysUserService;

    public SysUserController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * 后台管理登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody SysLoginRequest request, HttpServletRequest httpRequest) {
        try {
            // 获取登录IP
            String loginIp = IpUtil.getClientIp(httpRequest);

            // 执行登录
            String token = sysUserService.login(request.getUsername(), request.getPassword(), loginIp);

            // 查询用户信息
            SysUser user = sysUserService.getByUsername(request.getUsername());

            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userId", user.getId());
            data.put("username", user.getUsername());
            data.put("realName", user.getRealName());

            return Result.success(I18nUtil.getMessage("user.login.success"), data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 后台管理登出
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success(I18nUtil.getMessage("user.logout.success"));
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Result<SysUser> getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        SysUser user = sysUserService.getById(userId);
        // 隐藏密码
        user.setPassword(null);
        return Result.success(user);
    }
}
