package com.example.springdemo.controller;

import com.example.springdemo.bean.Car;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Response;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Map;

@Slf4j
@RestController
public class HelloController {

    final Car car;

    public HelloController(Car car) {
        this.car = car;
    }

    /**
     * application/octet-stream 形式上传图片
     *
     * @param bytes 图片数据
     * @return success
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String getPicFile(@RequestBody byte[] bytes, HttpServletRequest request) {
        log.info("this image name is [{}]", request.getContentType());
        try (FileOutputStream fileOuputStream = new FileOutputStream("image.jpg")){
            fileOuputStream.write(bytes);
            log.info("save image success");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "SUCCESS";
    }

    /**
     * image/jpeg 形式上传图片
     *
     * @param bytes 图片字节流
     * @param request 请求
     * @return 200ok
     */
    @RequestMapping(value = "/vi/snap/uploadFile", method = RequestMethod.POST)
    public int getImage(@RequestBody byte[] bytes, HttpServletRequest request) {
        log.info("ContentType : {}", request.getContentType());
        try (FileOutputStream fileOuputStream = new FileOutputStream("snap.jpg")){
            fileOuputStream.write(bytes);
            log.info("save snap image success");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Response.SC_OK;
    }

    /**
     * hashMap 转化成表单字符串
     *
     * @param map 图片数据
     * @return 字符串
     */
    public static String map2Form(Map<String, Object> map) {
        StringBuilder stringBuilder = new StringBuilder();
        if (map == null) {
            return stringBuilder.toString();
        } else {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        }
    }

    @RequestMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello, %s!", name);

    }
}
