package com.library.TopUp.Statel;

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 com.library.respcode.ServerResponse;
import com.wechat.pay.MD5Util;
import org.apache.http.util.TextUtils;

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

public class SeatelSentUtils {


    public final static String url = "http://172.22.188.20:11999/SeatelPayment/pay.jsp";//测试
//   public final static String url = "http://172.22.188.20:11800/SeatelPayment/pay.jsp";//生产

    private final static String shopid = "shoptest";
    private final static String private_key = "9834a62b4ec7c78a5424932bfdedfd74";
    private final static String terminalid = "shoptest0001";

    /**
     * 检查手机是否能充值
     *
     * @param phone
     * @return
     */
    public static String checkPhone(String phone) {

        try {

            String time = getFormatedDateString(7);

            String cmd = "queryphonenumberstatus";
            String terminaltrace = "shoptest186" + new Random().nextInt(10000);

            Map params = new HashMap();
            params.put("cmd", cmd);
            params.put("shopid", shopid);
            params.put("terminalid", terminalid);
            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");


//            HttpClientResult clientResult = HttpClientUtils.doGet(url, heardMap, params);
            String json = HttpClientUtils.postWithJson(new Gson().toJson(params), url, heardMap);

            return json;

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

    /**
     * 检查手机是否能充值
     *
     * @return
     */
    public static String checkPhone2(String phone) {

        try {


            String time = getFormatedDateString(7);

            String cmd = "queryphonenumberstatus";
            String terminaltrace = UUID.randomUUID().toString().replace("-", "");
//            String terminaltrace = generateKey()+new Random().nextInt(10000);;


            Map params = new HashMap();
            params.put("cmd", cmd);
            params.put("shopid", shopid);
            params.put("terminalid", terminalid);
            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\":" + "\"" + shopid + "\"" + "," +
                    "\"terminalid\":" + "\"" + terminalid + "\"" + "," +
                    "\"terminaltrace\":" + "\"" + terminaltrace + "\"" + "," +
                    "\"transtime\":" + "\"" + time + "\"" + "," +
                    "\"phone\":" + "\"" + phone + "\"" + "," +
                    "\"signtype\":" + "\"" + "MD5" + "\"" + "," +
                    "\"sign\":" + "\"" + sign + "\"" + "," +
                    "}";
            String json = HttpClientUtils.postWithJson(strJson, url, heardMap);
            return json;

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

    /**
     * 查询账户余额，是否能充值
     *
     * @return
     */
    public static String queryAgentFee() {

        try {

            String time = getFormatedDateString(7);

            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\":" + "\"" + shopid + "\"" + "," +
                    "\"terminalid\":" + "\"" + terminalid + "\"" + "," +
                    "\"terminaltrace\":" + "\"" + terminaltrace + "\"" + "," +
                    "\"transtime\":" + "\"" + time + "\"" + "," +
                    "\"signtype\":" + "\"" + "MD5" + "\"" + "," +
                    "\"sign\":" + "\"" + sign + "\"" + "," +
                    "}";
            String json = HttpClientUtils.postWithJson(strJson, url, heardMap);
            return json;

        } catch (Exception e) {
            e.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);

            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\":" + "\"" + shopid + "\"" + "," +
                    "\"terminalid\":" + "\"" + terminalid + "\"" + "," +
                    "\"terminaltrace\":" + "\"" + terminaltrace + "\"" + "," +
                    "\"transtime\":" + "\"" + time + "\"" + "," +
                    "\"phone\":" + "\"" + phone + "\"" + "," +
                    "\"amount\":" + "" + amountStr + "" + "," +
                    "\"signtype\":" + "\"" + "MD5" + "\"" + "," +
                    "\"sign\":" + "\"" + sign + "\"" + "," +
                    "}";
            String json = HttpClientUtils.postWithJson(strJson, url, heardMap);
            return json;

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

    /**
     * 查询充值结果
     *
     * @param systemtrace
     * @return
     */
    public static String queryCrmRecharge(String systemtrace) {

        try {


            String time = getFormatedDateString(7);

            String cmd = "querycrmrecharge";
            String terminaltrace = "shoptest183" + new Random().nextInt(10000);

//            String sign = getSignStr(cmd, terminaltrace, time, "");
            String str = cmd + shopid + terminalid + terminaltrace + time + systemtrace + "" + private_key;

            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\":" + "\"" + shopid + "\"" + "," +
                    "\"terminalid\":" + "\"" + terminalid + "\"" + "," +
                    "\"terminaltrace\":" + "\"" + terminaltrace + "\"" + "," +
                    "\"transtime\":" + "\"" + time + "\"" + "," +
                    "\"systemtrace\":" + "\"" + systemtrace + "\"" + "," +
                    "\"signtype\":" + "\"" + "MD5" + "\"" + "," +
                    "\"sign\":" + "\"" + sign + "\"" + "," +
                    "}";
            String json = HttpClientUtils.postWithJson(strJson, url, heardMap);
            return json;

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

    private static String getSignStr(String cmd, String terminaltrace, String transtime, String phone) {

        String str = cmd + "" + shopid + terminalid + terminaltrace + transtime + phone + private_key;
        String md5Text = MD5Util.MD5Encode(str, "");
        return md5Text;
    }

    private static String getSignInTopUp(String cmd, String terminaltrace, String transtime, String phone, String amount) {

        String str = cmd + "" + shopid + terminalid + terminaltrace + transtime + phone + amount + private_key;
        String md5Text = MD5Util.MD5Encode(str, "");
        return md5Text;
    }


    public static void main(String[] args) {
        String phone = "0189464112";

        String json = checkPhone(phone);
        System.out.println(json);
//        ResultsModel resultsModel = sentTopUp(phone, 1, "99999912");
//
//        System.out.println("充值是否成功：" + resultsModel.isSuccessful());
//        System.out.println("充值日志：" + resultsModel.getTip());
    }

    /**
     * 发送充值请求
     *
     * @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);
            if (!TextUtils.isEmpty(checkJson)) {
                JsonParser jsonParserCheck = new JsonParser();
                JsonObject jsonObjectCheck = jsonParserCheck.parse(checkJson).getAsJsonObject();
                String codeCheck = jsonObjectCheck.get("code") == null ? "" : jsonObjectCheck.get("code").getAsString();

                if (!TextUtils.isEmpty(codeCheck) && codeCheck.equals("0")) {
                    //号码校验成功，发起查询余额
                    feeJson = queryAgentFee();
                } else {
                    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 += "余额不足，请充值";
                        }
                    } else {
                        tip += "获取不到余额信息";
                    }
                } else {
                    tip += "查询余额失败；结果为：" + feeJson;
                }
            }

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

                JsonParser jsonParserRecharge = new JsonParser();
                JsonObject jsonObjectRecharge = jsonParserRecharge.parse(rechargeJson).getAsJsonObject();
                String codeCheck = jsonObjectRecharge.get("code") == null ? "" : jsonObjectRecharge.get("code").getAsString();
                if (!TextUtils.isEmpty(codeCheck) && codeCheck.equals("0")) {
                    //充值成功
                    tip += "充值成功!!! 发起复查；";
//                    topUpSuccess = true;//复查成功，再更改
                    systemtrace = jsonObjectRecharge.get("systemtrace") == null ? "" : jsonObjectRecharge.get("systemtrace").getAsString();
                    queryResultJson = queryCrmRecharge(systemtrace);

                } else {
                    tip += "充值失败，返回结果：" + rechargeJson;
                }
            }

            if (!TextUtils.isEmpty(queryResultJson)) {
                JsonParser jsonParserResult = new JsonParser();
                JsonObject jsonObjectResult = jsonParserResult.parse(queryResultJson).getAsJsonObject();
                String 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 += "检查结果，充值成功。";
                    } else {
                        tip += "检查结果，充值失败。";
                    }
                } else {
                    tip += "请求复查错误，解析如下：" + queryResultJson;
                }
            }


            ResultsModel resultsModel = new ResultsModel(topUpSuccess, tip, systemtrace);
            resultsModel.setTopUpNum(systemtrace);
            return resultsModel;

        } catch (Exception e) {
            e.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 || 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("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(timeZone);
        return sdf.format(new Date());
    }

}
