package com.storlead.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.storlead.framework.common.util.FileUtil;
import com.storlead.framework.common.util.OssBootUtil;
import com.storlead.framework.common.util.generate.CodeGenerate;
import com.storlead.framework.common.result.Result;
import com.storlead.system.pojo.entity.FileResourceEntity;
import com.storlead.framework.web.properties.FileProperties;
import com.storlead.system.service.FileResourceService;
import com.storlead.system.service.IOSSFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import javax.annotation.Resource;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * <p>
 * 文件系统 前端控制器
 * </p>
 *
 * @author chenkq
 * @since 2022-08-22
 */
@Log4j2
@RestController
@RequestMapping("/oss/file")
@Api(tags="平台中心 - 系统: 公共接口")
public class FileResourceController {

    @Resource
    private FileProperties fileProperties;

    @Resource
    private Environment environment;

    @Resource
    private IOSSFileService ossFileService;

    @Resource
    private FileResourceService fileResourceService;



    @ResponseBody
    @PostMapping("/upload")
    @ApiOperation(value = "公共接口-oss上传", notes = "公共接口-oss上传")
    public Result upload(@ApiParam(value = "上传文件", required = true)@RequestParam("file") MultipartFile file) {

        Result result = new Result();
        try {
            FileUtil.checkSize(fileProperties.getMaxSize(), file.getSize());
            String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
//            if (!documents.contains(suffix)) {
//                return Result.error("请上传pdf、doc、docx、xls、xlsx、ppt、pptx和zip格式!");
//            }
            String typeName = FileUtil.getFileTypeName(suffix);
            String code = CodeGenerate.GenerateFullCode();

            String name = FileUtil.getFileNameNoEx(file.getOriginalFilename());
            FileResourceEntity fileResourceEntity =new FileResourceEntity();
            fileResourceEntity.setFileName(name);
            fileResourceEntity.setFileCode(code);
            fileResourceEntity.setFileSuffix(suffix);
            fileResourceEntity.setFileTypeName(typeName);
            fileResourceEntity.setFileSize(Integer.valueOf((int) (file.getSize() / FileUtil.KB)));
            JSONObject jsonObject = new JSONObject();
            if (Integer.valueOf(0).equals(fileProperties.getMode())) {
//                StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
//                if(Objects.isNull(storePath)){
//                    return  Result.error("上传错误");
//                }
//                fileResourceEntity.setFilePath(fileProperties.getFilePath()+File.separator+storePath.getFullPath());
//                fileResourceService.save(fileResourceEntity);
//                String url = fileProperties.getFilePath()+"/"+storePath.getFullPath();
//                jsonObject.put("url", url);
            } else  {
                String url = ossFileService.upload(file);
                jsonObject.put("url", url);
            }
            jsonObject.put("fileShowName", file.getOriginalFilename());
            jsonObject.put("fileName", file.getName());
            jsonObject.put("fileSize", getFileSize(file.getSize()));
            jsonObject.put("fileExt", suffix);

            result.setResult(jsonObject);
            result.success("上传成功！");

        }catch (Exception e) {
            log.error("--upload -- error =",e);
            return  Result.error("上传错误");
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/documentUpload")
    @ApiOperation(value = "documentUpload 公共接口-oss上传", notes = " documentUpload 公共接口-oss上传")
    public Result documentUpload(@ApiParam(value = "上传文件", required = true)@RequestParam("file") MultipartFile file) {

        Result result = new Result();
        String documents = "pdf doc docx xls xlsx ppt pptx zip";
        try {
            FileUtil.checkSize(fileProperties.getMaxSize(), file.getSize());
            String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
            if (!documents.contains(suffix)) {
                return Result.error("请上传pdf、doc、docx、xls、xlsx、ppt、pptx和zip格式!");
            }
            String typeName = FileUtil.getFileTypeName(suffix);
            String code = CodeGenerate.GenerateFullCode();

            String name = FileUtil.getFileNameNoEx(file.getOriginalFilename());
            FileResourceEntity fileResourceEntity =new FileResourceEntity();
            fileResourceEntity.setFileName(name);
            fileResourceEntity.setFileCode(code);
            fileResourceEntity.setFileSuffix(suffix);
            fileResourceEntity.setFileTypeName(typeName);
            fileResourceEntity.setFileSize(Integer.valueOf((int) (file.getSize() / FileUtil.KB)));
            JSONObject jsonObject = new JSONObject();
            if (Integer.valueOf(0).equals(fileProperties.getMode())) {
                //  StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
                //  if(Objects.isNull(storePath)){
                //      return  Result.error("上传错误");
                //  }
                //  fileResourceEntity.setFilePath(fileProperties.getFilePath()+File.separator+storePath.getFullPath());
                //  fileResourceService.save(fileResourceEntity);
                //  String url = fileProperties.getFilePath()+"/"+storePath.getFullPath();
                //  jsonObject.put("url", url);
            } else  {
                String url = ossFileService.upload(file);
                jsonObject.put("url", url);
            }
            jsonObject.put("fileShowName", file.getOriginalFilename());
            jsonObject.put("fileName", file.getName());
            jsonObject.put("fileSize", getFileSize(file.getSize()));
            jsonObject.put("fileExt", suffix);

            result.setResult(jsonObject);
            result.success("上传成功！");

        }catch (Exception e) {
            log.error("--upload -- error =",e);
            return  Result.error("上传错误");
        }
        return result;
    }


    @GetMapping(value = "/download")
    @ApiOperation(value = "下载", notes = "下载")
    public void download(Long fileId, HttpServletResponse response) throws IOException {
        if (Objects.isNull(fileId)) {
            return;
        }
        FileResourceEntity resource = fileResourceService.getById(fileId);
        if (resource == null) {
            return;
        }
        String url =  fileProperties.getPath().getPath() + File.separator + resource.getFilePath();
        InputStream inputStream ;
//        if (Integer.valueOf(0).equals(resource.getUploadMode())) {
////            String fileUrl = resource.getFilePath();
////            fileUrl = fileUrl.replace(fileProperties.getFilePath()+"/","");
////            String group = fileUrl.substring(0, fileUrl.indexOf("/"));
////            String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
////            byte[] bytes = fastFileStorageClient.downloadFile(group, path, new DownloadByteArray());
//            inputStream = new ByteArrayInputStream(bytes);
//        }else {
//            inputStream = OssBootUtil.downloadObjFileToInputStream(url);
//        }
        inputStream = OssBootUtil.downloadObjFileToInputStream(url);
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        /*
         * 跨域配置
         * */
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");

        String filename = resource.getFileName()+"."+resource.getFileSuffix();
        filename = filename.replace(" ","");
        response.addHeader("content-disposition",
                "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")
                        + ";filename*=utf-8''" + URLEncoder.encode(filename, "UTF-8"));

        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
//从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }

//    @GetMapping(value = "/download-url")
//    @ApiOperation(value = "下载", notes = "下载")
//    public Result downloadUrl(Long fileId) throws IOException {
//        if (Objects.isNull(fileId)) {
//            return Result.error("参数错误");
//        }
//        FileResourceEntity resource = fileResourceService.getById(fileId);
//        if (resource == null) {
//            return Result.error("附未找到");
//        }
//        String url =  fileProperties.getPath().getPath() + File.separator + resource.getFilePath();
//
//        String active = environment.getProperty("spring.profiles.active");
//        String port =  environment.getProperty("server.port");
//        String domainUrl = "";
//        if(active.equals("prod")) {
//            domainUrl = "https://sales.storlead.com/file"+url;
//        } else if (active.equals("test")){
//            domainUrl = "https://sales.test.storlead.com/file"+url;
//        } else if (active.equals("dev")){
//            domainUrl = "http://localhost:"+port+url;
//        }
//        return Result.error(domainUrl);
//    }

//    @GetMapping(value = "/downloadOSS")
//    @ApiOperation(value = "下载", notes = "下载")
//    public void downloadOSS(Long resourceId, HttpServletResponse response) throws IOException {
//        if (resourceId == null) {
//            return;
//        }
//        TargetResource resource = targetResourceService.getById(resourceId);
//        if (resource == null) {
//            return;
//        }
//        String url =  resource.getResourceUrl().substring(resource.getResourceUrl().indexOf(".com/")+5);
//        InputStream inputStream ;
//        if (Integer.valueOf(0).equals(fileProperties.getMode())) {
//            String fileUrl = resource.getResourceUrl();
//            fileUrl = fileUrl.replace(fileProperties.getFilePath()+"/","");
//            String group = fileUrl.substring(0, fileUrl.indexOf("/"));
//            String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
//            byte[] bytes = fastFileStorageClient.downloadFile(group, path, new DownloadByteArray());
//            inputStream = new ByteArrayInputStream(bytes);
//        }else {
//            inputStream = OssBootUtil.downloadObjFileToInputStream(url);
//        }
//
//        response.reset();
//        response.setContentType("application/octet-stream;charset=utf-8");
//        /*
//         * 跨域配置
//         * */
//        response.addHeader("Access-Control-Allow-Origin", "*");
//        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
////        String filename = "测试.docx";
//        String filename = resource.getResourceName();
//        response.addHeader("content-disposition",
//                "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")
//                        + ";filename*=utf-8''" + URLEncoder.encode(filename, "UTF-8"));
////		response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
//        ServletOutputStream outputStream = response.getOutputStream();
//        byte[] b = new byte[1024];
//        int len;
////从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
//        while ((len = inputStream.read(b)) > 0) {
//            outputStream.write(b, 0, len);
//        }
//        inputStream.close();
//        outputStream.close();
//    }

    /**
     * 获取文件大小
     *
     * @author timo
     * @date 2018/9/3 14:03
     */
    public static String getFileSize(Long size) {
        BigDecimal fileSize = BigDecimal.valueOf(size);
        long B_SIZE = 1024;
        long KB_SIZE = B_SIZE;
        long MB_SIZE = KB_SIZE * B_SIZE;
        long GB_SIZE = MB_SIZE * B_SIZE;

        if (size / GB_SIZE > 0) {
            // GB
            return fileSize.divide(BigDecimal.valueOf(GB_SIZE), 2, RoundingMode.HALF_UP) + "GB";
        }
        if (size / MB_SIZE > 0) {
            // GB
            return fileSize.divide(BigDecimal.valueOf(MB_SIZE), 2, RoundingMode.HALF_UP) + "MB";
        }
        if (size / KB_SIZE > 0) {
            // GB
            return fileSize.divide(BigDecimal.valueOf(KB_SIZE), 2, RoundingMode.HALF_UP) + "KB";
        }
        if (size < B_SIZE) {
            return size + "B";
        }
        return 0 + "B";
    }


    //headers必须是form-data否则无法上传文件
//    @RequestMapping(value = "/uploadFile", headers = "content-type=multipart/form-data", method = RequestMethod.POST)
//    @ApiOperation(value = "文件上传测试", notes = "文件上传测试")
//    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
//        String result;
//        try {
//            String path = fileResourceService.upload(file);
//            if (!StringUtils.isEmpty(path)) {
//                result = path;
//            } else {
//                result = "上传失败";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            result = "服务异常";
//        }
//        return ResponseEntity.ok(result);
//    }
//
//    @RequestMapping(value = "/download-test", method = RequestMethod.GET)
//    @ApiOperation(value = "文件下载测试", notes = "文件下载测试")
//    public void downloadTest(String fileUrl, HttpServletResponse response, HttpServletRequest request) throws Exception {
////        "group1/M00/00/00/wKhAA2MF40eAX-w3AAMUCjmMJr4994.jpg"
//
//        byte[] data = fileResourceService.download(fileUrl);
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("下载文件名.jpg", "UTF-8"));
//        // 写出
//        ServletOutputStream outputStream = response.getOutputStream();
//        IOUtils.write(data, outputStream);
//    }
//
//    @RequestMapping(value = "/deleteByPath", method = RequestMethod.GET)
//    @ApiOperation(value = "文件删除测试", notes = "文件删除测试")
//    public Result deleteByPath(String filePathName) {
//        // String filePathName = "group1/M00/00/00/wKhjZF3WEDmAPSglAABSZAhj0eU111.jpg" ;
//        fileResourceService.deleteFile(filePathName);
//        return Result.result("删除成功");
//    }

}
