package com.youchain.utils.readFilebak;

import com.google.common.collect.Maps;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.BigItem;
import com.youchain.basicdata.domain.BomAccount;
import com.youchain.basicdata.domain.ProductionPlan;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.repository.ProductionPlanRepository;
import com.youchain.basicdata.service.BomAccountService;
import com.youchain.businessdata.domain.Spareparts;
import com.youchain.businessdata.repository.SparepartsRepository;
import com.youchain.businessdata.service.InventoryBakService;
import com.youchain.utils.BizStatus;
import com.youchain.utils.DateUtil;
import com.youchain.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@Component
@Slf4j
@Service
public class ReadUbuntuFiles  {
    private static final String SOURCE_DIR = "/home/1panel/1panel/apps/sftpgo/sftpgo/data/data/data/kcw";
//    private static final String SOURCE_DIR = "E:/data/kcw";
    // bak文件夹测试路径：E:\test\bak
    private static final Path BAK_DIR = Paths.get(SOURCE_DIR).resolve("bak");

    @Autowired
    private ReadFileDataRepository readFileDataRepository;
    @Autowired
    private SparepartsRepository sparepartsRepository;
    @Autowired
    private BigItemRepository bigItemRepository;
    @Autowired
    private BomAccountService bomAccountService;
    @Autowired
    private InventoryBakService inventoryBakService;

    public ReadUbuntuFiles () {
        log.info("定时读取ubuntu文件");
    }
    // 定时任务执行器
    private ScheduledExecutorService scheduler;

//    @PostConstruct
//    public void init() {
//        // 初始化定时任务：延迟0秒开始，每次执行完间隔3秒
//        scheduler = Executors.newSingleThreadScheduledExecutor();
//        scheduler.scheduleWithFixedDelay(
//                this::read,  // 执行的任务（调用read方法）
//                0,          // 首次执行延迟时间（0秒后立即开始）
//                5,          // 上一次任务结束到下一次任务开始的间隔（3秒）
//                TimeUnit.SECONDS  // 时间单位
//        );
//        log.info("定时任务已启动，每次执行完间隔3秒");
//    }
    // 业务逻辑：读取文件并处理
    public void readFtp() {
        log.info("开始读取ubuntu文件");
        Path directory = Paths.get(SOURCE_DIR);

        // 检查目录有效性
        if (!Files.exists(directory)) {
            log.error("目录不存在：" + SOURCE_DIR);
            return;
        }
        if (!Files.isDirectory(directory)) {
            log.error("路径不是目录：" + SOURCE_DIR);
            return;
        }
        // 解析结果集
        List<ReadFileData> readFileDataList=new ArrayList<>();

        List<Spareparts> sparepartsList=new ArrayList<>();
        List<BigItem> bigItemRepositories=bigItemRepository.findAll();
        Map<String, BigItem> itemMap = Maps.newHashMap();
        for (BigItem item : bigItemRepositories) {
            itemMap.put(item.getCode(), item);
        }
        Map<String, String> zsbigCode = Maps.newHashMap();
        List<Spareparts> sparepartsList1=sparepartsRepository.findAll();
        for (Spareparts spareparts : sparepartsList1) {
            if(spareparts.getStartNumber()!=null&&!spareparts.getStartNumber().equals("")) {
                zsbigCode.put(spareparts.getStartNumber(), spareparts.getStartNumber());
            }
        }
        // 遍历目录下的文件并处理每行内容
        try (Stream<Path> pathStream = Files.list(directory)) {
            pathStream.filter(Files::isRegularFile)
                    .forEach(file -> {
                        log.info("\n===== 处理文件：" + file + " =====");
                        try {
                            // 读取文件所有行（UTF-8编码）
                            List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
                            int i=1;
                            // 遍历每行并处理
                            for (String line : lines) {
                                // 1. 去除首尾空格；2. 将连续空格（1个以上）替换为单个空格
                                String processedLine = line.trim().replaceAll("\\s+", " ");
                                // 输出处理后的行
                                log.info(processedLine);
                                String[] processed = processedLine.split(" ");

                                // 校验格式，并写入结果集
                                ReadFileData readFileData=new ReadFileData();
                                String bigItemCode=processed[0];
                                readFileData.setBigItemCode(processed[0]);
                                readFileData.setAreaCode(processed[1]);
                                readFileData.setWorkingStation(processed[2]);
                                readFileData.setDownlineDate(processed[3]);
                                readFileData.setMakeLine(processed[4]);
                                readFileDataList.add(readFileData);

                                if(bigItemCode!=null&&bigItemCode.length()>=19){
                                    String idNo=bigItemCode.substring(0,9);
                                    String bigCode=bigItemCode.substring(9,19);
                                    String startNumber=bigItemCode.substring(0,19);
                                    BigItem bigItem=itemMap.get(bigCode);
                                    Spareparts spareparts = new Spareparts();
                                    spareparts.setStatus("UN_CONSUME");
                                    if(zsbigCode.get(startNumber)!=null){
                                        spareparts.setStatus("CF_DATA");
                                    }
                                    spareparts.setDate(new Timestamp(new Date().getTime()));
                                    spareparts.setKyQz(idNo.substring(0,2));
                                    spareparts.setBigItemId(bigItem);
                                    spareparts.setOrderQuantity(1);
                                    spareparts.setDescription("FTP自动耗用:"+bigItemCode);
                                    spareparts.setStartNumber(startNumber);//重复则直接将状态改为重复接收
                                    sparepartsList.add(spareparts);
                                    i++;
                                }
                            }
                            // 关键修改：将当前处理的文件（file）移动到bak文件夹，而非目录（directory）
                            moveToBakWithoutSubDir(file, DateUtil.getCurrentTimeAsString());
                        } catch (IOException e) {
                            log.error("处理文件失败：" + file + "，原因：" + e.getMessage());
                        }
                    });
        } catch (IOException e) {
            log.error("遍历目录失败：" + e.getMessage());
        }
        readFileDataRepository.saveAll(readFileDataList);
        sparepartsRepository.saveAll(sparepartsList);
    }

