package com.jkcredit.invoice.controller.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.jkcredit.invoice.model.entity.user.User;
import com.jkcredit.invoice.service.user.AuthenticationService;
import com.jkcredit.invoice.service.user.UserService;
import com.jkcredit.invoice.util.MD5Util;
import com.jkcredit.invoice.util.RespR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @author: sunzhaoning
 * @create: 2019-05-29 14:02
 * @version: V1.0
 **/
@Api(tags = "用户登录")
@RestController
@RequestMapping("/auth/login")
public class AuthenticationController {

    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private UserService userService;

    @ApiOperation(value="用户登录", notes="用户登录")
    @PostMapping("")
    public RespR login(@RequestBody User user) {
        //获取用户名
        String userName = user.getUserName();
        //根据用户名获取用户信息
        User userInDataBase = userService.selectUserByUserName(userName);
        JSONObject jsonObject = new JSONObject();
        //获取密码
        String password = user.getPassword();
        if (userInDataBase == null) {
            return new RespR<>(Boolean.FALSE, "用户不存在");
        } else if (1==userInDataBase.getIsLock()) {
            return new RespR<>(Boolean.FALSE, "该账号已被锁定");
        }else if(2==userInDataBase.getIsLock()){
            return new RespR<>(Boolean.FALSE, "该账号已停用");
        }else if (!StrUtil.equals(MD5Util.encrypt(password), userInDataBase.getPassword())) {
            return new RespR<>(Boolean.FALSE, "密码不正确");
        } else {
            //获取token
            String token = authenticationService.getToken(userInDataBase);
            //移除密码
            userInDataBase.setPassword("");
            jsonObject.put("token", token);
            jsonObject.put("user", userInDataBase);
        }
        return new RespR<>(jsonObject);
    }
}
