package com.ruoyi.web.controller.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.AntiVirus;
import com.ruoyi.postCheck.service.IPostCheckedService;
import com.ruoyi.web.controller.utils.PdfUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
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.*;
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 = "8.1.1-系统工具类")
@RestController
@RequestMapping("/common")
@Anonymous
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

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

    private static final String FILE_DELIMETER = ",";


//    @Autowired
//    private IPostCheckedService postCheckedService;


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @ApiOperation("下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件相对地址", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "delete", value = "是否完成后删除", dataType = "String", dataTypeClass = String.class),
    })
    @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);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload")
//    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("unid") String unid, @RequestParam("returnImage") String returnImage) throws Exception {
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            //安全验证
            if (!AntiVirus.scanFileName(file.getOriginalFilename())) {
                return AjaxResult.error("危险文件，不可以上传。");
            }
            // 文件后缀
            String fileNameXSS = file.getOriginalFilename();
            String suffix = fileNameXSS.substring(fileNameXSS.lastIndexOf(".") + 1).toLowerCase();

            // 判断是否是pdf文件类型
            if (StringUtils.equals(suffix, "pdf")) {
                // 判断文件xss攻击
                boolean haveJavaScript = PdfUtils.containsJavaScript(PdfUtils.multipartFileToFile(file));
                if (haveJavaScript) {
//                    return ("对不起,您上传的文件[" + fileName + "]包含xss脚本代码!");
                }
            }
//            System.out.println("file ============================= " + file);
//            System.out.println("unid ============================= " + unid);
//            System.out.println("returnImage ============================= " + returnImage);
            // 上传文件路径
            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("/uploads")
//    public AjaxResult uploadFiles(List<MultipartFile> files, @RequestParam("filePaths") String filePaths, @RequestParam("subject") String subject, @RequestParam("content") String content) throws Exception {
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            for (MultipartFile file : files) {
                //安全验证
                if (!AntiVirus.scanFileName(file.getOriginalFilename())) {
                    return AjaxResult.error("危险文件，不可以上传。");
                }
            }


//            System.out.println("files = " + files);
//            System.out.println("filePaths = " + filePaths);
//            System.out.println("subject = " + subject);
//            System.out.println("content = " + content);

            // 上传文件路径
            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());
        }
    }

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


    @ApiOperation("获取地址中文件的Base64")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "path", value = "文件相对地址", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping("/getBase64")
    @Anonymous
    public AjaxResult getBase64(String path, HttpServletResponse response) throws IOException {

        String downloadName = path;
        try {

//            System.out.println("url = " + url);
//            System.out.println("path = " + path);
            File file = new File(url + path);
            downloadName = file.getName();
            InputStream fileImageInputStream = new FileInputStream(file);
            byte[] bytes = IOUtils.toByteArray(fileImageInputStream);
            String encoded = Base64.getEncoder().encodeToString(bytes);
            String mimeType = Files.probeContentType(file.toPath());
            encoded = "data:" + mimeType + ";" + "base64," + encoded;
            return AjaxResult.success(encoded);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            String percentEncodedFileName = FileUtils.percentEncode(downloadName);

            StringBuilder contentDispositionValue = new StringBuilder();
            contentDispositionValue.append("attachment; filename=").append(percentEncodedFileName).append(";")
                    .append("filename*=")
                    .append("utf-8''")
                    .append(percentEncodedFileName);

            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
            response.setHeader("Content-disposition", contentDispositionValue.toString());
            response.setHeader("download-filename", percentEncodedFileName);
        }
        return AjaxResult.success(null);
    }
}