    public void ftpHy() {
        log.info("开始自动耗用下线数据");
        List<Spareparts> list=sparepartsRepository.getSparepartsList();
        for(Spareparts s:list) {
            String kyQz = s.getKyQz();
            List<BomAccount> bs = bomAccountService.queryBomAccountKy(s.getBigItemId().getId(),null, kyQz);
            if (bs.size() <= 0) {
                s.setSourceId("未查到" + kyQz + "对应BOM工位清单");
            }
            bomAccountService.bomTcInvDeal(bs,s.getOrderQuantity(),s.getBigItemId().getCode(),s.getId());
            s.setStatus(BizStatus.CONSUME);
            s.setHyBy("系统自动耗用");
            s.setHyTime(new Timestamp(new Date().getTime()));
            sparepartsRepository.save(s);
        }
    }

    /**
     * 将文件移动到当前目录的bak文件夹，并添加指定后缀
     * @param sourceFile 源文件路径
     * @throws IOException 移动文件或创建目录时发生异常
     */
    public static void moveToBakWithoutSubDir(Path sourceFile, String key) throws IOException {
        // 1. 构建bak文件夹路径（源文件同级目录下的bak，即E:\test\bak）
        Path parentDir = sourceFile.getParent();
        if (parentDir == null) {
            throw new IllegalArgumentException("源文件路径无效，无法获取父目录：" + sourceFile);
        }
        Path bakDir = parentDir.resolve("bak");

        // 2. 确保bak文件夹存在
        if (!Files.exists(bakDir)) {
            Files.createDirectory(bakDir);
            log.info("已创建bak文件夹：" + bakDir);
        }

        // 3. 生成目标文件名（原文件名 + 时间后缀）
        String originalFileName = sourceFile.getFileName().toString();
        String safeFileName = originalFileName.replaceAll("[\\\\/]", "_");
        String targetFileName = key+"_"+safeFileName;

        // 4. 构建目标文件路径
        Path targetFile = bakDir.resolve(targetFileName);

        // 5. 移动文件（覆盖已存在的同名文件）
        Files.move(
                sourceFile,
                targetFile,
                StandardCopyOption.REPLACE_EXISTING
        );

        log.info("文件已移动至：" + targetFile);
    }

    @Log("定时备份库存数据")
    public void backInvHis() {
        log.info("开始定时备份库存数据"+new Date());
        inventoryBakService.insertInvHis();
        log.info("定时备份库存数据完成"+new Date());
    }
}
