package com.wechat.service;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.random.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.wechat.common.utils.NumberUtils;
import com.wechat.global.base.dao.RedisWithExpiryTimeDao;

import cn.apiclub.captcha.Captcha;
import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer;
import cn.apiclub.captcha.noise.CurvedLineNoiseProducer;
import cn.apiclub.captcha.text.producer.DefaultTextProducer;
import cn.apiclub.captcha.text.renderer.DefaultWordRenderer;

@Service
public class CaptchaService {

	@Autowired
	private RedisWithExpiryTimeDao captchaRedisDao;

	@Value("#{configProperties['captcha.expirationTime']}")
	private String captchaExpirationTime;

	/**
	 * 获取图形验证码
	 * 
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("restriction")
	public String next(HttpServletResponse response) throws IOException {
		String base64Image="";
		try {
			List<Color> colors = new ArrayList<>();
			// 预设颜色 深灰
			Color drakgray = new Color(166,164,164);
			colors.add(drakgray);
			// 预设字体
			List<Font> fonts = new ArrayList<>();
			fonts.add(new Font("Arial", Font.BOLD, 40));
			fonts.add(new Font("Courier", Font.BOLD, 40));
			// 随机字母
			char[] numberChar = new char[] { 'a', 'b', 'B', 'c', 'd', 'D', 'e', 'f', 'g', 'G', 'h', 'H', 'i', 'j', 'k',
					'L', 'm', 'M', 'n', 'O', 'p', 'q', 'r', 'R', 's', 't', 'T', 'u', 'v', 'w', 'x', 'y', 'Y', 'z' };
			
			/*设置背景的渐进*/
	        GradiatedBackgroundProducer gbp=new GradiatedBackgroundProducer();
	        gbp.setFromColor(new Color(245,231,231));
	        gbp.setToColor(new Color(245,231,231));


			// 生成验证码
			Captcha captcha = new Captcha.Builder(140, 65)
					.addText(new DefaultTextProducer(4, numberChar), new DefaultWordRenderer(colors, fonts))
					.addBackground(gbp)
					.addNoise(new CurvedLineNoiseProducer(drakgray, 1.0f))
					.addNoise(new CurvedLineNoiseProducer(drakgray, 1.0f)).build();
			String answer = captcha.getAnswer();
			String uuid = R.UU16();
			captchaRedisDao.insert(uuid, answer, NumberUtils.stringToInt(captchaExpirationTime, 300));
			Cookie cookie = new Cookie("uuid", uuid);
			cookie.setPath("/");
			response.addCookie(cookie);
			BufferedImage image = captcha.getImage(); 
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
//			ServletOutputStream out = response.getOutputStream();
//			ImageIO.write(image, "png", out);
//			out.close();
            base64Image = new sun.misc.BASE64Encoder().encodeBuffer(baos.toByteArray()).trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return base64Image;
	}
}
