package com.library.TopUp.mefont;

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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MetfoneSentUtils {


    private final static String baseUrl = "https://36.37.242.116:8301/";
    //    private final static String baseUrl = "https://payment.emoney.com.kh:8888/";
    private final static String PIN = "298315";

    public static String initTel(String transAmount, String refId, String customerPhoneNumber) {

        Map params = new HashMap();

        params.put("serviceType", "TOPUP");
        params.put("transAmount", transAmount);
        params.put("currency", "USD");
        params.put("refId", refId);
        params.put("customerPhoneNumber", customerPhoneNumber);


        Map<String, String> heardMap = new HashMap<>();
        heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
        heardMap.put("e-language", "English");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("Accept", "application/json");

        String url = baseUrl + "ePayTest/telco/init";
//        String urlTest="https://36.37.242.116:8301/ePayTest/telco/init";
        String str = HttpUtils.post(url,
                params, heardMap
                , 3000, 3000, "UTF-8");

        return str;
    }

    public static String confirmTel(String txPaymentTokenId) {

        Map<String, String> heardMap = new HashMap<>();
        heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
        heardMap.put("e-language", "English");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("Accept", "application/json");

        Map params = new HashMap();
        params.put("txPaymentTokenId", txPaymentTokenId);

        String conURL = baseUrl + "ePayTest/telco/confirm";

        String str = HttpUtils.post(conURL,
                params, heardMap
                , 3000, 3000, "UTF-8");

        return str;
    }

    public static String initTelPost(String transAmount, String refId, String customerPhoneNumber) {

        try {

//            Map params = new HashMap();
            Map<String, String> params = new HashMap<>();
            params.put("serviceType", "TOPUP");
            params.put("transAmount", transAmount);
            params.put("currency", "USD");
            params.put("refId", refId);
            params.put("customerPhoneNumber", customerPhoneNumber);


            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
            heardMap.put("e-language", "English");
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");


            String requestUrl = baseUrl + "ePayTest/telco/init";
            String str = HttpsTool.send(new Gson().toJson(params), heardMap, requestUrl, "utf-8",
                    "utf-8", 300 * 1000, 300 * 1000,
                    "application/json");// 大家最终只要使用这一句代码就可调用


            return str;

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


    public static String confirmPost(String txPaymentTokenId) {

        try {

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
            heardMap.put("e-language", "English");
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");

            Map params = new HashMap();
            params.put("txPaymentTokenId", txPaymentTokenId);

            String conURL = baseUrl + "ePayTest/telco/confirm";
            String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
                    "utf-8", 300 * 1000, 300 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
            return senc;

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

    public static String checkPayPost(String transDetailId, String refId) {

        try {

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
            heardMap.put("e-language", "English");
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");

            Map params = new HashMap();
            params.put("transDetailId", transDetailId);
            params.put("refId", refId);

            String conURL = baseUrl + "ePayTest/trans/check";
            String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
                    "utf-8", 300 * 1000, 300 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
            return senc;

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

    public static String billInfoPost(String paymentCode) {

        try {

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
            heardMap.put("e-language", "English");
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");

            Map params = new HashMap();
            params.put("paymentCode", paymentCode);

            String conURL = baseUrl + "ePayTest/telco/metfone-bill/info";
            String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
                    "utf-8", 300 * 1000, 300 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用
            return senc;

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

    /**
     * 查询系统我的账户余额
     *
     * @param refId
     * @param msisdn
     * @return
     */
    public static String checkMyMoneyPost(String refId, String msisdn) {

        try {

            Map<String, String> heardMap = new HashMap<>();
            heardMap.put("Authorization", "epa 2478e27af578e11a6af86a8320562124240f5c972e8039cd9c564e53d643bb31");
            heardMap.put("e-language", "English");
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");

            String pin = PIN + "|" + msisdn + "|" + refId;

            Map params = new HashMap();
            params.put("refId", refId);
            params.put("serviceType", "TOPUP");
            params.put("msisdn", msisdn);
            params.put("pin", MetfoneRSAUtils.encryptRSA(pin));//encrypt the plain text in format "pin|msisdn|refId

            String conURL = baseUrl + "ePayTest/account/balance";
            String senc = HttpsTool.send(new Gson().toJson(params), heardMap, conURL, "utf-8",
                    "utf-8", 300 * 1000, 300 * 1000,
                    "application/json");// 大家最终只要使用这一句代码就可调用
            return senc;

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

    public static void main(String[] args) {
/*        String str = checkMyMoneyPost("1200016", "0979530750");
//{"status":0,"code":"MSG_SUCCESS","message":"Success","msisdn":null,"accountName":null,"accountType":null,"balances":{"KHR":"498,983","USD":"5,135.60"}}
        System.out.println(str);*/


        String str = checkMyMoneyPost("20010818431127","0979530750");
        System.out.println(str);
    }

    public static void main222(String[] args) {

        String phone = "0979530750";
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        String hms = sdf.format(new Date());

        ResultsModel resultsModel=sentTopUp(phone, 1, hms);
        System.out.println("充值日志："+resultsModel.getTip());
        System.out.println("充值状态："+resultsModel.isSuccessful());
        System.out.println("拓展字段："+resultsModel.getExpandText());
    }

    /**
     * 发起充值
     *
     * @param phone
     * @param amount
     * @param orderNum
     * @return
     */
    public static ResultsModel sentTopUp(String phone, int amount, String orderNum) {

        String tip = "";
        boolean topUpSuccess = false;
        try {
            String refId = orderNum;
            String transDetailId = "";//可以用来复查充值订单数据

            String json = initTelPost(String.valueOf(amount), refId, phone);
            String tokenId = "";
            if (!TextUtils.isEmpty(json)) {
                JsonObject object = new JsonParser().parse(json).getAsJsonObject();
                String status = object.get("status") == null ? "" : object.get("status").getAsString();
                //请求是否成功
                if (status.equals("0")) {
                    JsonObject txDetail = object.get("txDetail").getAsJsonObject();
                    if (txDetail != null) {
                        //获取需要解密的值
                        tokenId = txDetail.get("txPaymentTokenId").getAsString();
                        transDetailId = txDetail.get("transDetailId").getAsString();
                    } else {
                        tip += "返回值txDetail为空";
                    }
                } else {
                    tip += "initTel返回结果：" + new Gson().toJson(object) + " \n";
                }
            } else {
                tip += "返回值为空";
            }

            String conStr = "";
            if (!TextUtils.isEmpty(tokenId)) {
                String str = MetfoneRSAUtils.decryptRSA(tokenId);

                String encryptText = str + "|" + PIN;
//            tip += "解析的值：" + encryptText;
                String retStr = MetfoneRSAUtils.encryptRSA(encryptText);
//            tip += "\n" + "加密后的值：" + retStr;

                //发起充值
                conStr = confirmPost(retStr);

            }


            //处理返回结果
            if (!TextUtils.isEmpty(conStr)) {
                //有结果返回

                System.out.println(conStr);
                JsonObject confirmObject = new JsonParser().parse(conStr).getAsJsonObject();
                String status = confirmObject.get("status") == null ? "" : confirmObject.get("status").getAsString();
                if (status.equals("0")) {
                    System.out.println("充值成功");
                    topUpSuccess = true;
                    tip += " 充值成功！！！";
                } else {
                    tip += "confirmTel返回结果：" + new Gson().toJson(confirmObject) + " \n";
                }
            }

//            String checkStr = checkPayPost(transDetailId, refId);
//            System.out.println(checkStr);

            return new ResultsModel(topUpSuccess, tip, transDetailId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultsModel(topUpSuccess, tip);
        }
    }
}
