package com.infoepoch.pms.dispatchassistant.common.utils;

import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


public class CaptcaUtils {
    /**
     * 算术表达式验证码
     *
     * 1：干扰线的产生
     * 2: 范围随机颜色，随机数
     *
     * @param response
     * @return
     */
    public static  Map<String,Object> drawImageVerificate(HttpServletResponse response){
        SecureRandom random;
        try{
            random = SecureRandom.getInstance("SHA1PRNG");
        }catch (Exception e){
            throw new ValidationException("随机数获取失败");
        }
        //开始进行对算术验证码表达式的拼接
        int num1 = (int)(random.nextDouble()*10 + 1);
        int num2 = (int)(random.nextDouble()*10 + 1);
        int fuhao = random.nextInt(3);//产生一个[0,2]之间的随机整数
        //记录符号
        String fuhaostr = null;
        int result = 0;
        switch (fuhao){
            case 0 : fuhaostr = "+";result = num1 + num2;break;
            case 1: fuhaostr = "-";result = num1 - num2;break;
            case 2 : fuhaostr = "x";result = num1 * num2;break;
            //case 3 : fuhaostr = "/";result = num1 / num2;break;
        }
        //拼接算术表达式,用户图片显示。
        String calc = num1 + " " + fuhaostr +" "+ num2 +" = ?";

        try {
            //输出图片到页面
//            ImageIO.write(image,"JPEG",response.getOutputStream());
            Map<String,Object> map = new HashMap<>();
            map.put("calc",calc);
            map.put("result",result);
            return map;
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 范围随机颜色
     * @param fc
     * @param bc
     * @return
     */
    public static Color getRandomColor(int fc,int bc){
        //利用随机数
        SecureRandom random;
        try{
            random = SecureRandom.getInstance("SHA1PRNG");
        }catch (Exception e){
            throw new ValidationException("随机数获取失败");
        }
        //随机颜色,了解颜色-Color(red,green,blue).rgb三元色 0-255
        if(fc>255)fc = 255;
        if(bc>255)bc = 255;
        int r = fc+random.nextInt(bc-fc);
        int g = fc+random.nextInt(bc-fc);
        int b = fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
    }

    /**
     * 此方法用户产生随机数字母和数字
     * @return
     */
    private static char randomChar(){
        //1:定义验证需要的字母和数字
        String string = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789";
        //2：定义随机对象
        SecureRandom random;
        try{
            random = SecureRandom.getInstance("SHA1PRNG");
        }catch (Exception e){
            throw new ValidationException("随机数获取失败");
        }
        return string.charAt(random.nextInt(string.length()));
    }

}
