package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.entity.AdminUser;
import com.zhentao.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/admin/auth")
@CrossOrigin(origins = "*")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> params) {
        try {
            String username = params.get("username");
            String password = params.get("password");
            
            if (username == null || password == null) {
                return Result.error("用户名和密码不能为空");
            }
            
            AdminUser user = authService.login(username, password);
            
            if (user == null) {
                return Result.error("用户名或密码错误");
            }
            
            // 生成token（这里简化处理，实际项目应使用JWT）
            String token = authService.generateToken(user);
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            
            // 返回用户信息（不包含密码）
            user.setPassword(null);
            data.put("userInfo", user);
            data.put("permissions", new String[]{"*"});
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success("退出成功");
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/userInfo")
    public Result<Map<String, Object>> getUserInfo(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token == null || token.isEmpty()) {
                return Result.error(401, "未授权");
            }
            
            // 验证token并获取用户信息
            AdminUser user = authService.getUserByToken(token);
            
            if (user == null) {
                return Result.error(401, "token无效");
            }
            
            Map<String, Object> data = new HashMap<>();
            user.setPassword(null);
            data.put("userInfo", user);
            data.put("permissions", new String[]{"*"});
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(401, "获取用户信息失败");
        }
    }
}

