package com.persagy.bdtp.adm.test.data;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.persagy.bdtp.adm.entity.db.AdmInfosConfig;
import lombok.Data;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class InfosCfgs {

    public static void main(String[] args) throws Exception {
        new InfosCfgs().read("se");
    }

    private ObjectMapper objectMapper = new ObjectMapper();;
    private List<AdmInfosConfig> eqList = new ArrayList<>();
    private AdmInfosConfig eq;
    private String group;
    private String major;

    public List<AdmInfosConfig> read(String type){
        major = type.toUpperCase();
        try (BufferedReader r = new BufferedReader(new FileReader("D:\\work_area\\adm_1015\\" + type + ".txt"))){
            String tmp;
            while ((tmp = r.readLine()) != null){
                readLine(tmp);
            }

            String json = objectMapper.writeValueAsString(eqList);
            System.out.println(json);

            return eqList;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void readLine(String line){
        if(StrUtil.isBlank(line))
            return;

        int preS = preS(line);
        String[] arr = line.trim().split("\\s", 9 - (preS == 0 ? 0 : preS - 1));

        if(arr.length < 3)
            return;

        readLine(preS, arr);
    }

    private void readLine(int preS, String[] arr) {
        if (preS <= 2) {
            eq = new AdmInfosConfig();
            eq.setId(IdUtil.simpleUUID());
            eqList.add(eq);
            eq.setName(arr[3 - preS]);
            eq.setClassCode(arr[4 - preS]);
            eq.setMajorCode(major);
            eq.setSystemCode(eq.getClassCode().substring(0, 4));
            eq.setObjType("equipment");
            eq.setInfos(new ArrayList<>());
        }
        if(preS <= 5){
            group = arr[5 - preS];
        }
        Info info = new Info();
        eq.getInfos().add(info);

        info.group = group;

        //debug
        if(6 - preS < 0 || 6 - preS >= arr.length)
            System.out.println();

        info.label = arr[6 - preS];
        info.code = arr[7 - preS];
        if(isCode(info.label)){
            String tmp = info.label;
            info.label = info.code;
            info.code = tmp;
        }

        //debug
        if(8 - preS >= arr.length)
            System.out.println();

        info.dataType = getDataType(arr[8 - preS]);
        String optionsStr = null;
        if(arr.length > 9 - preS) {
            String left = arr[9 - preS];
            if(left.charAt(0) == '\t')
                optionsStr = left.trim();
            else {
                String[] arr1 = left.split("\\s", 1);
                info.unit = arr1[0];
//                if(StrUtil.isNotBlank(info.unit) && info.unit.indexOf('%') >= 0)
//                    info.unit = info.unit.replace("%", "");
                if(arr1.length > 1)
                    optionsStr = arr1[1];
            }
        }
        if(StrUtil.isNotBlank(optionsStr))
          parseOptions(optionsStr, info);
    }

    private void parseOptions(String optionsStr, Info info) {
        List<Op> ops = new ArrayList<>();
        info.options = ops;

        if(optionsStr.startsWith("{")) {
            while(optionsStr.length() > 0){
                int p1 = optionsStr.indexOf("{");
                int p2 = optionsStr.indexOf("}");
                if(p1 >= 0 && p2 > 0) {
                    String item = optionsStr.substring(p1 + 1, p2);

                    String[] arr = item.split(":");
                    Op op = new Op();
                    op.val = arr[0];
                    op.txt = arr[1];
                    ops.add(op);

                    optionsStr = optionsStr.substring(p2 + 1);
                } else
                    break;
            }
        } else {
            String multi = "（可多选）";
            if(optionsStr.endsWith(multi)) {
                optionsStr = optionsStr.substring(0, optionsStr.length() - multi.length());
                info.inputType = "checkbox";
            }

            String[] arr = optionsStr.split("\\s+");
            if(arr.length < 2 || arr.length % 2 != 0)
                return;
            for (int i = 0; i < arr.length; ) {
                String id = arr[i];
                if(id.endsWith("."))
                    id = id.substring(0, id.length() - 1);

                //debug
                if(i + 1 >= arr.length)
                    System.out.println(optionsStr);

                String val = arr[i + 1];

                Op op = new Op();
                op.val = id;
                op.txt = val;
                ops.add(op);

                i += 2;
            }
        }
    }

    private String getDataType(String dtName){
        if(StrUtil.isBlank(dtName))
            return null;

        if("整数".equals(dtName))
            return "int";
        if("字符串".equals(dtName))
            return "string";
        if("浮点数".equals(dtName))
            return "float";
        if("枚举值".equals(dtName))
            return "string";
        if(dtName.indexOf("数组") >= 0)
            return "arr";
        return null;
    }

    private String getSeg(int segIdx, String line) {
        int s = 0;
        int idx = 0;
        StringBuilder code = null;
        while (idx < line.length()){
            char c = line.charAt(idx++);
            if(Character.isWhitespace(c)) {
                s++;
                if(s == segIdx)
                    code = new StringBuilder();
                else if(code != null)
                    break;
            } else if(code != null) {
                code.append(c);
            }
        }
        return code.toString();
    }

    private boolean isCode(String s){
        String pattern = "^[A-Za-z0-9]+$";
        return Pattern.matches(pattern, s);
    }

    private int preS(String line){
        int s = 0;
        while (s < line.length()){
            if(!Character.isWhitespace(line.charAt(s)))
                break;
            s++;
        }
        return s;
    }

    @Data
    class Info {

        String group;

        String code;

        String label;

        String dataType;

        String inputType;

        String unit;

        List<Op> options;

    }

    @Data
    class Op{
        private String txt;
        private Object val;
    }

}
