package com.library.TopUp.cellcard;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.library.TopUp.Http.HttpUtils;
import com.library.TopUp.Http.HttpsTool;
import com.library.TopUp.model.ResultsModel;
import org.apache.http.util.TextUtils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class CellcardSentUtils {

    private final static String distributor_id = "35";

    private static String access_token = "";
    private static String token_type = "";


    public static String getToken() {

        try {

            Map<String, String> params = new HashMap();
            params.put("grant_type", "client_credentials");

            String keyAndSecret = "v2VSgq7Q2Yqhp36s5TOzD13J5FMa:Go0wTNZdR53xNbxHwhneLF1p40Ma";
            String code = Base64.getEncoder().encodeToString(keyAndSecret.getBytes("UTF-8"));

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", "Basic " + code);
//            heardMap.put("Content-Type", "application/json");
//            heardMap.put("Accept", "application/json");


            String url = "https://stg-api.cellcard.com.kh:8243/token";

//            HttpClientResult clientResult = HttpClientUtils.doPost(url, heardMap, params);
////            System.out.println(new Gson().toJson(clientResult));
////            return clientResult.getContent();

            String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");

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

    public static String checkBalance(String transaction_id) {

        try {

            Map<String, String> params = new HashMap();
            params.put("transaction_id", transaction_id);
            params.put("distributor_id", distributor_id);

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", token_type + " " + access_token);
            heardMap.put("Content-Type", "application/x-www-form-urlencoded");
//            heardMap.put("Accept", "application/json");


            String url = "https://stg-api.cellcard.com.kh:8243/tom/v2/query_balance";

            String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");
            return json;

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


    public static String rechargePhone(String phone, int amount, String transaction_id) {

        try {

            String amountStr = String.valueOf(amount * 10000);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String timestamp = sdf.format(new Date());

            Map<String, String> params = new HashMap();
            params.put("distributor_id", distributor_id);
            params.put("subscriber", phone);
            params.put("amount", amountStr);//Top-up amount in centi-cent 1$=10000. The minimum value is 2500.
            params.put("transaction_id", transaction_id);
            params.put("timestamp", timestamp);

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", token_type + " " + access_token);
            heardMap.put("Content-Type", "application/x-www-form-urlencoded");

            String url = "https://stg-api.cellcard.com.kh:8243/tom/v2/balance_transfer";

            String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");
            return json;

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

    /**
     * By some reasons client not get response from API after top up request. It could be
     * connection broken, timing out, service hanging, internal error, … To clarify the transaction
     * status we implement one more step to check in OCS’s CDR which date available in 3 months
     * backward.
     * <p>
     * SLA: This API effective after 10 minutes from client got timeout
     * response (Need times to collect CDR)
     *
     * @param phone
     * @param transaction_id
     * @return
     */
    public static String topUpStatus(String phone, String transaction_id) {

        try {
            String tokenStr = "";
            String jsonToken = getToken();
            if (!TextUtils.isEmpty(jsonToken)) {
                JsonParser jsonParser = new JsonParser();
                JsonObject jsonObject = jsonParser.parse(jsonToken).getAsJsonObject();
                tokenStr = jsonObject.get("access_token") == null ? "" : jsonObject.get("access_token").getAsString();

                if (!TextUtils.isEmpty(tokenStr)) {
                    token_type = jsonObject.get("token_type") == null ? "" : jsonObject.get("token_type").getAsString();
                    access_token = tokenStr;
                }
            }

            if (TextUtils.isEmpty(tokenStr)) {
                return "";
            }


            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String timestamp = sdf.format(new Date());

            Map<String, String> params = new HashMap();
            params.put("distributor_id", distributor_id);
            params.put("subscriber", phone);
            params.put("transaction_id", transaction_id);
            params.put("transaction_date", timestamp);

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", token_type + " " + access_token);
            heardMap.put("Content-Type", "application/x-www-form-urlencoded");

            String url = "https://stg-api.cellcard.com.kh:8243/tom/v2/transaction_status";

            String json = HttpUtils.post(url, params, heardMap, 30000, 30000, "utf-8");
            return json;

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


    public static void main(String[] args) {


//        String json = topUpStatus("85561254730", "123");
        ResultsModel model = sentTopUp("855061254730", "123", 1);
        System.out.println("充值结果 " + model.getTip());
        System.out.println("充值状态" + model.isSuccessful());
    }

    /**
     * 发起充值
     *
     * @param phone    11为数的手机号码
     * @param orderNum 唯一编号
     * @param amount   充值金额 ，单位1美元 里面做了乘以10000的操作了
     */
    public static ResultsModel sentTopUp(String phone, String orderNum, int amount) {

        String tip = "";
        boolean isSuccessful = false;

        try {
            String jsonToken = getToken();

            String rechargeJson = "";
            if (!TextUtils.isEmpty(jsonToken)) {
                JsonParser jsonParserToken = new JsonParser();
                JsonObject jsonObjectToken = jsonParserToken.parse(jsonToken).getAsJsonObject();
                String tokenStr = jsonObjectToken.get("access_token") == null ? "" : jsonObjectToken.get("access_token").getAsString();

                if (!TextUtils.isEmpty(tokenStr)) {
                    token_type = jsonObjectToken.get("token_type") == null ? "" : jsonObjectToken.get("token_type").getAsString();
                    access_token = tokenStr;
                    tip += "令牌解析成功；准备发起充值；";

                    /**
                     * 发起充值
                     */
                    rechargeJson = rechargePhone(phone, amount, orderNum);
                } else {
                    tip += "令牌解析失败：" + jsonToken;
                }
            } else {
                tip += "令牌获取失败; ";
            }

            String transaction_id = "";
            if (!TextUtils.isEmpty(rechargeJson)) {
                JsonParser jsonParserRecharge = new JsonParser();
                JsonObject jsonObjectRecharge = jsonParserRecharge.parse(rechargeJson).getAsJsonObject();
                if (jsonObjectRecharge != null) {
                    JsonObject data = jsonObjectRecharge.get("data") == null ? null : jsonObjectRecharge.get("data").getAsJsonObject();
                    if (data != null) {
                        //有data对象
                        String error_code = data.get("error_code") == null ? "" : data.get("error_code").getAsString();
                        if (!TextUtils.isEmpty(error_code) && error_code.equals("0")) {
                            //充值成功
                            transaction_id = data.get("transaction_id") == null ? "" : data.get("transaction_id").getAsString();

                            tip += " 充值成功！！！";
                            isSuccessful = true;
                        } else {
                            //充值报错
                            tip += "充值失败,返回结果：" + rechargeJson;
                        }
                    } else {
                        tip += "充值无data返回，返回结果：" + rechargeJson;
                    }
                } else {
                    tip += "充值报错，解析失败，返回结果：" + rechargeJson;
                }
            }

            ResultsModel model = new ResultsModel(isSuccessful, tip);
            return model;
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

}
