package hw.tagApi.service.controller;

import hw.tagApi.common.core.controller.BaseController;
import hw.tagApi.common.core.domain.AjaxResult;
import hw.tagApi.common.utils.poi.ExcelUtil;
import hw.tagApi.service.constant.ApiConstants;
import hw.tagApi.service.domain.ApiContent;
import hw.tagApi.service.domain.ApiRequest;
import hw.tagApi.service.domain.ApiResponse;
import hw.tagApi.service.service.IKDocsService;
import hw.tagApi.system.domain.SysAttachInfo;
import hw.tagApi.system.service.ISysAttachInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 云接口Controller
 *
 * @author Yinq
 * @date 2025-04-15
 */
@RestController
@RequestMapping("/docs")
public class KDocsApiController extends BaseController {

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

    @Autowired
    private IKDocsService ikDocsService;

    @Autowired
    private ISysAttachInfoService attachInfoService;

    /**
     * 统一接口处理
     *
     * @param request 请求对象，包含CASE和CONTENT
     * @return 处理结果
     */
    @PostMapping("/api")
    public ApiResponse handleRequest(@RequestHeader("API-Key") String apiKey, @RequestBody ApiRequest request) {
        ApiResponse apiResponse = new ApiResponse();
        // 验证API-Key
        if (!validateApiKey(apiKey)) {
            log.warn("无效的API-Key: {}", apiKey);
            apiResponse.setCaseCode("无效的API-Key:" + apiKey);
            return apiResponse;
        }
        try {
            String caseCode = request.getCASE();
            List<ApiContent> content = request.getCONTENT();
            apiResponse.setCaseCode(caseCode);
            // 打印接收到的请求参数
            log.info("接收到请求 - CASE: {}, CONTENT: {}", caseCode, content);
            switch (caseCode) {
                case ApiConstants.DATA_STATUS:
                    log.info("查询数据库状态");
                    return apiResponse;
                case ApiConstants.DATA_IMPORT:
                    // 数据导入
                    if (content == null || content.isEmpty()) {
                        log.warn("导入数据为空");
                        return apiResponse;
                    }
                    List<ApiContent> apiContents = ikDocsService.importDataList(content);
                    apiResponse.setResult(apiContents);
                    return apiResponse;
                case ApiConstants.DATA_QUERY:
                    // 数据查询
                    if (content == null || content.isEmpty()) {
                        log.warn("查询条件为空");
                        return apiResponse;
                    }
                    log.info("开始查询数据: {}", content);
                    List<ApiContent> queryResults = ikDocsService.queryDataList(content);
                    apiResponse.setResult(queryResults);
                    return apiResponse;
                case ApiConstants.DATA_EXPORT:
                    // 数据导出
                    if (content == null || content.isEmpty()) {
                        log.warn("导出条件为空");
                        return apiResponse;
                    }
                    log.info("开始导出数据: {}", content);
                    List<ApiContent> exportResults = ikDocsService.exportDataList(content);
                    apiResponse.setResult(exportResults);
                    return apiResponse;
                default:
                    log.warn("未知的功能代码: {}", caseCode);
                    return apiResponse;
            }
        } catch (Exception e) {
            log.error("处理请求时发生错误", e);
            return apiResponse;
        }
    }


    /**
     * 下载导出文件
     *
     * @param attachUrl 附件ID
     * @param response HTTP响应对象
     */
    @GetMapping("/export/{attachUrl}")
    public void downloadExportFile(@PathVariable String attachUrl, HttpServletResponse response) {
        try {
            // 查询附件信息
            SysAttachInfo sysAttachInfo = new SysAttachInfo();
            sysAttachInfo.setAttachUrl(ApiConstants.BASE_URL + attachUrl);
            List<SysAttachInfo> attachInfoList = attachInfoService.selectSysAttachInfoList(sysAttachInfo);
            if (attachInfoList.isEmpty()) {
                throw new RuntimeException("附件不存在");
            }
            SysAttachInfo attachInfo = attachInfoList.get(0);

            Instant now = Instant.now();
            Instant expirationTime = attachInfo.getExpirationTime().toInstant();
            if (now.isAfter(expirationTime)) {
                DateTimeFormatter formatter = DateTimeFormatter
                        .ofPattern("yyyy-MM-dd HH:mm:ss")
                        .withZone(ZoneId.systemDefault());
                String formattedTime = formatter.format(expirationTime);
                throw new ServletException("此文件已过期（有效期至: " + formattedTime + "）");
            }
            // 检查文件是否存在
            File file = new File(attachInfo.getAttachAddress());
            if (!file.exists()) {
                throw new RuntimeException("文件不存在");
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + 
                URLEncoder.encode(attachInfo.getAttachName(), "UTF-8"));

            // 写入响应流
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis)) {
                byte[] buffer = new byte[1024];
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
            throw new RuntimeException("下载文件失败: " + e.getMessage());
        }
    }

    /**
     * 验证API-Key
     *
     * @param apiKey API密钥
     * @return 是否有效
     */
    private boolean validateApiKey(String apiKey) {
        // TODO: 实现API-Key的验证逻辑
        return true;
    }
}
