package com.nokia.domainb.capability;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nokia.domainb.util.Utils;
import de.siegmar.fastcsv.writer.CsvWriter;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Set;

class GetEcreditTest {
    @Test
    void testQuery() {
        GetEcredit getEcredit = new GetEcredit();
        String result = getEcredit.query("18622305641");
        System.out.println(result);
        JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
        JsonObject rsp = jsonObject.getAsJsonObject("UNI_BSS_BODY")
                .getAsJsonObject("GET_ECREDIT_RSP")
                .getAsJsonObject("RSP");
//        String rspCode = rsp.get("RSP_CODE").getAsString();
//        if (!"0000".equals(rspCode)) {
//            String rspDesc = rsp.get("RSP_DESC").getAsString();
//            return R.error().message(rspDesc);
//        }

        JsonObject data = rsp.getAsJsonArray("DATA").get(0).getAsJsonObject();
        JsonObject creditInfo = data.getAsJsonObject("CREDIT_INFO");
//        if (creditInfo == null) {
//            String detail = data.get("detail").getAsString();
//            return R.error().message(detail);
//        }
        String creditClass = creditInfo.get("CREDIT_CLASS").getAsString();
        String totalCreditValue = creditInfo.get("TOTAL_CREDIT_VALUE").getAsString();
        String availableCreditValue = creditInfo.get("AVAILABLE_CREDIT_VALUE").getAsString();
        System.out.println(creditClass);
        System.out.println(totalCreditValue);
        System.out.println(availableCreditValue);
    }
    @Test
    void test() {
        GetEcredit getEcredit = new GetEcredit();
        Set<String> phones = Utils.readPhones();
//        String filePath = "result/用户信用度查询样本.csv";
        String filePath = "result/用户信用度查询.csv";
        try (OutputStreamWriter osw = new OutputStreamWriter(Files.newOutputStream(Paths.get(filePath)), "GBK");
             CsvWriter csv = CsvWriter.builder().build(osw);) {
            csv.writeRow("手机号", "时间", "调用时长", "结果");
            phones.forEach(t -> {
                String[] a = t.split(",");
                String phone = a[0];
                LocalDateTime startTime = LocalDateTime.now();
                long startTimestamp = System.currentTimeMillis();
                String result = getEcredit.query(phone, false);
                long endTimestamp = System.currentTimeMillis();
                long cost = endTimestamp - startTimestamp;
                csv.writeRow(phone, startTime.toString(), String.valueOf(cost), result);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
