package com.ruoyi.web.controller.common;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.app.service.IPicParseService;
import com.ruoyi.common.PdfParse2Util;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.PdfParseUtil;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;

import technology.tabula.*;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;
import org.apache.pdfbox.pdmodel.PDDocument;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IPicParseService picParseService;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
    @PostMapping("/uploadA")
    public AjaxResult uploadA(MultipartFile file,
                                 @RequestParam(value = "waterText", required = false)int waterText ) throws Exception
    {
//        Map<String, Object>  detail = new HashMap<>();
//        detail = PdfParseUtil.extractPdfContent(file);

        Map<String, Object>  detail = picParseService.picParseA(file);

        return AjaxResult.success(detail);
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file,
                                 @RequestParam(value = "waterText", required = false)int waterText ) throws Exception
    {
        try
        {

            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();

            // 上传并返回新文件名称
            String fileName = null;
            if (ObjectUtil.isNotEmpty(waterText) && waterText == 1){

                String loginUser = SecurityUtils.getLoginUser().getUser().getNickName();
                System.out.println(loginUser);
                String format = DateUtil.format(new Date(), "yyyy/MM/dd/HH/mm");
                List<String> list = Arrays.asList(loginUser, format);
                BufferedImage image = javax.imageio.ImageIO.read(file.getInputStream());
                BottomRightWatermarkUtil.BottomRightWatermarkConfig config =
                        BottomRightWatermarkUtil.BottomRightWatermarkConfig.builder()
                                .fontSize(12)
                                .opacity(0.5f)
                                .withBackground(true)
                                .backgroundColor(new Color(0, 0, 0, 120))
                                .build();
                BufferedImage bufferedImage = BottomRightWatermarkUtil.addMultiLineBottomRightWatermark(image, list.toArray(new String[0]), config);
                MultipartFile multipartFile = convertToMultipartFile(bufferedImage, file);

                fileName =  FileUploadUtils.upload(filePath, multipartFile);
                multipartFile.getInputStream().close();

            }else {
                fileName = FileUploadUtils.upload(filePath,  file);
            }

            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());

            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    private static MultipartFile convertToMultipartFile(
            BufferedImage image,
            MultipartFile originalFile) throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 获取原文件扩展名
        String originalFilename = originalFile.getOriginalFilename();
        String extension = getFileExtension(originalFilename);
        String formatName = getFormatName(extension);

        // 写入图片
        ImageIO.write(image, formatName, baos);

        // 创建内存 MultipartFile
        return new InMemoryMultipartFile(
                originalFile.getName(),
                originalFilename,
                originalFile.getContentType(),
                baos.toByteArray()
        );
    }
    private static String getFormatName(String extension) {
        switch (extension.toLowerCase()) {
            case "jpg":
            case "jpeg":
                return "JPEG";
            case "png":
                return "PNG";
            case "gif":
                return "GIF";
            case "bmp":
                return "BMP";
            default:
                return "JPEG";
        }
    }

    private static String getFileExtension(String filename) {
        if (StrUtil.isBlank(filename) || !filename.contains(".")) {
            return "jpg";
        }
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    }


    /**
     * 上传PDF文件并解析
     */
    @PostMapping("/uploadAndParse")
    public AjaxResult uploadAndParse(MultipartFile file ,
                                     @RequestParam(value = "type", required = false) String type) throws Exception
    {
        //验证文件
        if (file.isEmpty()) {
            return AjaxResult.error("请上传文件");
        }

        try
        {

            if (type ==null || "0".equals(type)){
                try {
                    // 上传文件路径
                    String filePath = RuoYiConfig.getUploadPath();
//                 上传并返回新文件名称
                    String fileName = FileUploadUtils.upload(filePath, file);
                    String url = serverConfig.getUrl() + fileName;
                    //解析
                    Map<String, Object>  detail = new HashMap<>();
                    if("application/pdf".equals(file.getContentType())){
                        detail = PdfParseUtil.extractPdfContent(file);
                    }else if(file.getContentType() != null && file.getContentType().startsWith("image/")){
                        detail = picParseService.picParse(file);
                    }else{
                        return AjaxResult.error("不支持的文件格式");
                    }
                    AjaxResult ajax = AjaxResult.success();
                    ajax.put("detail", detail);
                    ajax.put("url", url);
                    ajax.put("fileName", fileName);
                    ajax.put("newFileName", FileUtils.getName(fileName));
                    ajax.put("originalFilename", file.getOriginalFilename());
                    return ajax;
                }catch (Exception e){
                    throw new Exception("检疫证识别失败，请手工填写");
                }

            }else {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                //解析
                Map<String, Object>  detail = new HashMap<>();

//                 detail = picParseService.picParseA(file);
                detail = PdfParse2Util.extractPdfContent(file);

                AjaxResult ajax = AjaxResult.success();
                ajax.put("detail", detail);
                ajax.put("url", url);
                ajax.put("fileName", fileName);
                ajax.put("newFileName", FileUtils.getName(fileName));
                ajax.put("originalFilename", file.getOriginalFilename());
                return ajax;
            }

        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }




        public static List<String> parseEarTags(String input) {
            List<String> allTags = new ArrayList<>();
            // 正则匹配三种模式：1.完整范围 2.单个耳标 3.多段范围
            Pattern pattern = Pattern.compile("(\\d{15})(?:-(\\d{3}))?|(\\d{15})-(\\d{6})");
            Matcher matcher = pattern.matcher(input);

            while (matcher.find()) {
                // 处理完整范围（如123012615932429-465）
                if (matcher.group(1) != null && matcher.group(2) != null) {
                    String base = matcher.group(1).substring(0, 12);
                    int start = Integer.parseInt(matcher.group(1).substring(12));
                    int end = Integer.parseInt(matcher.group(2));
                    generateRange(base, start, end, allTags);
                }
                // 处理单个耳标（如233011223610519）
                else if (matcher.group(3) != null) {
                    allTags.add(matcher.group(3));
                }
                // 处理多段范围（如236215559302-557595-517）
                else if (matcher.group(4) != null && matcher.group(5) != null) {
                    String base = matcher.group(4).substring(0, 12);
                    int start = Integer.parseInt(matcher.group(4).substring(12));
                    int end = Integer.parseInt(matcher.group(5));
                    generateRange(base, start, end, allTags);
                }
            }
            return allTags;
        }

        private static void generateRange(String base, int start, int end, List<String> list) {
            for (int i = start; i <= end; i++) {
                list.add(base + String.format("%03d", i));
            }
        }

    /**
     * 上传图片并解析
     */
    @PostMapping("/uploadImgAndParse")
    public AjaxResult uploadImgAndParse(MultipartFile file) throws Exception
    {
        //验证文件
        if (file.isEmpty()) {
            return AjaxResult.error("请上传图片");
        }

        // 方法三：判断是否是image类型（所有图片格式）
        if (file.getContentType() == null || !file.getContentType().startsWith("image/")) {
            return AjaxResult.error("仅支持图片文件");
        }
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();

            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map<String, Object>  detail = picParseService.picParse(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("detail", detail);

            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    @PostMapping("/addBatch")
    public ResponseEntity<Map<String, Object>> addBatch(@RequestBody Map<String, Object> params) {
        System.out.println(JSON.toJSONString(params));
        Map<String, Object> response = new HashMap<>();
        response.put("resultCode", 0);
        response.put("resultMsg", "success");
        return ResponseEntity.ok(response);
    }
}
