package com.ruoyi.file.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.file.service.FileUploadResponse;
import com.ruoyi.file.domain.FilesUpload;
import com.ruoyi.file.service.FilesService;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;


@RestController
//@RequestMapping("/files")
public class FilesController {

    @Autowired
    private FilesService filesService;

    @PostMapping("/upload")
    public ApiResult<FileUploadResponse> upload(@RequestParam MultipartFile file, HttpServletRequest request) {
        // 打印所有请求头，以便调试
/*        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            System.out.println(headerName + ": " + headerValue);
        }*/

        // 从请求头中获取 userid
        String useridStr = request.getHeader("user_id");

        Long userid = null; // 初始化为 null
        if (useridStr != null && !useridStr.isEmpty()) {
            try {
                // 尝试将 userid 转换为 Long 类型
                userid = Long.parseLong(useridStr);
            } catch (NumberFormatException e) {
                // 如果转换失败，打印错误信息并保持 userid 为 null
                System.out.println("无法将 user_id 转换为 Long 类型: " + useridStr);
            }
        }

        // 从请求头中获取 username
        String username = request.getHeader("username");

        // 如果用户名为空或解码失败，设置为“未知用户”
        if (username == null || username.isEmpty()) {
            username = "未知用户";
        } else {
            try {
                // 使用 URLDecoder 解码用户名
                username = URLDecoder.decode(username, StandardCharsets.UTF_8.name());
            } catch (Exception e) {
                // 如果解码失败，设置为“未知用户”
                username = "未知用户";
            }
        }

        // 从请求头中获取 referer
        String referer = request.getHeader("referer");
        String refererPath = "";
        if (referer != null && !referer.isEmpty()) {
            try {
                // 提取 referer 的路径部分
                URL url = new URL(referer);
                refererPath = url.getPath();
            } catch (Exception e) {
                System.out.println("无法解析 referer URL: " + referer);
            }
        }

        // 打印 referer 路径部分
//        System.out.println("Referer 路径部分: " + refererPath);

        // 继续处理文件上传逻辑
        FileUploadResponse response = filesService.upload(file, userid, username, refererPath);
        return ApiResult.success(response);
    }


    @DeleteMapping("/delete/{id}")
    public ApiResult<String> delete(@PathVariable Integer id, HttpServletRequest request) {
        // 打印所有请求头，以便调试
/*        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            System.out.println(headerName + ": " + headerValue);
        }*/

        // 从请求头中获取 userid
        String useridStr = request.getHeader("user_id");

        Long userid = null; // 初始化为 null
        if (useridStr != null && !useridStr.isEmpty()) {
            try {
                // 尝试将 userid 转换为 Long 类型
                userid = Long.parseLong(useridStr);
            } catch (NumberFormatException e) {
                // 如果转换失败，打印错误信息并保持 userid 为 null
                System.out.println("无法将 user_id 转换为 Long 类型: " + useridStr);
            }
        }

        // 从请求头中获取username
        String username = request.getHeader("username");

        // 如果用户名为空或解码失败，设置为“未知用户”
        if (username == null || username.isEmpty()) {
            username = "未知用户";
        } else {
            try {
                // 使用 URLDecoder 解码用户名
                username = URLDecoder.decode(username, StandardCharsets.UTF_8.name());
            } catch (Exception e) {
                // 如果解码失败，设置为“未知用户”
                username = "未知用户";
            }
        }

        try {
            filesService.deleteFile(id, userid, username);
            return ApiResult.success("删除成功");
        } catch (Exception e) {
            return ApiResult.error("删除失败"); // 删除失败，返回错误信息
        }
    }

    @GetMapping("/query")
    public R<CommonPage<FilesUpload>> queryFiles(
            @RequestParam(required = false) String filesName,
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime,
            @RequestParam(required = false) Boolean isDeleted,
            @RequestParam(required = false) String fileType,
            @RequestParam(required = false) String userName,
            @RequestParam int current,
            @RequestParam int size) {

        // 调用服务层方法
        CommonPage<FilesUpload> resultPage = filesService.queryFiles(filesName, startTime, endTime, isDeleted, fileType, userName, current, size);

        // 返回封装好的分页结果
        return R.ok(resultPage);
    }
}