package com.zcloud.modules.sys.controller;

import com.zcloud.common.utils.R;
import com.zcloud.modules.sys.entity.SysUserEntity;
import com.zcloud.modules.sys.form.SysLoginForm;
import com.zcloud.modules.sys.service.SysCaptchaService;
import com.zcloud.modules.sys.service.SysUserService;
import com.zcloud.modules.sys.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 */
@RestController
@Api(tags = "登录接口")
public class SysLoginController extends AbstractController {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserTokenService sysUserTokenService;
    @Resource
    private SysCaptchaService sysCaptchaService;

    /**
     * 验证码
     */
    @PostMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     */
    @PostMapping("/sys/login")
    @ApiOperation("登录")
    public R login(@RequestBody SysLoginForm form) throws IOException {
        try {
            //用户信息
            SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

            //账号不存在、密码错误
            if (user == null || "2".equals(user.getType()) || "3".equals(user.getType()) || !user.getPassword().equals(new Sha256Hash(form.getPassword(), form.getUsername()).toHex())) {
                return R.error(200, "账号或密码不正确");
            }

            //账号锁定
            if (user.getStatus() == 0) {
                return R.error(200, "账号已被锁定,请联系管理员");
            }

            //生成token，并保存到数据库
            R r = sysUserTokenService.createToken(user.getUserId());
            r.put("userId", user.getUserId());
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(200, e.getMessage());
        }
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    @ApiOperation("退出登录")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }

    /**
     * 刷新token
     */
    @PostMapping("/sys/refreshToken")
    @ApiOperation("刷新token")
    public R refreshToken() {
        sysUserTokenService.refreshToken(getUserId());
        return R.ok();
    }
}
