package com.nanri.aiimage.modules.file.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.modules.file.model.vo.ExcelInfoVo;
import com.nanri.aiimage.modules.file.model.vo.UploadFileVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class LocalFileStorageService {

    private final StorageProperties storageProperties;

    public UploadFileVo saveTempFile(MultipartFile file, String relativePath) throws IOException {
        File tempDir = FileUtil.file(storageProperties.getLocalTempDir());
        File parentDir = tempDir.getParentFile();
        if (parentDir != null) {
            FileUtil.mkdir(parentDir);
        }
        FileUtil.mkdir(tempDir);
        String fileKey = IdUtil.fastSimpleUUID();
        String extName = FileUtil.extName(file.getOriginalFilename());
        File target = FileUtil.file(tempDir, fileKey + (extName.isEmpty() ? "" : "." + extName));
        file.transferTo(target);

        UploadFileVo vo = new UploadFileVo();
        vo.setFileKey(fileKey);
        vo.setOriginalFilename(file.getOriginalFilename());
        vo.setLocalPath(target.getAbsolutePath());
        vo.setSize(file.getSize());
        vo.setRelativePath(relativePath);
        return vo;
    }

    public ExcelInfoVo getExcelInfo(String fileKey) throws IOException {
        File inputFile = findLocalSourceFile(fileKey);
        if (inputFile == null || !inputFile.exists()) {
            throw new BusinessException("源文件不存在");
        }

        DataFormatter formatter = new DataFormatter();
        try (FileInputStream fis = new FileInputStream(inputFile); Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(fis)) {
            Sheet sheet = workbook.getSheetAt(0);
            Row headerRow = sheet.getRow(0);
            if (headerRow == null) {
                throw new BusinessException("Excel 表头为空");
            }

            Map<String, Integer> headerMap = new HashMap<>();
            List<String> headers = new ArrayList<>();
            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                String value = normalizeCellText(cell == null ? null : formatter.formatCellValue(cell));
                if (value.isBlank()) {
                    continue;
                }
                value = value.split("idASIN国家状态价格变体数量", 2)[0].trim().isEmpty()
                        ? value
                        : value.split("idASIN国家状态价格变体数量", 2)[0].trim();
                if (headerMap.containsKey(value)) {
                    continue;
                }
                headerMap.put(value, i);
                headers.add(value);
                if ("缩略图地址8".equals(value)) {
                    break;
                }
            }

            ExcelInfoVo vo = new ExcelInfoVo();
            vo.setHeaders(headers);
            vo.setTotalRows(Math.max(sheet.getLastRowNum(), 0));
            return vo;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException("读取 Excel 信息失败");
        }
    }

    public File findLocalSourceFile(String fileKey) {
        File baseDir = FileUtil.file(storageProperties.getLocalTempDir());
        if (!baseDir.exists()) {
            return null;
        }
        List<File> matchedFiles = FileUtil.loopFiles(baseDir, pathname -> pathname.isFile() && pathname.getName().startsWith(fileKey));
        return matchedFiles.isEmpty() ? null : matchedFiles.getFirst();
    }

    private String normalizeCellText(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\ufeff", "")
                .replace("\u3000", " ")
                .replace("\r\n", " ")
                .replace("\r", " ")
                .replace("\n", " ")
                .replace("\t", " ")
                .trim()
                .replaceAll("\\s+", " ");
    }
}
