package com.ruoyi.web.controller.common;

import java.lang.reflect.Array;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.buyerapi.domain.BuyerFileInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ZipUtils;
import com.ruoyi.framework.web.domain.server.SysFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Api(tags = "文件上传通用接口")
@RestController
@RequestMapping("/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 文件实体信息
     */
    @ApiOperation(value = "文件实体信息")
    @GetMapping("/bean")
    public void fileBean(BuyerFileInfo buyerFileInfo) {
        System.out.println("通用文件关联信息对象");
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @ApiOperation(value = "通用下载请求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名", required = true, paramType = "query"),
            @ApiImplicitParam(name = "response", value = "request", required = true, paramType = "query"),
            @ApiImplicitParam(name = "request", value = "request", required = true, paramType = "query")
    })
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            String filePath = fileName.replace("/profile", profile);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 打包下载请求
     *
     * @param filePathArray 文件列表
     */
    @ApiOperation(value = "打包下载请求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePathArray", value = "文件数组(文件实体fileUrl字段组成的数组)", required = true, paramType = "query"),
            @ApiImplicitParam(name = "response", value = "response", required = true, paramType = "query"),
    })
    @GetMapping("/downloadZip")
    public void fileDownloadZip(HttpServletResponse response, String[] filePathArray) throws Exception {
        List<String> filePathList = new ArrayList<>();
        for (String fileName : filePathArray) {
            if (fileName.contains("/home")) {
                filePathList.add(fileName);
            } else {
                filePathList.add(fileName.replace("/profile", profile));
            }
        }
        ZipUtils.downLoadMaterialFile(response, filePathList);
    }

//    /**
//     * 通用下载请求
//     *
//     * @param fileName 文件名称
//     * @param delete   是否删除
//     */
//    @ApiOperation(value = "通用下载请求")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "fileName", value = "文件名", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "response", value = "request", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "request", value = "request", required = true, paramType = "query")
//    })
//    @GetMapping("/download")
//    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
//        try {
//            if (!FileUtils.checkAllowDownload(fileName)) {
//                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//            }
//            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
//            String filePath = RuoYiConfig.getDownloadPath() + fileName;
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            FileUtils.setAttachmentResponseHeader(response, realFileName);
//            FileUtils.writeBytes(filePath, response.getOutputStream());
//            if (delete) {
//                FileUtils.deleteFile(filePath);
//            }
//        } catch (Exception e) {
//            log.error("下载文件失败", e);
//        }
//    }

//    /**
//     * 通用上传请求（单个）
//     */
//    @PostMapping("/upload")
//    public AjaxResult uploadFile(MultipartFile file) throws Exception {
//        try {
//            // 上传文件路径
//            String filePath = RuoYiConfig.getUploadPath();
//            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, file);
//            String url = serverConfig.getUrl() + fileName;
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("url", url);
//            ajax.put("fileName", fileName);
//            ajax.put("newFileName", FileUtils.getName(fileName));
//            ajax.put("originalFilename", file.getOriginalFilename());
//            return ajax;
//        } catch (Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
//    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileUrl", fileName.replace("/profile", profile));
            ajax.put("fileName", fileName);
            ajax.put("fileAddr", file.getOriginalFilename());
            ajax.put("fileSize", file.getSize() + "KB");
            ajax.put("uploadTime", DateUtils.getDate());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（单个或多个，返回字符串）
     */
    @ApiOperation(value = "通用上传请求（单个或多个，返回字符串）")
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（单个或多个）
     */
    @ApiOperation(value = "通用上传请求（单个或多个，返回列表）")
    @PostMapping("/fileUploads")
    public AjaxResult fileUploads(List<MultipartFile> files) throws Exception {
        try {
            AjaxResult ajaxResult = AjaxResult.success();
            List<Map> list = new ArrayList<>();
            for (MultipartFile file : files) {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                Map dataMap = new HashMap<String, Object>();
                dataMap.put("fileName", file.getOriginalFilename());
                dataMap.put("fileAddr", fileName);
                dataMap.put("fileUrl", url);
                dataMap.put("fileSize", file.getSize() + "KB");
                dataMap.put("uploadTime", DateUtils.getNowDate());
                list.add(dataMap);
            }
            ajaxResult.put("data", list);
            return ajaxResult;
        } catch (Exception e) {
            AjaxResult ajaxResult = AjaxResult.error();
            return ajaxResult;
        }
    }

    /**
     * 本地资源通用下载
     */
    @ApiOperation(value = "本地资源通用下载")
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
