package com.ai.da.common.config;

import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.ThreeDDetailMapper;
import com.ai.da.mapper.primary.ThreeDLayoutMapper;
import com.ai.da.mapper.primary.ThreeDPatternLayoutMapper;
import com.ai.da.mapper.primary.ThreeDSimpleMapper;
import com.ai.da.mapper.primary.entity.ThreeDDetail;
import com.ai.da.mapper.primary.entity.ThreeDLayout;
import com.ai.da.mapper.primary.entity.ThreeDPatternLayout;
import com.ai.da.mapper.primary.entity.ThreeDSimple;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ThreeDSave {

    @Resource
    private ThreeDDetailMapper threeDDetailMapper;
    @Resource
    private ThreeDSimpleMapper threeDSimpleMapper;
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private ThreeDLayoutMapper threeDLayoutMapper;
    @Resource
    private ThreeDPatternLayoutMapper threeDPatternLayoutMapper;
    @PostConstruct
    public void test() {
//        minioSave();
//        frontBackDataCreate();
//        patternDataCreate();
    }

    private void patternDataCreate() {
        QueryWrapper<ThreeDSimple> qw = new QueryWrapper<>();
        qw.lambda().eq(ThreeDSimple::getGender, "female");
        qw.lambda().ne(ThreeDSimple::getId, 1);
        List<ThreeDSimple> threeDSimpleList = threeDSimpleMapper.selectList(qw);
        List<Integer> numbers = new ArrayList<>();
        String patternPath = "C:\\workspace\\3D\\3D虚拟 1-7\\6.版文件、dxf文件\\女装系列(1)\\女装系列\\56款打版截图";

        File directory = new File(patternPath);

        if (directory.exists() && directory.isDirectory()) {
            // 获取目录下的所有文件名，并建立编号 -> 文件名的映射
            Map<Integer, String> fileMap = Arrays.stream(directory.listFiles())
                    .filter(File::isFile)  // 只获取文件
                    .map(File::getName)    // 获取文件名
                    .collect(Collectors.toMap(
                            name -> {
                                Matcher matcher = Pattern.compile("^\\d+").matcher(name);
                                return matcher.find() ? Integer.parseInt(matcher.group()) : -1;
                            },
                            name -> name,
                            (existing, replacement) -> existing // 处理重复情况，保留原有值
                    ));

            for (ThreeDSimple threeDSimple : threeDSimpleList) {
                String name = threeDSimple.getName();
                Pattern pattern = Pattern.compile("^\\d+"); // 匹配开头的数字
                Matcher matcher = pattern.matcher(name);
                if (matcher.find()) {
                    int number = Integer.parseInt(matcher.group());
                    numbers.add(number);
                    // 匹配对应文件夹，并获取文件
                    if (fileMap.containsKey(number)) {
                        String matchedFolder = fileMap.get(number);
                        File folder = new File(directory, matchedFolder);

                        ThreeDPatternLayout threeDPatternLayout = new ThreeDPatternLayout();
                        threeDPatternLayout.setThreeDSimpleId(threeDSimple.getId());
                        threeDPatternLayout.setName(matchedFolder);
                        String minioUrl = "aida-threed/female/pattern-layout/" + matchedFolder;
                        minioUtil.upload(minioUrl, folder);
                        threeDPatternLayout.setUrl(minioUrl);
//                        threeDPatternLayoutMapper.insert(threeDPatternLayout);
                    }
                }
            }

            System.out.println("文件编号映射：" + fileMap);
        }
    }

    private void frontBackDataCreate() {
        QueryWrapper<ThreeDSimple> qw = new QueryWrapper<>();
        qw.lambda().eq(ThreeDSimple::getGender, "female");
//        qw.lambda().ne(ThreeDSimple::getId, 1);
        List<ThreeDSimple> threeDSimpleList = threeDSimpleMapper.selectList(qw);
        List<Integer> numbers = new ArrayList<>();

        // 文件夹名列表
        String path = "C:\\workspace\\3D\\3D虚拟 1-7\\3D服装真反面整理\\female"; // 目标路径
        File directory = new File(path);

        if (directory.exists() && directory.isDirectory()) {
            // 获取文件夹名列表，并建立编号 -> 文件夹名的映射
            Map<Integer, String> folderMap = Arrays.stream(directory.listFiles())
                    .filter(File::isDirectory)
                    .map(File::getName)
                    .collect(Collectors.toMap(
                            name -> {
                                Matcher matcher = Pattern.compile("^\\d+").matcher(name);
                                return matcher.find() ? Integer.parseInt(matcher.group()) : -1;
                            },
                            name -> name,
                            (existing, replacement) -> existing // 处理重复情况，保留原有值
                    ));

            System.out.println("文件夹编号映射：" + folderMap);

            for (ThreeDSimple threeDSimple : threeDSimpleList) {
                String name = threeDSimple.getName();
                Pattern pattern = Pattern.compile("^\\d+"); // 匹配开头的数字
                Matcher matcher = pattern.matcher(name);
                if (matcher.find()) {
                    int number = Integer.parseInt(matcher.group());
                    numbers.add(number);
                    // 匹配对应文件夹，并获取文件
                    if (folderMap.containsKey(number)) {
                        String matchedFolder = folderMap.get(number);
                        File folder = new File(directory, matchedFolder);
                        if (folder.exists() && folder.isDirectory()) {

                            for (File file : folder.listFiles()) {
                                String fileName = file.getName(); // 去掉后缀
                                ThreeDLayout threeDLayout = new ThreeDLayout();
                                threeDLayout.setGender("female");
                                threeDLayout.setThreeDSimpleId(threeDSimple.getId());
                                threeDLayout.setName(file.getName());
                                if (fileName.startsWith("前")) {
                                    threeDLayout.setType("front");
                                }else if (fileName.startsWith("后")) {
                                    threeDLayout.setType("back");
                                }
                                String minioUrl = "aida-threed/female/layout/" + folderMap.get(number) + " " + file.getName();
                                minioUtil.upload(minioUrl, file);
                                threeDLayout.setUrl(minioUrl);
//                                threeDLayoutMapper.insert(threeDLayout);
                            }

                        }
                    }
                }
            }
            System.out.println(numbers);
        } else {
            System.out.println("路径不存在或不是文件夹");
        }
    }

    private void minioSave() {
        // 指定目标文件夹路径
        String folderPath = "C:\\workspace\\3D\\3D虚拟 1-7\\3D服装整理\\maleZip";

        // 创建文件对象
        File folder = new File(folderPath);

        // 检查文件夹是否存在且是目录
        if (folder.exists() && folder.isDirectory()) {
            // 获取所有 .zip 文件
            File[] zipFiles = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".zip"));

            List<String> zipFileNameList = new ArrayList<>();
            // 输出文件名
            if (zipFiles != null) {
                for (File file : zipFiles) {
                    String zipFileName = file.getName();
                    String[] split = zipFileName.split("_");
                    String zipName = split[0];
                    String sizeWithSuffix = split[1];
                    String[] sizeWithSuffixSplit = sizeWithSuffix.split("\\.");
                    String size = sizeWithSuffixSplit[0];
                    // 找到第一个字母的位置
                    int index = 0;
                    while (index < size.length() && Character.UnicodeBlock.of(size.charAt(index)) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
                        index++;
                    }

                    if (index > 0 && index < size.length()) {
                        String prefix = size.substring(0, index); // "亚码"
                        String suffix = size.substring(index);    // "L"

                        ThreeDDetail threeDDetail = new ThreeDDetail();
                        threeDDetail.setName(zipFileName);
                        String url = "aida-threed/male/zip/" + zipFileName;
                        threeDDetail.setGender("male");
                        threeDDetail.setSizeType(prefix);
                        threeDDetail.setSize(suffix);
                        threeDDetail.setUrl(url);
//                        threeDDetailMapper.insert(threeDDetail);
                        minioUtil.upload(url, file);

                        QueryWrapper<ThreeDSimple> qw = new QueryWrapper<>();
                        qw.lambda().eq(ThreeDSimple::getName, zipName);
                        qw.lambda().eq(ThreeDSimple::getGender, "male");
                        List<ThreeDSimple> threeDSimples = threeDSimpleMapper.selectList(qw);

                        if (CollectionUtils.isEmpty(threeDSimples)) {
                            ThreeDSimple threeDSimple = new ThreeDSimple();
                            threeDSimple.setName(zipName);
                            threeDSimple.setGender("male");

                            String glbPath = "C:\\workspace\\3D\\3D虚拟 1-7\\3D服装整理\\male\\" + zipName + "\\" +"亚码L";
                            File glbFolder = new File(glbPath);

                            // 查找 .glb 文件
                            if (glbFolder.exists() && glbFolder.isDirectory()) {
                                File[] glbFiles = glbFolder.listFiles((dir, name) -> name.toLowerCase().endsWith(".glb"));
                                if (glbFiles != null && glbFiles.length > 0) {
                                    for (File glbFile : glbFiles) {
                                        String name = glbFile.getName();
                                        String glbUrl = "aida-threed/male/glb/" + name;
                                        threeDSimple.setUrl(glbUrl);
                                        minioUtil.upload(glbUrl, glbFile);
                                    }
                                } else {
                                    System.out.println("未找到 GLB 文件。" + glbFolder);
                                }
                            } else {
                                System.out.println("GLB 文件夹不存在: " + glbPath);
                            }
//                            threeDSimpleMapper.insert(threeDSimple);
                            threeDDetail.setThreeDSimpleId(threeDSimple.getId());
                            threeDDetailMapper.updateById(threeDDetail);
                        }else {
                            Long id = threeDSimples.get(0).getId();
                            threeDDetail.setThreeDSimpleId(id);
                            threeDDetailMapper.updateById(threeDDetail);
                        }

                    } else {

                    }

                }
            } else {
                System.out.println("未找到 ZIP 文件。");
            }
            log.info("aaa");
        } else {
            System.out.println("文件夹不存在或不是一个目录。");
        }
    }
}
