package com.mortals.xhx.base.login.web;

import java.awt.image.BufferedImage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortals.xhx.base.system.valid.model.ValidCodeEntity;
import com.mortals.xhx.base.system.valid.service.ValidCodeService;
import com.mortals.xhx.base.system.valid.web.ValidCodeForm;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mortals.framework.util.SecurityImage;
import com.mortals.framework.web.BaseCRUDJsonController;
import com.mortals.xhx.base.login.service.GifSecurityImage;

@RestController
@RequestMapping("securitycode")
public class SecurityCodeController
	extends BaseCRUDJsonController<ValidCodeService, ValidCodeForm, ValidCodeEntity, Long> {
    @Autowired
    private ValidCodeService validCodeService;

    @RequestMapping("createCode")
    public void createCode(HttpServletRequest request, HttpServletResponse response) {

	// 获取默认难度和长度的验证码
	String securityCode = validCodeService.createImageValidCode(request.getSession().getId(),
		super.getRequestIP(request));

	// int imageType = ParamUtil.getInt("securityImage", 1);
	int imageType = 0;
	switch (imageType) {
	case 1:
	    BufferedImage image = SecurityImage.createImage(securityCode);
	    super.doResponseImage(response, image);
	    break;

	default:
	    // 默认图验
	    byte[] content = GifSecurityImage.createGifImage(securityCode);
	    doResponseGif(response, content);
	    break;
	}

	// // 获取默认难度和长度的验证码
	// String securityCode =
	// validCodeService.createImageValidCode(request.getSession().getId(),
	// super.getRequestIP(request));
	// BufferedImage image = SecurityImage.createImage(securityCode);
	// super.doResponseImage(response, image);
    }

    protected void doResponseGif(HttpServletResponse response, byte[] content) {
	try {
	    response.setHeader("Pragma", "No-cache");
	    response.setHeader("Cache-Control", "No-cache");
	    response.setDateHeader("Expires", 0);
	    response.setContentType("image/gif");
	    IOUtils.write(content, response.getOutputStream());
	} catch (Exception e) {
	    log.error("验证码图片传输异常-->" + e.getMessage());
	}
    }

}
