package com.yihu.wlyy.web.common.util;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 患者端验证码生成控制器。验证码生成后保存到Redis中，并将Redis的Key与图片路径返回。
 * 客户端获取图片，并由用户输入后，与redis的key一块返回，用于验证是否出错。
 *
 * @author Sand
 * @created 2016/09/28
 */
@Api(description = "验证码")
@RestController
@RequestMapping(value = "/patient/captcha", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CaptchaController extends BaseController {
    private Map<String, String> captchaCache = new ConcurrentHashMap<>();
    private DefaultKaptcha captchaProducer = new DefaultKaptcha();

    public CaptchaController() {
        Properties properties = new Properties();
        properties.put("kaptcha.textproducer.font.color", "blue");
        properties.put("kaptcha.textproducer.font.size", "45");
        properties.put("kaptcha.textproducer.char.length", "4");
        properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");

        Config config = new Config(properties);
        captchaProducer.setConfig(config);
    }

    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation("生成验证码，用于第一次请求")
    public String createCaptcha(){
        try{
            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }

    @RequestMapping(value = "/{legacy_key}", method = RequestMethod.POST)
    @ApiOperation("刷新验证码，需提供第一次生成验证码返回的key")
    public String refreshCaptcha(@PathVariable("legacy_key") String legacyKey){
        try{
            cleanCaptcha(legacyKey);

            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }

    @RequestMapping(value = "/{key}", method = RequestMethod.GET)
    @ApiOperation("校验证码，提供key及用户输入的验证码")
    public String verifyCaptcha(@PathVariable("key") String key,
                                @RequestParam("text") String text){
        try{
            boolean pass = false;
            String captcha = captchaCache.get(key);
            if (captcha != null && captcha.equals(text.toLowerCase())){
                pass = true;
                cleanCaptcha(key);
            }

            return write(200, "ok", "pass", pass);
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }

    private String generateCaptcha() throws IOException {
        String captchaText = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        String base64Img = new BASE64Encoder().encode(outputStream.toByteArray());
        String key = "captcha:" + UUID.randomUUID().toString() + ":text";

        Map<String, String> data = new HashMap<>();
        data.put("key", key);
        data.put("image", base64Img);
        data.put("format", "png");

        captchaCache.put(key, captchaText.toLowerCase());

        return write(200, "ok", "data", data);
    }

    private void cleanCaptcha(String key){
        captchaCache.remove(key);
    }
}
