
package com.library.service.Impl;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.library.TopUp.Statel.SeatelSentUtils;
import com.library.TopUp.cellcard.CellcardSentUtils;
import com.library.TopUp.mefont.MetfoneSentUtils;
import com.library.config.NameValue;
import com.library.mapper.CommMapper;
import com.library.mapper.CurrencyMapper;
import com.library.respcode.ServerResponse;
import com.library.service.CommService;
import com.library.util.SendEmailTools;
import org.apache.http.util.TextUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

@Service
public class CommServiceImpl implements CommService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private CommMapper commMapper;
    @Resource
    private CurrencyMapper currencyMapper;

    public CommServiceImpl() {
    }

    @Override
    public ServerResponse Recharge() {
        try {
            return ServerResponse.createByErrorCodeMessage(-1, "无此接口");
        } catch (Exception var2) {
            var2.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    public ServerResponse adminLogin() {
        return ServerResponse.createByErrorCodeMessage(-1, "无此接口");
    }

    @Override
    public ServerResponse checkPhoneInSeatel() {
        String phone = this.request.getParameter("phone");
        String json = SeatelSentUtils.checkPhone2(phone);
        return ServerResponse.createBySuccess(json);
    }

    @Override
    public ServerResponse queryAgentFeeInSeatel() {
        String feeJson = SeatelSentUtils.queryAgentFee();
        String tip = "";
        String myAmount = "";
        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) {
                    myAmount = jsonObjectFee.get("amount").getAsString();
                    tip = tip + "您当前的余额为：$" + myAmount + "";
                    this.changeTheAmountLog(myAmount, "", "", "", "");
                } else {
                    tip = tip + "获取不到余额信息";
                }
            } else {
                tip = tip + "查询余额失败；结果为：" + feeJson;
            }
        }

        System.out.println(tip);
        return ServerResponse.createBySuccess(tip, myAmount);
    }

    @Override
    public ServerResponse queryAgentFeeInCellcard() {
        String feeJson = "";

        try {
            feeJson = CellcardSentUtils.checkBalance();
            String tip = "";
            String myAmount = "";
            if (!TextUtils.isEmpty(feeJson)) {
                JsonParser jsonParserFee = new JsonParser();
                JsonObject jsonObjectFee = jsonParserFee.parse(feeJson).getAsJsonObject();
                if (jsonObjectFee.get("data") != null) {
                    JsonObject data = jsonObjectFee.get("data").getAsJsonObject();
                    String error_message = data.get("error_message") == null ? "" : data.get("error_message").getAsString();
                    String error_code = data.get("error_code") == null ? "" : data.get("error_code").getAsString();
                    if (!TextUtils.isEmpty(error_code) && error_code.equals("0")) {
                        if (data.get("distributor_balance") != null) {
                            myAmount = data.get("distributor_balance").getAsString();
                            tip = tip + "您当前的余额为：$" + myAmount + "";
                            this.changeTheAmountLog("", "", myAmount, "", "");
                            return ServerResponse.createBySuccess(tip, myAmount);
                        }

                        tip = tip + "获取不到余额信息;" + error_message;
                    } else {
                        tip = tip + "查询余额失败；结果为：" + feeJson;
                    }
                } else {
                    tip = tip + "解析data为空";
                }
            } else {
                tip = tip + "请求的数据为空";
            }

            System.out.println(tip);
            return ServerResponse.createByErrorCodeMessage(3001, tip);
        } catch (Exception var9) {
            var9.printStackTrace();
            return ServerResponse.createByErrorCodeMessage(-1, feeJson);
        }
    }

    @Override
    public ServerResponse checkMyMoneyInMetfone() {
        String feeJson = "";

        try {
            String refId = getFormatedDateString(7.0F);
            String phone = "855886402606";
            feeJson = MetfoneSentUtils.checkMyMoneyPost(refId, phone);
            String tip = "";
            JsonObject data = null;
            if (!TextUtils.isEmpty(feeJson)) {
                JsonParser jsonParserFee = new JsonParser();
                JsonObject jsonObjectFee = jsonParserFee.parse(feeJson).getAsJsonObject();
                String status = jsonObjectFee.get("status") == null ? "" : jsonObjectFee.get("status").getAsString();
                if (status.equals("0")) {
                    String usd;
                    if (jsonObjectFee.get("balances") != null) {
                        data = jsonObjectFee.get("balances").getAsJsonObject();
                        if (data != null && data.get("USD") != null) {
                            usd = data.get("USD").getAsString();
                            this.changeTheAmountLog("", usd, "", "", "");
                        }

                        return ServerResponse.createBySuccess(data);
                    }

                    usd = jsonObjectFee.get("message") == null ? "" : jsonObjectFee.get("message").getAsString();
                    tip = tip + "" + usd;
                } else {
                    tip = tip + "请求的数据为空";
                }
            } else {
                tip = tip + "请求的数据为空";
            }

            return ServerResponse.createByErrorCodeMessage(3001, tip);
        } catch (Exception var10) {
            var10.printStackTrace();
            return ServerResponse.createByErrorCodeMessage(-1, feeJson);
        }
    }

    @Override
    public ServerResponse checkMyMoney() {
        try {
            Map<String, Object> map = this.currencyMapper.FindDataById(NameValue.Table_pay_operator_balance, 1);
            return ServerResponse.createBySuccess(map);
        } catch (Exception var2) {
            var2.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    @Override

    public ServerResponse saveTheEmail() {
        try {
            String email = this.request.getParameter("email");
            email = URLDecoder.decode(email, "UTF-8");
            System.out.println(email);
            Map<String, Object> mapUpdate = new HashMap();
            mapUpdate.put("email", email);
            int rest = this.commMapper.updateTheBalance(mapUpdate);
            return ServerResponse.createBySuccess(rest);
        } catch (Exception var4) {
            var4.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    private void changeTheAmountLog(String statel, String mefont, String cellcard, String smart, String remark) {
        try {
            Map<String, Object> map = new HashMap();
            if (!TextUtils.isEmpty(statel)) {
                map.put("statel", statel);
                this.sentMail(statel, "statel");
            }

            if (!TextUtils.isEmpty(mefont)) {
                map.put("mefont", mefont);
                this.sentMail(mefont, "mefont");
            }

            if (!TextUtils.isEmpty(cellcard)) {
                map.put("cellcard", cellcard);
                this.sentMail(cellcard, "cellcard");
            }

            if (!TextUtils.isEmpty(smart)) {
                map.put("smart", smart);
                this.sentMail(smart, "smart");
            }

            if (!TextUtils.isEmpty(remark)) {
                map.put("remark", remark);
            }

            this.commMapper.updateTheBalance(map);
        } catch (Exception var7) {
            var7.printStackTrace();
        }

    }

    private void sentMail(String money, String operation) {
        try {
            Map<String, Object> map = this.currencyMapper.FindDataById(NameValue.Table_pay_operator_balance, 1);
            String email = map.get("email") == null ? "" : map.get("email").toString();
            String lackbalance = map.get("lackbalance") == null ? "" : map.get("lackbalance").toString();
            if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(lackbalance)) {
                if (money.indexOf(",") != -1) {
                    money = money.replace(",", "");
                }

                if ((new BigDecimal(money)).compareTo(new BigDecimal(lackbalance)) < 0) {
                    String[] els = email.split(",");

                    for (int i = 0; i < els.length; ++i) {
                        SendEmailTools.SendMail("充值系统-余额不足" + lackbalance + "美元", operation + "运营商当前剩余余额：" + money, els[i]);
                    }
                }
            }
        } catch (Exception var8) {
            var8.printStackTrace();
        }

    }

    /**
     * 此函数非原创，从网上搜索而来，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("yyyyMMddHHmmss");
        sdf.setTimeZone((TimeZone) timeZone);
        return sdf.format(new Date());
    }
}
