package cn.edu.whu.boot.photozip.controller;

import cn.edu.whu.boot.photozip.mapper.PhotoZipMapper;
import cn.edu.whu.boot.photozip.service.PhotoZipService;
import cn.edu.whu.boot.photozip.util.XmlUtil;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.util.Map;

@RestController
@RequestMapping("/photozip")
public class PhotoZipController {
    private final PhotoZipService photoZipService;
    private final PhotoZipMapper photoZipMapper;

    public PhotoZipController(PhotoZipService photoZipService, PhotoZipMapper photoZipMapper) {
        this.photoZipService = photoZipService;
        this.photoZipMapper = photoZipMapper;
    }

    /**
     * /viewer 请求只生成 ZIP 文件，不返回给客户端
     */
    @GetMapping("/viewer")
    public ResponseEntity<Void> generateZipForViewer(@RequestParam String taskName) {
        Path zipFilePath = generateZip(taskName);
        if (zipFilePath == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); // 500 生成失败
        }
        return ResponseEntity.ok().build();
    }

    /**
     * /download 直接下载 ZIP 文件
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadTaskPhotos(@RequestParam String taskName) {
        Path zipFilePath = generateZip(taskName);
        if (zipFilePath == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); // 500 生成失败
        }

        Resource fileResource = photoZipService.getZipFileResource(zipFilePath);

        try {
            // 对文件名进行 URL 编码，避免中文文件名的问题
            String encodedFileName = URLEncoder.encode(zipFilePath.getFileName().toString(), "UTF-8")
                    .replaceAll("\\+", "%20"); // URL 编码会把空格转成 "+"，这会导致问题，所以手动替换为 "%20"

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"")
                    .body(fileResource);
        } catch (UnsupportedEncodingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); // 如果编码失败，返回 500 错误
        }
    }
    /**
     * 统一的 ZIP 生成逻辑，供 /viewer 和 /download 复用
     */
    private Path generateZip(String taskName) {
        // 1. 查询 task_name 对应的 database_name 和 xml_id
        Map<String, Object> taskInfo = photoZipMapper.getTaskInfoByTaskName(taskName);
        if (taskInfo == null) {
            return null;
        }
        String databaseName = (String) taskInfo.get("database_name");

        // 解析 xml_id，避免 Integer/Long 类型不兼容
        Object xmlIdObj = taskInfo.get("xml_id");
        Integer xmlId = (xmlIdObj instanceof Number) ? ((Number) xmlIdObj).intValue() : null;
        if (xmlId == null) {
            return null;
        }

        // 2. 根据 xml_id 查询 file_path
        String filePath = photoZipMapper.getXmlFilePathByXmlId(xmlId);
        if (filePath == null) {
            return null;
        }

        // 3. 解析 XML 获取 table key
        String tableName;
        try {
            tableName = XmlUtil.getTableKey(filePath);
        } catch (Exception e) {
            return null;
        }

        // 4. 形成完整表名，加上 schema 引号
        String fullTableName = "\"" + databaseName + "\"." + tableName + "_media";

        // 5. 生成 ZIP 文件
        return photoZipService.createPhotoZip(fullTableName, taskName);
    }
}
