package com.qmth.paper.library;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.paper.library.business.entity.PaperLibrary;
import com.qmth.paper.library.business.service.PaperLibraryService;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.enums.UploadFileEnum;
import com.qmth.paper.library.common.util.FileStoreUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 短信工具测试类
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class CheckFileTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(CheckFileTest.class);

    @Resource
    PaperLibraryService paperLibraryService;

    @Resource
    FileStoreUtil fileStoreUtil;

    // 根目录必须为学校ID那一层
    String rootPath = "/Users/xiaofei/qmth/temporary/paperlibrary/jhut/image/10";

    @Test
    public void checkFile() {
        Long schoolId = 10L;

        File file = new File(rootPath);
        File[] rootFiles = file.listFiles();
        List<PaperLibrary> finalList = new ArrayList<>();
        for (File file1 : rootFiles) {
            if (file1.isDirectory()) {
                String file1Name = file1.getName();
                if (".DS_Store".equals(file1Name)) {
                    continue;
                }
                File[] docFiles = file1.listFiles();
                for (File file2 : docFiles) {
                    // 第二级为扫描任务ID
                    String paperScanTaskId = file2.getName();
                    if (".DS_Store".equals(paperScanTaskId)) {
                        continue;
                    }
                    QueryWrapper<PaperLibrary> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(PaperLibrary::getPaperScanTaskId, paperScanTaskId);
                    List<PaperLibrary> paperLibraryList = paperLibraryService.list(queryWrapper);
                    File[] files = file2.listFiles();

                    Map<String, PaperLibrary> map = new HashMap<>();

                    List<String> txtList = new ArrayList<>();

                    // 以下为图片
                    for (File imageFile : files) {
                        String name = imageFile.getName();
                        if (".DS_Store".equals(name)) {
                            continue;
                        }
                        // 后缀
                        int suffixIndex = name.lastIndexOf(".");
                        String suffix = name.substring(suffixIndex);

                        // 序号
                        int lastSlice = name.lastIndexOf("-");
                        String newName = name.substring(0, lastSlice);

                        if (map.containsKey(newName)) {
                            continue;
                        }


                        int lastSlice2 = newName.lastIndexOf("-");
                        String sequence = newName.substring(lastSlice2 + 1);

                        Long createId = paperLibraryList.get(0).getCreateId();

                        List<PaperLibrary> paperLibraryList1 = paperLibraryList.stream().filter(m -> m.getPath().indexOf(name) > 0).collect(Collectors.toList());
                        if (paperLibraryList1.isEmpty()) {
                            String format = String.format("任务编号：%s，文件名为：%s", paperScanTaskId, name);
                            LOGGER.info("任务编号：{}，文件名为：{}图片未保存", paperScanTaskId, name);
                            txtList.add(format);

                            String rootPath = fileStoreUtil.buildPath(schoolId, Long.valueOf(file.getName()), Long.valueOf(paperScanTaskId), UploadFileEnum.IMAGE, false);
                            List<JSONObject> objects = new ArrayList<>();
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put(SystemConstant.TYPE, SystemConstant.LOCAL);
                            jsonObject1.put(SystemConstant.PATH, rootPath + "\\" + newName + "-1" + suffix);
                            jsonObject1.put(SystemConstant.UPLOAD_TYPE, "IMAGE");
                            objects.add(jsonObject1);

                            JSONObject jsonObject2 = new JSONObject();
                            jsonObject2.put(SystemConstant.TYPE, SystemConstant.LOCAL);
                            jsonObject2.put(SystemConstant.PATH, rootPath + "\\" + newName + "-2" + suffix);
                            jsonObject2.put(SystemConstant.UPLOAD_TYPE, "IMAGE");
                            objects.add(jsonObject2);


                            PaperLibrary paperLibrary = new PaperLibrary();
                            paperLibrary.setId(SystemConstant.getDbUuid());
                            paperLibrary.setPaperScanTaskId(Long.valueOf(paperScanTaskId));
                            paperLibrary.setPath(JSON.toJSONString(objects));
                            paperLibrary.setSequence(Integer.valueOf(sequence));
                            paperLibrary.setCreateId(createId);
                            paperLibrary.setCreateTime(System.currentTimeMillis());
                            finalList.add(paperLibrary);
                            map.put(newName, paperLibrary);
                        }
                    }
                    if (!txtList.isEmpty()) {
                        txtList.sort(Comparator.comparing(s -> s));
                        String fileName = file1Name + "-" + paperScanTaskId + ".txt";
                        this.writeTxtFile(fileName, txtList);
                    }

                }
            }
        }
        // 按任务保存
//            paperLibraryService.saveBatch(finalList);
    }


    private void writeTxtFile(String fileName, List<String> textList) {
        try {
            File file = new File(rootPath + File.separator + "txt", fileName);
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            } else {
                file.getParentFile().mkdirs();
            }

            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            for (String text : textList) {
                bufferedWriter.write(text);
                bufferedWriter.newLine();
            }

            bufferedWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
