package com.keyware.shandan.mark.config;

import cn.hutool.core.io.FileUtil;
import com.keyware.shandan.frame.properties.CustomProperties;
import com.keyware.shandan.mark.pojo.MarkFile;
import com.keyware.shandan.mark.pojo.MarkRecord;
import com.keyware.shandan.mark.pojo.MarkType;
import com.keyware.shandan.mark.services.MarkTypeService;
import com.keyware.shandan.system.entity.SysFile;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author GuoXin
 * @date 2022-07-26
 */
@Component
public class MarkFileBuilder {
    private final String MH = ":";
    private final String FH = ";";
    private final String DH = ",";

    @Autowired
    private CustomProperties properties;
    @Autowired
    private MarkTypeService markTypeService;


    @SneakyThrows
    public MarkFile build(SysFile file) {
        MarkFile markFile = new MarkFile();
        markFile.setDirectoryId(file.getEntityId());
        markFile.setMarkConfig(parseMarkFile(file));
        return markFile;
    }

    private Map<String, List<MarkRecord>> parseMarkFile(SysFile file) throws IOException {
        String filePath = properties.getFileStorage().getPath() + File.separator + file.getPath();
        File localFile = new File(filePath);
        Assert.isTrue(localFile.exists(), "初始化置标文件异常，没有找到置标文件");

        BufferedReader reader = FileUtil.getUtf8Reader(localFile);
        List<String> lines = reader.lines().map(this::replaceSeparator).collect(Collectors.toList());
        reader.close();
        Map<String, List<MarkRecord>> markRecordMap = new HashMap<>();
        lines.forEach(line -> {
            parseLine(line, markRecordMap);
        });
        return markRecordMap;
    }

    /**
     * 解析行<br>
     * 置标文件统一使用如下格式：<br>
     * 默认置标：置标类型1：标签1，标签2；置标类型2：标签1，标签2<br>
     * xx文件：置标类型1：标签1，标签2；置标类型1：标签1，标签2
     *
     * @param line 行
     * @param map  map
     */
    private void parseLine(@NotNull String line, Map<String, List<MarkRecord>> map) {
        String key = line.split(MH)[0].trim();
        String content = line.substring(line.indexOf(MH)+ 1);
        List<MarkRecord> records = new ArrayList<>();
        for (String s : content.split(FH)) {
            String[] items = s.split(MH);
            String markType = items[0];
            String markTags = items.length < 2 ? "" : checkMarkTags(items[1]);
            MarkRecord record = new MarkRecord();
            record.setFormType("fileUploadForm");

            MarkType type = markTypeService.getByName(markType);
            if (type == null) {
                type = new MarkType(markType, markTags);
                markTypeService.save(type);
            }
            record.setMarkType(String.valueOf(type.getId()));
            record.setMarkValue(markTags);
            records.add(record);
        }
        map.put(key, records);
    }

    private String replaceSeparator(String line) {
        return line.replace("：", ":")
                .replace("，", ",")
                .replace("；", ";");
    }

    private String checkMarkTags(@NotNull String tags) {
        String[] arr = tags.split(DH);
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i].trim();
        }
        return String.join(",", arr);
    }
}
