package cn.gintone.controller;

import cn.gintone.controller.vo.ImportantFileSaveReqVO;
import cn.gintone.dto.EncInfo;
import cn.gintone.entity.ImportantFileDO;
import cn.gintone.service.KeyCodeService;
import cn.hutool.core.io.IoUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FileUploadReqVO;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@RestController
@RequestMapping("/admin-api/myFileCon")
public class MyFileController {
    @Resource
    private FileService fileService;
    @Autowired
    private KeyCodeService keyCodeService;

    @PostMapping("/upload")
    @Operation(summary = "上传文件", description = "模式一：后端上传文件")
    public CommonResult<EncInfo> uploadFile(FileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        String path = uploadReqVO.getPath();
        String url = fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()));
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);
        EncInfo encInfo = keyCodeService.rasEncryption(map);
        return success(encInfo);
    }

    @PostMapping("/fileRasDecrypt")
    @Operation(summary = "文件解密接口")
    public CommonResult<Map<String, Object>> rasDecrypt(@RequestBody ImportantFileSaveReqVO createReqVO, HttpServletRequest request) throws Exception {
        String pdToken = request.getHeader("pdToken");
        String ip = request.getHeader("X-Forwarded-For");
        if (isInvalidIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isInvalidIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isInvalidIp(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (isInvalidIp(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (isInvalidIp(ip)) {
            ip = request.getRemoteAddr();
        }

        // 处理多级代理情况（取第一个非 unknown 的 IP）
        if (ip != null && ip.contains(",")) {
            ip = Arrays.stream(ip.split(","))
                    .map(String::trim)
                    .filter(part -> !"unknown".equalsIgnoreCase(part))
                    .findFirst()
                    .orElse(request.getRemoteAddr());
        }
        Map<String, Object> map = keyCodeService.fileRasDecrypt(createReqVO, ip, pdToken);
        return success(map);
    }

    private boolean isInvalidIp(String ip) {
        return ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip);
    }


}
