package com.library.TopUp.smart;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
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 net.sf.json.JSONObject;
import org.apache.http.util.TextUtils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

public class SmartSentUtils {

    private static String access_token = "";
    private static String refresh_token = "";
    private static String token_type = "";
    private static int expires_in;

    private final static String institution_id = "98198198";
    private final static String institution_password = "OTgxOTgxOTg=";


    public static String getToken() {

        try {

            Map params = new HashMap();
            params.put("grant_type", "password");
            params.put("username", "link.asia");
            params.put("password", "@@$$SSaa_8899");


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

            String url = "https://mife.smart.com.kh:8243/token";

            HttpClientResult clientResult = HttpClientUtils.doPost(url, heardMap, params);

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

            return clientResult.getContent();

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

    public static String refreshToken(String refresh_token) {

        try {

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


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

            String url = "https://mife.smart.com.kh:8243/token";

            HttpClientResult clientResult = HttpClientUtils.doPost(url, heardMap, params);


            return clientResult.getContent();

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


    public static String checkPhone(String phone) {

        try {

            String phoneStr = "tel:+855" + phone;
            String endPhone = URLEncoder.encode(phoneStr);

            Map params = new HashMap();

            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://mife.smart.com.kh:8243/api/etopup/pinless/v1.1/" + endPhone + "/eligibility";

            HttpClientResult clientResult = HttpClientUtils.doGet(url, heardMap, params);


            return clientResult.getContent();

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

    public static String rechargePhone(String phone, String amount, String correlation_id) {

        try {

            String phoneStr = "tel:+855" + phone;
            String endPhone = URLEncoder.encode(phoneStr);

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

            Map<String, String> params = new HashMap();
            params.put("institution_password", institution_password);
            params.put("correlation_id", correlation_id);
            params.put("amount", amount);
            params.put("channel", "WEB");

            String url = "https://mife.smart.com.kh:8243/api/etopup/pinless/v1.1/" + institution_id + "/recharge/" + endPhone + "";

            String json = HttpClientUtils.postWithJson(new Gson().toJson(params), url, heardMap);
//            String json = HttpsTool.send(new Gson().toJson(params), heardMap, url, "utf-8",
//                    "utf-8", 30 * 1000, 30 * 1000, "application/json");// 大家最终只要使用这一句代码就可调用

            return json;

//            return clientResult.getContent();

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

    public static String queryRechargePhone(String correlation_id) {

        try {


            String end_correlation_id = URLEncoder.encode(correlation_id);

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


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


            String url = "https://mife.smart.com.kh:8243/api/etopup/pinless/v1.1/" + institution_id + "/query/" + end_correlation_id + "";

            String json = HttpClientUtils.postWithJson(new Gson().toJson(params), url, heardMap);
            return json;

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


    public static void main222(String[] args) {

        /**
         * {
         *     "correlation_id": "Link Asia:87234159:20200109105959",
         *     "institution_id": "98198198",
         *     "subscriber_id": "tel:+85587234159",
         *     "amount": 100,
         *     "channel": "WEB",
         *     "instance_id": "0109110016004792"
         * }
         */

        String json = getToken();
        /**
         * {"access_token":"372b5f81-9662-3d75-abcf-639920880ce3","refresh_token":"d62d9da3-3730-35f7-9368-c82b43509db1","scope":"default","token_type":"Bearer","expires_in":3249}//
         */
        System.out.println(json);

        String tip="";
        String tokenStr = "";
        //判断是否成功获取到token
        if (!TextUtils.isEmpty(json)) {
            JsonParser jsonParser = new JsonParser();
            JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
            tokenStr = jsonObject.get("access_token") == null ? "" : jsonObject.get("access_token").getAsString();
            if (!TextUtils.isEmpty(tokenStr)) {
                access_token = tokenStr;
                refresh_token = jsonObject.get("refresh_token").getAsString();
                token_type = jsonObject.get("token_type").getAsString();
                expires_in = jsonObject.get("expires_in").getAsInt();
            } else {
                tip += " 返回结果：" + json;
            }
        } else {
            tip += " 返回值为空";
        }
        String jsonQuery = queryRechargePhone("Link Asia:87234159:20200109105959");//发起校验
        System.out.println(jsonQuery);
        System.out.println(tip);

    }
    public static void main(String[] args) {
        String phone = "87234159";
        ResultsModel resultsModel = sentTopUp(phone, 1, getFormatedDateString(7));

        System.out.println("充值是否成功：" + resultsModel.isSuccessful());
        System.out.println("充值日志：" + resultsModel.getTip());
    }

    /**
     * 发送Smart充值请求
     *
     * @param phone       手机号
     * @param topUpAmount 单位1美元，里面已经做了1分钱转1元的处理了
     * @param orderNum    需要确保唯一性，建议使用订单id
     */
    public static ResultsModel sentTopUp(String phone, int topUpAmount, String orderNum) {

        String tip = "";
        boolean topUpSuccess = false;

        try {
            //以0开头，去掉0
            if (phone.startsWith("0")) {
                phone = phone.substring(1);
            }

            String json = getToken();
            /**
             * {"access_token":"372b5f81-9662-3d75-abcf-639920880ce3","refresh_token":"d62d9da3-3730-35f7-9368-c82b43509db1","scope":"default","token_type":"Bearer","expires_in":3249}//
             */
            System.out.println(json);

            String tokenStr = "";
            //判断是否成功获取到token
            if (!TextUtils.isEmpty(json)) {
                JsonParser jsonParser = new JsonParser();
                JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
                tokenStr = jsonObject.get("access_token") == null ? "" : jsonObject.get("access_token").getAsString();
                if (!TextUtils.isEmpty(tokenStr)) {
                    access_token = tokenStr;
                    refresh_token = jsonObject.get("refresh_token").getAsString();
                    token_type = jsonObject.get("token_type").getAsString();
                    expires_in = jsonObject.get("expires_in").getAsInt();
                } else {
                    tip += " 返回结果：" + json;
                }
            } else {
                tip += " 返回值为空";
            }

            System.out.println(tip);

            String phoneJson = "";
            if (!TextUtils.isEmpty(tokenStr)) {
                //成功获取到token,可以进行校验手机号了
                phoneJson = checkPhone(phone);
                System.out.println(phoneJson);
            }

            String correlation_id = "";
//        String refJson = refreshToken("d62d9da3-3730-35f7-9368-c82b43509db1");
//        System.out.println(refJson);

            //手机号校验是否成功，如果成功，则直接发起充值
            if (!TextUtils.isEmpty(phoneJson)) {
                JsonParser jsonParser2 = new JsonParser();
                JsonObject jsonObject2 = jsonParser2.parse(phoneJson).getAsJsonObject();
                String eligible = jsonObject2.get("eligible") == null ? "" : jsonObject2.get("eligible").getAsString();

                if (eligible.equals("true")) {
                    //校验成功
                    tip += " 手机号码校验成功 ！！！";

                    String rechId = "LinkAsia:" + phone + ":" + orderNum;
                    int amount = topUpAmount * 100;//需要乘以100，文档写在至少100分美元，则1美元，以分为单位
                    String rechargeJson = rechargePhone(phone, String.valueOf(amount), rechId);//发起充值
                    System.out.println(rechargeJson);
                /*
                * {
                    "correlation_id": "58cam:87234159:100025",
                    "institution_id": "98198198",
                    "subscriber_id": "tel:+85587234159",
                    "amount": 100,
                    "channel": "WEB",
                    "instance_id": "0106142011016656"
                }
                * */
                    if (!TextUtils.isEmpty(rechargeJson)) {
                        JsonParser jsonParserRecharge = new JsonParser();
                        JsonObject jsonObjectRecharge = jsonParserRecharge.parse(rechargeJson).getAsJsonObject();
                        correlation_id = jsonObjectRecharge.get("correlation_id") == null ? "" : jsonObjectRecharge.get("correlation_id").getAsString();//不为空，则充值成功
                        tip += " 充值发起请求成功！！！";
                    } else {
                        tip += " 充值请求返回值为空；";
                    }

                } else {
                    //手机号码校验失败
                    tip += " 手机号码校验失败,返回值：" + phoneJson;
                }
            } else {
                tip += " 手机号码校验返回值为空；";
            }

            String jsonQuery = "";
            //如果充值成功，可以进行校验充值状态
            if (!TextUtils.isEmpty(correlation_id)) {
                //充值成功了
                topUpSuccess = true;
                tip += " 充值成功,发起复查；";

                jsonQuery = queryRechargePhone(correlation_id);//发起校验
                System.out.println(jsonQuery);

                //校验复查充值是否成功
                if (!TextUtils.isEmpty(jsonQuery)) {
                    JsonParser jsonQueryParser = new JsonParser();
                    JsonObject jsonObjectQuery = jsonQueryParser.parse(jsonQuery).getAsJsonObject();
                    String recharge_status = jsonObjectQuery.get("recharge_status") == null ? "" : jsonObjectQuery.get("recharge_status").getAsString();

                    if (recharge_status.equals("Succeeded")) {
                        System.out.println(" 复查充值成功！！");
                        tip += " 复查充值结果：成功。";
                    } else {
                        tip += " 复查充值结果：" + jsonQuery;
                    }
                } else {
                    tip += " 复查充值结果为空；";
                }
            }


            System.out.println(tip);

            ResultsModel resultsModel = new ResultsModel(topUpSuccess, tip);
            return resultsModel;

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


    /**
     * 此函数非原创，从网上搜索而来，timeZoneOffset原为int类型，为班加罗尔调整成float类型
     * timeZoneOffset表示时区，如中国一般使用东八区，因此timeZoneOffset就是8
     *
     * @param timeZoneOffset
     * @return
     */
    public static String getFormatedDateString(float timeZoneOffset) {
        if (timeZoneOffset > 13 || timeZoneOffset < -12) {
            timeZoneOffset = 0;
        }

        int newTime = (int) (timeZoneOffset * 60 * 60 * 1000);
        TimeZone timeZone;
        String[] ids = TimeZone.getAvailableIDs(newTime);
        if (ids.length == 0) {
            timeZone = TimeZone.getDefault();
        } else {
            timeZone = new SimpleTimeZone(newTime, ids[0]);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sdf.setTimeZone(timeZone);
        return sdf.format(new Date());
    }

}
