package com.izouma.awesomeadmin.web;

import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.util.VerifyCodeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 
 * <p>验证图片。</p> 
 * 
 * @version 1.0
 * @author 姓名 <br />
 * 更新履历 <br />
 *  日期 : 姓名: 更新内容<br />
 */
@Controller
@RequestMapping("/auth")
public class AuthImageController extends BaseController {

    @RequestMapping(value = "/image", method = RequestMethod.GET)
    @ResponseBody
    public Result image(HttpServletRequest request, HttpServletResponse response) {

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串  
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //存入会话session  
        HttpSession session = request.getSession(true);
        session.setAttribute("rand", verifyCode.toLowerCase());
        //生成图片  
        int w = 200, h = 80;
        try {
            VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
            return new Result(true, verifyCode);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result(false, "验证图片生成失败");
    }

}
