package com.nantian.cloud.jljc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nantian.cloud.jljc.service.NginxService;
import com.nantian.cloud.jljc.tools.FtpUtil;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/nginx")
public class NginxController {

    @Autowired
    private NginxService nginxService;

    /**
     * 单文件上传
     */
    @PostMapping("/upload")
    @SysLog("单文件上传（nginx）")
    public R pictureUpload(@RequestParam(value = "file") MultipartFile uploadFile) {
        long begin = System.currentTimeMillis();
        Object result = nginxService.uploadPicture(uploadFile);
       /* String json = "";
        try {
            Object result = nginxService.uploadPicture(uploadFile);
            // 浏览器擅长处理json格式的字符串，为了减少因为浏览器内核不同导致的bug，建议用json
            json = new ObjectMapper().writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }*/
        long end = System.currentTimeMillis();
        log.info("文件上传任务结束，共耗时：" + (end-begin) + "毫秒");
        return R.ok(result);
    }

    /**
     * 多文件上传
     */
    @PostMapping("/uploads")
    @SysLog("多文件上传（nginx）")
    public R picturesUpload(@RequestParam(value = "file") MultipartFile[] uploadFile) {
        long begin = System.currentTimeMillis();
        //Map<Object, Object> map = new HashMap<>();
        Map<Object, Object> map = new HashMap<>(10);

        int count = 0;
        for (MultipartFile file : uploadFile) {
            Object result = nginxService.uploadPicture(file);
            map.put(count, result);
            count++;
        }
        long end = System.currentTimeMillis();
        log.info("文件上传任务结束，共耗时：" + (end-begin) + "毫秒");
        return R.ok(map);
    }

    /**
     * 根据文件路径下载文件
     */
    @GetMapping("/download")
    @SysLog("根据文件路径下载文件（nginx）")
    public R FileDownloadController(String fileUrl, String outfileName, HttpServletResponse response) throws IOException {
        boolean b = FtpUtil.getImages(fileUrl, outfileName, response);
        return b ? R.ok("文件下载成功！") : R.failed("文件下载失败！");
    }

}
