package com.gitee.sop.gateway;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.gitee.sop.gateway.message.CodeEnum;
import com.gitee.sop.gateway.message.ErrorEnum;
import com.gitee.sop.support.message.OpenMessageFactory;
import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @author 六如
 */
public class ErrorCodePrintTest {
    @Test
    public void print() {
        OpenMessageFactory.initMessage();

        ErrorEnum[] values = ErrorEnum.values();
        Map<String, List<ErrorEnum>> codeMap = Stream.of(values)
                .collect(Collectors.groupingBy(ErrorEnum::getCode));

        AtomicInteger id = new AtomicInteger();
        List<ErrorInfo> errorList = codeMap.entrySet()
                .stream()
                .map(entry -> {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setId(id.incrementAndGet());
                    errorInfo.setCode(entry.getKey());
                    errorInfo.setMsg(CodeEnum.of(entry.getKey()).getConfigValue());

                    List<SubError> collect = entry.getValue()
                            .stream()
                            .filter(errorEnum -> StringUtils.hasText(errorEnum.getSubCode()))
                            .map(errorEnum -> {
                                SubError subError = new SubError();
                                subError.setId(id.incrementAndGet());
                                subError.setSub_code(errorEnum.getSubCode());
                                subError.setSub_msg(errorEnum.getError(Locale.CHINESE).getSubMsg());
                                subError.setSolution("");
                                return subError;
                            })
                            .collect(Collectors.toList());

                    errorInfo.setChildren(collect);

                    return errorInfo;
                })
                .collect(Collectors.toList());

        System.out.println(JSON.toJSONString(errorList, JSONWriter.Feature.PrettyFormat));

    }

    @Data
    static class ErrorInfo {
        private Integer id;
        private String code;
        private String msg;
        private List<SubError> children;
    }

    @Data
    static class SubError {
        private Integer id;
        private String sub_code;
        private String sub_msg;
        private String solution;
    }
}
