package com.css.simulation.resource.server.adapter.controller;

import api.common.pojo.common.ResponseBodyVO;
import api.common.pojo.constants.DictConstants;
import api.common.pojo.param.MinioParameter;
import api.common.util.StringUtil;
import api.common.util.TimeUtil;
import com.css.simulation.resource.server.infra.feign.service.FileDownService;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//文件上传下载
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileDownService fileDownService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseBodyVO<Map<String, String>> uploadWj(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        //获取文件类型
        String type = request.getParameter("type");
//        String objectPath = request.getParameter("objectPath");
        if (multipartFile != null) {
            String fileName = "";
            Integer nowTime = TimeUtil.getRq(new Date(), 0);
            String randomCode = StringUtil.getRandomCode();
            if (type.equals(DictConstants.VEHICLE_IMG_FILE)) {
                fileName = "/" + DictConstants.VEHICLE_IMG_FILE + "/" + nowTime + "/" + randomCode + "/" + multipartFile.getOriginalFilename();
            } else {
                new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "文件类型错误！");
            }
            ResponseBodyVO<String> response = fileDownService.upload(multipartFile, fileName);
            if (response.isStatus()) {
                String previewUrl = response.getInfo();
                Map<String, String> map = new HashMap<>();
                map.put("previewUrl", previewUrl);
                map.put("fileName", fileName);
                return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, map);
            }
            new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "上传失败！");
        }
        return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "文件流file为空，请检查！");
    }

    @PostMapping(value = "/download")
    public void download(HttpServletResponse response, @RequestBody @Validated MinioParameter parms) throws IOException {
        Response download = fileDownService.download(parms);
        Response.Body body = download.body();
        InputStream inputStream = body.asInputStream();
        downloadForHttp(parms.getObjectName(), inputStream, response, 1024);
    }


    public void downloadForHttp(String fileName, InputStream in, HttpServletResponse response, int bufferSize) throws IOException {
        int idx = fileName.lastIndexOf("/");
        fileName = fileName.substring(idx + 1, fileName.length());

        log.info("下载----" + fileName);
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        copyBytes(in, response.getOutputStream(), bufferSize);
    }

    public static void copyBytes(InputStream in, OutputStream out, int bufferSize) throws IOException {
        byte[] buffer = new byte[bufferSize];
        for (int bytesRead = in.read(buffer); bytesRead >= 0; bytesRead = in.read(buffer)) {
            out.write(buffer, 0, bytesRead);
        }
    }

    //从minio获取文件列表
    @PostMapping(value = "/queryList")
    public List<String> queryList(@RequestBody @Validated MinioParameter parms) {
        List<String> list = fileDownService.list(parms).getInfo();
        return list;
    }

    @PostMapping(value = "/queryList1")
    public List<String> queryList1(@RequestBody @Validated MinioParameter parms) {
        List<String> list = fileDownService.listDeepOne(parms).getInfo();
        return list;
    }


}
