package thyyxxk.webserver.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.entity.ResultVo;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @description: 新医保交易工具类
 * @author: DingJie
 * @create: 2021-05-14 16:41:21
 **/
@Component
@Slf4j
public class SiUtil {

    private static final String RESULT_CODE = "infcode";
    private static final String ERROR_MESSAGE = "err_msg";

    public static ResultVo<String> makeReturnWithoutOutput(JSONObject result, String message) {
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            return ResultVoUtil.success(message);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }


    public static Queue<String> readTxtFile(String path) {
        Queue<String> result = new LinkedList<>();
        try {
            File file = new File(path);
            InputStreamReader isr = new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String temp;
            while ((temp = br.readLine()) != null) {
                result.add(temp);
            }
        } catch (Exception e) {
            log.error("读取txt文件出错", e);
            return new LinkedList<>();
        }
        return result;
    }

    /**
     * @Description 需要返回其他信息
     * @Author hsh
     * @Date 2025/6/4 0004 18:07
     */
    public static ResultVo<JSONObject> makeReturnWithoutOutputOfElseInfo(JSONObject result) {
        if (null == result) {
            return ResultVoUtil.fail(ExceptionEnum.NETWORK_ERROR);
        }
        if (result.getIntValue(RESULT_CODE) == 0) {
            return ResultVoUtil.success(result);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, result.getString(ERROR_MESSAGE));
    }

}
