package com.yxproject.start.api;

import com.yxproject.start.entity.UserInfo;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("user")
public class UserApi {

    @PostMapping("login")
    public Map<String, Object> submitLogin(@RequestBody String jsonStr) {
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        Subject currentUser = SecurityUtils.getSubject();
        // 把用户名和密码封装为 UsernamePasswordToken 对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            currentUser.login(token);
            UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            resultMap.put("status", 200);
            resultMap.put("message", "登录成功");
            resultMap.put("user", userInfo);
        } catch (UnknownAccountException e) {
            resultMap.put("status", 201);
            resultMap.put("message", "账号不存在！");
        } catch (IncorrectCredentialsException e1) {
            resultMap.put("status", 202);
            resultMap.put("message", "密码错误！");
        } catch (Exception e) {
            resultMap.put("status", 500);
            resultMap.put("message", "用户名密码错误");
        }
        return resultMap;
    }

    @RequestMapping("logout")
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
    }
}
