package com.boyue.web.controller.common;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import com.boyue.common.annotation.Anonymous;
import com.boyue.common.config.BoYueConfig;
import com.boyue.common.core.domain.AjaxResult;
import com.boyue.common.utils.StringUtils;
import com.boyue.common.utils.file.FileUtils;
import com.boyue.common.utils.file.MimeTypeUtils;
import com.boyue.file.utils.FileOperateUtils;
import com.boyue.framework.config.ServerConfig;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 *
 * @author boyue
 */
@Tag(name = "通用请求处理")
@RestController
@RequestMapping("/common")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @Operation(summary = "通用下载请求")
    @Parameters({
            @Parameter(name = "fileName", description = "文件名称"),
            @Parameter(name = "delete", description = "是否删除")
    })
    @GetMapping("/download")
    @Anonymous
    public void fileDownload(
            @RequestParam("fileName") String fileName,
            @RequestParam("delete") 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 = BoYueConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            // FileUtils.writeBytes(filePath, response.getOutputStream());
            FileOperateUtils.downLoad(filePath, response.getOutputStream());
            if (delete) {
                FileOperateUtils.deleteFile(fileName);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @Operation(summary = "通用上传请求（单个）")
    @PostMapping("/upload")
    @Anonymous
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            if (file == null) {
                return AjaxResult.error("上传的文件不能为空");
            }
            
            // 记录文件信息
            log.info("接收到文件上传请求，文件名: {}, 大小: {}KB", 
                    file.getOriginalFilename(), file.getSize() / 1024);
            
            String url = FileOperateUtils.upload(file);
            
            log.info("文件上传成功，文件地址: {}", url);
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", getFileName(file.getOriginalFilename()));
            ajax.put("newFileName", FileUtils.getName(file.getOriginalFilename()));
            ajax.put("originalFilename", file.getOriginalFilename());
            ajax.put("code", 200); // 确保返回正确的状态码
            
            return ajax;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return AjaxResult.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 从文件名中提取文件名（不带路径）
     */
    private String getFileName(String name) {
        if (name == null) {
            return "";
        }
        int lastIndex = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
        return lastIndex >= 0 ? name.substring(lastIndex + 1) : name;
    }

    /**
     * 通用上传请求（多个）
     */
    @Operation(summary = "通用上传请求（多个）")
    @PostMapping("/uploads")
    @Anonymous
    public AjaxResult uploadFiles(@RequestBody List<MultipartFile> files)
            throws Exception {
        try {
            // 上传文件路径
            String filePath = BoYueConfig.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 = FileOperateUtils.upload(filePath, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
                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());
        }
    }

    /**
     * 本地资源通用下载
     */
    @Operation(summary = "本地资源通用下载")
    @GetMapping("/download/resource")
    @Anonymous
    public void resourceDownload(@Parameter(name = "resource", description = "资源名称") String resource,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, resource);
            FileOperateUtils.downLoad(resource, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 删除文件请求
     *
     * @param filePathParam 包含文件路径的参数对象
     * @return 删除结果
     */
    @Operation(summary = "删除文件请求")
    @PostMapping("/deleteFile")
    @Anonymous
    public AjaxResult deleteFile(@RequestBody(required = false) FilePathParam filePathParam,
                                @RequestParam(value = "filePath", required = false) String filePathParam2) {
        try {
            String filePath;
            
            // 支持两种方式传参：请求体或URL参数
            if (filePathParam != null && StringUtils.isNotEmpty(filePathParam.filePath)) {
                filePath = filePathParam.filePath;
            } else if (StringUtils.isNotEmpty(filePathParam2)) {
                filePath = filePathParam2;
            } else {
                return AjaxResult.error("文件路径不能为空");
            }
            
            log.info("原始文件路径: {}", filePath);
            
            // 处理文件路径格式
            if (filePath.contains("http://") || filePath.contains("https://")) {
                // 如果是完整URL，提取文件名或相对路径部分
                if (filePath.contains("/profile/")) {
                    filePath = filePath.substring(filePath.indexOf("/profile/") + 9);
                } else {
                    // 尝试从路径中提取文件名
                    filePath = filePath.substring(filePath.lastIndexOf('/') + 1);
                }
            }
            
            // 处理反斜杠
            filePath = filePath.replace('\\', '/');
            
            // 去除开头的斜杠
            if (filePath.startsWith("/")) {
                filePath = filePath.substring(1);
            }
            
            log.info("处理后的文件路径: {}", filePath);
            
            // 安全检查
            if (!FileUtils.checkAllowDownload(filePath)) {
                return AjaxResult.error(StringUtils.format("文件名称({})非法，不允许删除。", filePath));
            }
            
            // 执行删除
            boolean result = FileOperateUtils.deleteFile(filePath);
            if (result) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("文件删除失败");
            }
        } catch (Exception e) {
            log.error("删除文件失败", e);
            return AjaxResult.error("删除文件失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除文件请求 - GET方法
     * 
     * @param filePath 文件路径
     * @return 删除结果
     */
    @Operation(summary = "删除文件请求 - GET方式")
    @GetMapping("/deleteFile")
    @Anonymous
    public AjaxResult deleteFileGet(@RequestParam("filePath") String filePath) {
        FilePathParam param = new FilePathParam();
        param.setFilePath(filePath);
        return deleteFile(param, null);
    }
    
    /**
     * 文件路径参数类
     */
    public static class FilePathParam {
        public String filePath;
        
        public FilePathParam() {
        }
        
        public String getFilePath() {
            return filePath;
        }
        
        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }
    }
    
    /**
     * 文件上传诊断工具
     */
    @Operation(summary = "文件上传诊断工具")
    @GetMapping("/diagnose-upload")
    @Anonymous
    public AjaxResult diagnoseUpload() {
        try {
            Map<String, Object> diagnostics = new HashMap<>();
            
            // 获取系统配置
            diagnostics.put("uploadPath", BoYueConfig.getProfile());
            diagnostics.put("fileServer", BoYueConfig.getFileServer());
            
            // 系统信息
            Map<String, Object> systemInfo = new HashMap<>();
            systemInfo.put("os.name", System.getProperty("os.name"));
            systemInfo.put("file.separator", File.separator);
            systemInfo.put("user.dir", System.getProperty("user.dir"));
            diagnostics.put("systemInfo", systemInfo);
            
            // 检查目录
            List<String> pathsToCheck = new ArrayList<>();
            pathsToCheck.add(BoYueConfig.getProfile());
            pathsToCheck.add(BoYueConfig.getProfile() + "/files");
            pathsToCheck.add(BoYueConfig.getProfile() + "/files/master");
            
            List<Map<String, Object>> directoryChecks = new ArrayList<>();
            for (String path : pathsToCheck) {
                Map<String, Object> check = new HashMap<>();
                File directory = new File(path);
                check.put("path", path);
                check.put("exists", directory.exists());
                check.put("isDirectory", directory.exists() && directory.isDirectory());
                check.put("canWrite", directory.exists() && directory.canWrite());
                check.put("canRead", directory.exists() && directory.canRead());
                check.put("absolutePath", directory.getAbsolutePath());
                directoryChecks.add(check);
            }
            diagnostics.put("directoryChecks", directoryChecks);
            
            // 尝试创建测试文件
            try {
                String testDirectory = BoYueConfig.getProfile() + "/files/master";
                File dir = new File(testDirectory);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                
                String testFilePath = testDirectory + "/test_" + System.currentTimeMillis() + ".txt";
                File testFile = new File(testFilePath);
                boolean created = testFile.createNewFile();
                
                Map<String, Object> testFileInfo = new HashMap<>();
                testFileInfo.put("path", testFilePath);
                testFileInfo.put("created", created);
                testFileInfo.put("exists", testFile.exists());
                
                if (created && testFile.exists()) {
                    // 写入一些内容
                    try (java.io.FileWriter writer = new java.io.FileWriter(testFile)) {
                        writer.write("Test file created at: " + new java.util.Date());
                    }
                    
                    // 生成访问URL
                    String url = FileOperateUtils.getURL(testFilePath.substring(BoYueConfig.getProfile().length() + 1));
                    testFileInfo.put("url", url);
                    
                    // 删除测试文件
                    boolean deleted = testFile.delete();
                    testFileInfo.put("deleted", deleted);
                }
                
                diagnostics.put("testFileInfo", testFileInfo);
            } catch (Exception e) {
                Map<String, Object> testFileError = new HashMap<>();
                testFileError.put("error", e.getMessage());
                testFileError.put("stackTrace", e.getStackTrace());
                diagnostics.put("testFileError", testFileError);
            }
            
            return AjaxResult.success("诊断完成").put("diagnostics", diagnostics);
        } catch (Exception e) {
            log.error("诊断失败", e);
            return AjaxResult.error("诊断失败: " + e.getMessage());
        }
    }
}
