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.AutomaticCodeService;
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;

    @Resource
    private AutomaticCodeService automaticCodeService;

    /**
     * 此函数非原创，从网上搜索而来，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());
    }

    @Override
    public ServerResponse Recharge() {
        try {

            return ServerResponse.createByErrorCodeMessage(-1, "无此接口");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    @Override
    public ServerResponse adminLogin() {

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

    @Override
    public ServerResponse checkPhoneInSeatel() {
        String phone = 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 += "您当前的余额为：$" + myAmount + "";

//                    if (!TextUtils.isEmpty(myAmount)) {
//                        Map<String, Object> map = new HashMap<>();
//                        map.put("statel", myAmount);
//                        commMapper.updateTheBalance(map);
//                    }
                    changeTheAmountLog(myAmount, "", "", "", "");
                } else {
                    tip += "获取不到余额信息";
                }
            } else {
                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 += "您当前的余额为：$" + myAmount + "";

//                            if (!TextUtils.isEmpty(myAmount)) {
//                                Map<String, Object> map = new HashMap<>();
//                                map.put("cellcard", myAmount);
//                                commMapper.updateTheBalance(map);
//                            }

                            changeTheAmountLog("", "", myAmount, "", "");

                            return ServerResponse.createBySuccess(tip, myAmount);
                        } else {
                            tip += "获取不到余额信息;" + error_message;
                        }
                    } else {
                        tip += "查询余额失败；结果为：" + feeJson;
                    }
                } else {
                    tip += "解析data为空";
                }

            } else {
                tip += "请求的数据为空";
            }
            System.out.println(tip);
            return ServerResponse.createByErrorCodeMessage(3001, tip);


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

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

            String refId = getFormatedDateString(7);
            String phone = request.getParameter("phone");

//            {"status":0,"code":"MSG_SUCCESS","message":"Success","msisdn":null,"accountName":null,"accountType":null,"balances":{"KHR":"498,983","USD":"4,748.00"}}
            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")) {
                    if (jsonObjectFee.get("balances") != null) {
                        data = jsonObjectFee.get("balances").getAsJsonObject();
                        return ServerResponse.createBySuccess(data);
                    } else {
                        String message = jsonObjectFee.get("message") == null ? "" : jsonObjectFee.get("message").getAsString();
                        tip += "" + message;
                    }
                } else {
                    tip += "请求的数据为空";
                }

            } else {
                tip += "请求的数据为空";
            }
            return ServerResponse.createByErrorCodeMessage(3001, tip);

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

    @Override
    public ServerResponse checkMyMoney() {

        try {

            Map<String, Object> map = currencyMapper.FindDataById(NameValue.Table_pay_operator_balance, 1);
            return ServerResponse.createBySuccess(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    @Override
    public ServerResponse saveTheEmail() {
        try {
            String email = 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 = commMapper.updateTheBalance(mapUpdate);

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

                sentMail(statel, "statel");

            }
            if (!TextUtils.isEmpty(mefont)) {
                map.put("mefont", mefont);
                sentMail(mefont, "mefont");
            }
            if (!TextUtils.isEmpty(cellcard)) {
                map.put("cellcard", cellcard);
                sentMail(cellcard, "cellcard");
            }
            if (!TextUtils.isEmpty(smart)) {
                map.put("smart", smart);
                sentMail(smart, "smart");
            }
            if (!TextUtils.isEmpty(remark)) {
                map.put("remark", remark);
            }
            commMapper.updateTheBalance(map);

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

    private void sentMail(String money, String operation) {

        try {

            Map<String, Object> map = 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 (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 e) {
            e.printStackTrace();
        }
    }

}
