

package com.library.TopUp.Statel;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.library.TopUp.model.ResultsModel;
import com.wechat.pay.MD5Util;
import org.apache.http.util.TextUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.UUID;

public class SeatelSentUtils {
    public static final String url = "http://172.22.188.20:11800/SeatelPayment/pay.jsp";
    private static final String shopid = "linkasia";
    private static final String private_key = "a562065907364aacedb102375a01fb39";
    private static final String terminalid = "linkasia001";

    public SeatelSentUtils() {
    }


    /**
     * 检查手机是否能充值
     *
     * @param phone
     * @return
     */
    public static String checkPhone(String phone) {
        try {
            String time = getFormatedDateString(7.0F);
            String cmd = "queryphonenumberstatus";
            String terminaltrace = "linkasia1" + (new Random()).nextInt(10000);
            Map params = new HashMap();
            params.put("cmd", cmd);
            params.put("shopid", "linkasia");
            params.put("terminalid", "linkasia001");
            params.put("terminaltrace", terminaltrace);
            params.put("transtime", time);
            params.put("phone", phone);
            params.put("signtype", "MD5");
            String sign = getSignStr(cmd, terminaltrace, time, phone);
            params.put("sign", sign);
            Map<String, String> heardMap = new HashMap();
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");
            String json = HttpClientUtils.postWithJson((new Gson()).toJson(params), "http://172.22.188.20:11800/SeatelPayment/pay.jsp", heardMap);
            return json;
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
    }

    /**
     * 检查手机是否能充值
     *
     * @return
     */
    public static String checkPhone2(String phone) {
        try {
            String time = getFormatedDateString(7.0F);
            String cmd = "queryphonenumberstatus";
            String terminaltrace = UUID.randomUUID().toString().replace("-", "");
            Map params = new HashMap();
            params.put("cmd", cmd);
            params.put("shopid", "linkasia");
            params.put("terminalid", "linkasia001");
            params.put("terminaltrace", terminaltrace);
            params.put("transtime", time);
            params.put("phone", phone);
            params.put("signtype", "MD5");
            String sign = getSignStr(cmd, terminaltrace, time, phone);
            params.put("sign", sign);
            Map<String, String> heardMap = new HashMap();
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");
            String strJson = "{\"cmd\":\"" + cmd + "\",\"shopid\":\"" + "linkasia" + "\",\"terminalid\":\"" + "linkasia001" + "\",\"terminaltrace\":\"" + terminaltrace + "\",\"transtime\":\"" + time + "\",\"phone\":\"" + phone + "\",\"signtype\":\"MD5\",\"sign\":\"" + sign + "\",}";
            String json = HttpClientUtils.postWithJson(strJson, "http://172.22.188.20:11800/SeatelPayment/pay.jsp", heardMap);
            return json;
        } catch (Exception var9) {
            var9.printStackTrace();
            return null;
        }
    }

    /**
     * 查询账户余额，是否能充值
     *
     * @return
     */
    public static String queryAgentFee() {
        try {
            String time = getFormatedDateString(7.0F);
            String cmd = "queryagentfee";
            String terminaltrace = "shoptest183" + (new Random()).nextInt(10000);
            String sign = getSignStr(cmd, terminaltrace, time, "");
            Map<String, String> heardMap = new HashMap();
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");
            String strJson = "{\"cmd\":\"" + cmd + "\",\"shopid\":\"" + "linkasia" + "\",\"terminalid\":\"" + "linkasia001" + "\",\"terminaltrace\":\"" + terminaltrace + "\",\"transtime\":\"" + time + "\",\"signtype\":\"MD5\",\"sign\":\"" + sign + "\",}";
            String json = HttpClientUtils.postWithJson(strJson, "http://172.22.188.20:11800/SeatelPayment/pay.jsp", heardMap);
            return json;
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }

    /**
     * 发起充值
     *
     * @param phone  手机号码
     * @param amount 充值金额,单位1美元 里面做了分转元的处理
     * @return
     */
    public static String crmRecharge(String phone, int amount) {
        try {
            String amountStr = String.valueOf(amount * 100);
            String time = getFormatedDateString(7.0F);
            String cmd = "crmrecharge";
            String terminaltrace = "shoptest183" + (new Random()).nextInt(10000);
            String sign = getSignInTopUp(cmd, terminaltrace, time, phone, amountStr);
            Map<String, String> heardMap = new HashMap();
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");
            String strJson = "{\"cmd\":\"" + cmd + "\",\"shopid\":\"" + "linkasia" + "\",\"terminalid\":\"" + "linkasia001" + "\",\"terminaltrace\":\"" + terminaltrace + "\",\"transtime\":\"" + time + "\",\"phone\":\"" + phone + "\",\"amount\":" + amountStr + ",\"signtype\":\"MD5\",\"sign\":\"" + sign + "\",}";
            String json = HttpClientUtils.postWithJson(strJson, "http://172.22.188.20:11800/SeatelPayment/pay.jsp", heardMap);
            return json;
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
    }

    /**
     * 查询充值结果
     *
     * @param systemtrace
     * @return
     */
    public static String queryCrmRecharge(String systemtrace) {
        try {
            String time = getFormatedDateString(7.0F);
            String cmd = "querycrmrecharge";
            String terminaltrace = "shoptest183" + (new Random()).nextInt(10000);
            String str = cmd + "linkasia" + "linkasia001" + terminaltrace + time + systemtrace + "" + "a562065907364aacedb102375a01fb39";
            String sign = MD5Util.MD5Encode(str, "");
            Map<String, String> heardMap = new HashMap();
            heardMap.put("Content-Type", "application/json");
            heardMap.put("Accept", "application/json");
            String strJson = "{\"cmd\":\"" + cmd + "\",\"shopid\":\"" + "linkasia" + "\",\"terminalid\":\"" + "linkasia001" + "\",\"terminaltrace\":\"" + terminaltrace + "\",\"transtime\":\"" + time + "\",\"systemtrace\":\"" + systemtrace + "\",\"signtype\":\"MD5\",\"sign\":\"" + sign + "\",}";
            String json = HttpClientUtils.postWithJson(strJson, "http://172.22.188.20:11800/SeatelPayment/pay.jsp", heardMap);
            return json;
        } catch (Exception var9) {
            var9.printStackTrace();
            return null;
        }
    }

    private static String getSignStr(String cmd, String terminaltrace, String transtime, String phone) {
        String str = cmd + "" + "linkasia" + "linkasia001" + terminaltrace + transtime + phone + "a562065907364aacedb102375a01fb39";
        String md5Text = MD5Util.MD5Encode(str, "");
        return md5Text;
    }

    private static String getSignInTopUp(String cmd, String terminaltrace, String transtime, String phone, String amount) {
        String str = cmd + "" + "linkasia" + "linkasia001" + terminaltrace + transtime + phone + amount + "a562065907364aacedb102375a01fb39";
        String md5Text = MD5Util.MD5Encode(str, "");
        return md5Text;
    }

    public static void main(String[] args) {
        String phone = "0189464112";
        String json = queryAgentFee();
        System.out.println(json);
    }

    /**
     * 发送充值请求
     *
     * @param phone       手机号
     * @param topUpAmount 单位1美元，里面已经做了1分钱转1元的处理了
     *
     */
    public static ResultsModel sentTopUp(String phone, int topUpAmount) {
        String tip = "";
        boolean topUpSuccess = false;

        try {
            String feeJson = "";
            String checkJson = checkPhone2(phone);
            String systemtrace;
            if (!TextUtils.isEmpty(checkJson)) {
                JsonParser jsonParserCheck = new JsonParser();
                JsonObject jsonObjectCheck = jsonParserCheck.parse(checkJson).getAsJsonObject();
                systemtrace = jsonObjectCheck.get("code") == null ? "" : jsonObjectCheck.get("code").getAsString();
                if (!TextUtils.isEmpty(systemtrace) && systemtrace.equals("0")) {

                    //号码校验成功，发起查询余额
                    feeJson = queryAgentFee();
                } else {
                    tip = tip + "校验号码失败；结果为：" + checkJson;
                }
            }

            String rechargeJson = "";
            if (!TextUtils.isEmpty(feeJson)) {
                JsonParser jsonParserFee = new JsonParser();
                JsonObject jsonObjectFee = jsonParserFee.parse(feeJson).getAsJsonObject();
                String codeCheck = jsonObjectFee.get("code") == null ? "" : jsonObjectFee.get("code").getAsString();
                if (!TextUtils.isEmpty(codeCheck) && codeCheck.equals("0")) {
                    //接口查询成功，比较金额大小
                    if (jsonObjectFee.get("amount") != null) {
                        BigDecimal myAmount = jsonObjectFee.get("amount").getAsBigDecimal();
                        if (myAmount.compareTo(new BigDecimal(topUpAmount)) >= 0) {

                            //余额充足
                            rechargeJson = crmRecharge(phone, topUpAmount);
                        } else {
                            //余额不足

                            tip = tip + "余额不足，请充值";
                        }
                    } else {
                        tip = tip + "获取不到余额信息";
                    }
                } else {
                    tip = tip + "查询余额失败；结果为：" + feeJson;
                }
            }

            String queryResultJson = "";
            systemtrace = "";
            String codeCheck;
            JsonParser jsonParserResult;
            JsonObject jsonObjectResult;
            if (!TextUtils.isEmpty(rechargeJson)) {
                //充值请求成功

                jsonParserResult = new JsonParser();
                jsonObjectResult = jsonParserResult.parse(rechargeJson).getAsJsonObject();
                codeCheck = jsonObjectResult.get("code") == null ? "" : jsonObjectResult.get("code").getAsString();
                if (!TextUtils.isEmpty(codeCheck) && codeCheck.equals("0")) {

                    //充值成功

                    tip = tip + "充值成功!!! 发起复查；";
                    systemtrace = jsonObjectResult.get("systemtrace") == null ? "" : jsonObjectResult.get("systemtrace").getAsString();
                    queryResultJson = queryCrmRecharge(systemtrace);
                } else {
                    tip = tip + "充值失败，返回结果：" + rechargeJson;
                }
            }

            if (!TextUtils.isEmpty(queryResultJson)) {
                jsonParserResult = new JsonParser();
                jsonObjectResult = jsonParserResult.parse(queryResultJson).getAsJsonObject();
                codeCheck = jsonObjectResult.get("code") == null ? "" : jsonObjectResult.get("code").getAsString();
                if (!TextUtils.isEmpty(codeCheck) && codeCheck.equals("0")) {
                    String crmstatus = jsonObjectResult.get("crmstatus") == null ? "" : jsonObjectResult.get("crmstatus").getAsString();
                    if (crmstatus.equals("successed")) {
                        //检查结果，充值成功

                        topUpSuccess = true;
                        tip = tip + "检查结果，充值成功。";
                    } else {
                        tip = tip + "检查结果，充值失败。";
                    }
                } else {
                    tip = tip + "请求复查错误，解析如下：" + queryResultJson;
                }
            }

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

    public static String generateKey() {
        String key = UUID.randomUUID().toString();
        // 替换掉-号
        key = key.replace("-", "").substring(0, 16);
        return key;
    }


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

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

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone((TimeZone) timeZone);
        return sdf.format(new Date());
    }
}
