package top.lejings.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.lejings.demo.pojo.Result;
import top.lejings.demo.pojo.Users;
import top.lejings.demo.service.UsersService;
import top.lejings.demo.utils.JwtUtils;

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

/*
* 登录响应
*
* */
@Slf4j
@RestController
@RequestMapping("/user")
public class UsersController {

    @Autowired UsersService usersService;

    /*
    * 接收前端传来的用户对象，目前只传递用户名和密码
    * */
    @PostMapping("/login")
    @CrossOrigin(origins = "http://localhost:82")
    public Result login(@RequestBody Users users){
        log.info("正在进行登录。用户名是：{}",users.getUsername());
        Users u = usersService.login(users);
        //登录成功逻辑
        if(u != null){
            log.info("登录成功，下发jwt令牌");
            Map<String,Object> claims = new HashMap<>();
            claims.put("user_id",u.getUser_id());
            claims.put("username",u.getUsername());
            claims.put("email",u.getEmail());
            String jwt = JwtUtils.generateJwt(claims);//jwt包含了当前员工信息
            log.info("{}",jwt);
            return Result.success(jwt);
        }
        //登录失败，返回错误信息

        return Result.error("用户名或密码错误");
    }

    //注册后自动登录
    @PostMapping("/registered")
    @CrossOrigin(origins = "http://localhost:82")
    public Result register(@RequestBody Users users){
        log.info("正在进行注册操作。用户名为{}，邮箱为{}",users.getUsername(),users.getEmail());
        boolean f = usersService.registered(users);
        if(f){
            return Result.success("注册成功！");
        }
        else{
            //注册失败，用户名或者邮箱已被注册
            return Result.error("此邮箱已被注册");
        }

    }

    @PostMapping("/findpassword/{email}")
    @CrossOrigin(origins = "http://localhost:82")
    public Result findPassword(@PathVariable String email){
        log.info("邮箱为{}",email);
        boolean f  = usersService.findPassword(email);
        if(f){

            return Result.success("密码已经发送");
        }
        else{
            return Result.error("这个邮箱尚未被注册");
        }
    }

    //用户修改个人信息，根据用户id，修改用户名，密码
    @PutMapping("/revise")
    public Result update(@RequestBody Users users){
        usersService.revise(users);
        return Result.success();
    }

//    注销账号
    @DeleteMapping("/logout")
    public Result delete(@RequestBody Users users){
        log.info("开始注销");
        usersService.logout(users);
        return Result.success();
    }

}
