package com.goldenwater.web.controller.yjjt;

import com.goldenwater.common.core.controller.BaseController;
import com.goldenwater.common.core.domain.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 引江济太模板下载Controller
 */
@RestController
@RequestMapping("/yjjt/template")
@Tag(name = "引江济太模板管理", description = "引江济太模板下载接口")
public class YjjtTemplateController extends BaseController {

    private static final String TEMPLATE_PATH = "excel/yjjt/";

    /**
     * 下载水量数据模板
     */
    @GetMapping("/{type}")
    @Operation(summary = "下载指定类型数据模板", description = "下载指定类型数据导入模板")
    @PreAuthorize("@ss.hasPermi('yjjtgl:upload')")
    public ResponseEntity<Resource> downloadSlTemplate(
            @Parameter(description = "模板类型：sz(水质)/sl(水量)") @PathVariable String type) {
        String filename = getTemplateFilename(type);
        return downloadTemplate(filename);
    }
    /**
     * 获取水量模板文件名
     */
    private String getTemplateFilename(String type) {
        return switch (type.toLowerCase()) {
            case "sl" -> "station-sl-model.xlsx";
            case "sz" -> "station-sz-model.xlsx";
            default -> "station-sl-model.xlsx";
        };
    }

    /**
     * 下载模板文件
     */
    private ResponseEntity<Resource> downloadTemplate(String filename) {
        try {
            Resource resource = new ClassPathResource(TEMPLATE_PATH + filename);
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8)
                    .replace("+", "%20");

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFilename + "\"")
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}