package com.example.demo.controller;



import com.example.demo.model.KaptchaCodeRequest;
import com.example.demo.model.KaptchaCodeResponse;
import com.example.demo.result.ResponseData;
import com.example.demo.result.ResponseUtil;
import com.example.demo.service.IKaptchaService;
import com.example.demo.utils.CookieUtil;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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


@RestController
// 不打包为：@RequestMapping("/user")
@RequestMapping("/api/user")
public class CaptchaController {

    @Autowired
    IKaptchaService kaptchaService;

    /**
     * 获取验证码
     */
    @GetMapping("/kaptcha")
    public ResponseData getKaptchaCode(HttpServletResponse response) {
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.getKaptchaCode();
        Cookie cookie = CookieUtil.genCookie("kaptcha_uuid", kaptchaCodeResponse.getUuid(), "/", 60);
        cookie.setHttpOnly(true);
//        cookie.setDomain("localhost:8085");//setDomain要和setHttpOnly搭配使用。
        response.addCookie(cookie);
        return new ResponseUtil<>().setData(kaptchaCodeResponse.getImageCode(),kaptchaCodeResponse.getUuid());

    }

    @PostMapping("/kaptcha")
    public ResponseData validKaptchaCode(@RequestBody KaptchaCodeRequest request, HttpServletRequest httpServletRequest) {
//        KaptchaCodeRequest request = new KaptchaCodeRequest();
////        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
//        request.setUuid(uuid);
//        request.setCode(code);
        kaptchaService.validateKaptchaCode(request);
        return new ResponseUtil<>().setData(null);


    }
}
