package com.roy.controller;

import com.roy.util.ImageUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author ：楼兰
 * @date ：Created in 2021/1/19
 * @description:
 **/

@RestController
@RequestMapping("/common")
public class LoginController {

    //登录 验证， 这里只需要判断验证码是否正确
    @RequestMapping("/login")
    public Object login(String verifyCode,HttpServletRequest request){
        final String sessionVerifyCode = request.getSession().getAttribute("verifyCode").toString();
        if(sessionVerifyCode.equals(verifyCode)){
            return "success";
        }else{
            return null;
        }
    }

    //用来产生验证码
    @RequestMapping("/verifyCode")
    public void generateImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

        final ImageUtil imageUtil = ImageUtil.getInstance();
        //验证码图片
        final ByteArrayInputStream image = imageUtil.getImage();
        //验证码文字
        final String verifyCode = imageUtil.getStr();
        request.getSession().setAttribute("verifyCode",verifyCode);

        response.setContentType("image/jpeg");
        byte[] bytes = new byte[1024];
        try(final ServletOutputStream out = response.getOutputStream()){
            while (image.read(bytes)!= -1 ){
                out.write(bytes);
            }
        }
    }
}
