package com.reyun.service.impl;

import com.reyun.model.*;
import com.reyun.repository.*;
import com.reyun.service.AccountFlowRestrictService;
import com.reyun.task.EmailThread;
import com.reyun.util.Constant;
import com.reyun.util.DateUtil;
import com.reyun.util.HttpClientUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class AccountFlowRestrictServiceImpl implements AccountFlowRestrictService {
    @Autowired
    private AppRepository appRepository;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private PackageTypeRepository packageTypeRepository;

    @Autowired
    private IsNotifiedRepository isNotifiedRepository;

    @Autowired
    private SalesManLeaderRepository salesManLeaderRepository;

    @Autowired
    private AccountRestrict4WebRepository accountRestrict4WebRepository;

    @Autowired
    private ConfigParamRepository configParamRepository;


    private static final String SUPER_USER_EMAIL_NOTIFY_SUBJECT = "客户包年套餐到期提醒";
    private static final String SUPER_USER_IO_EMAIL_NOTIFY_CONTENT = "%s购买的“%s”中用户行为分析服务%s，请尽快跟进。";
    private static final String ALREADY_EXPIRE = "已经到期";


    @Override
    public AccountRestrict4Web findRestrictByAccount(Long accountId) {

        Long rootParent = accountRepository.findRootParentByAccountId(accountId).longValue();
        AccountRestrict4Web accountRestrict4Web = new AccountRestrict4Web();

        List<App> apps = appRepository.listAppByRootAccount(rootParent);
        Account rootAccount = accountRepository.findOne(rootParent);
        String companyOrEmail = rootAccount.getCompany() != null ? rootAccount.getCompany() : rootAccount.getEmail();
        IsNotified isNotifiedObject = isNotifiedRepository.findIsNotifiedByAccountId(rootParent);

        StringBuffer appsStr = new StringBuffer();
        for (App app : apps) {
            appsStr = appsStr.append("\'" + app.getAppkey() + "\'" + ",");
        }
        String appids = "";
        if (apps.size() != 0) {
            appids = appsStr.substring(0, appsStr.length() - 1);
        }

        PackageType packageType = packageTypeRepository.findPackageTypeByRootParent(rootParent);
        Boolean flowRestrict = rootAccount.getFlowRestrict();

        String pastDate = rootAccount.getPastDate();
        Date currentDate = DateUtil.getCurrentDate();
        String currentDateStr = DateUtil.getCurrentDateStr();
        int remainingDays = DateUtil.daysBetween(currentDate, DateUtil.parseDate(pastDate)) + 1;


        String salesManLeaderEmail = salesManLeaderRepository.findLeaderByBussinessMan(rootAccount.getBussinessman());

        String[] split={""};
        if(salesManLeaderEmail!=null ){
            split = salesManLeaderEmail.split(",");
        }
        ArrayList<String> emailList = new ArrayList<>();
        Collections.addAll(emailList, split);

        ArrayList<String> accountEmailList = new ArrayList<>();
        String operate_email = configParamRepository.findParamsByKey("operate_email");
        if(operate_email!=null){
            String[] split1 = operate_email.split(",");
            accountEmailList.addAll(Arrays.asList(split1));
        }
        if (Constant.flowneed.equals("true")) {
            accountEmailList.add(rootAccount.getEmail());
        }

        Date lastMonth = getLastMonth(1);
        String firstDayOfLastMonth = DateUtil.getFirstDayOfMonth(lastMonth);
        String lastDayOfLastMonth = DateUtil.getLastDayOfMonth(lastMonth);
        String firstDayOfThisMonth = DateUtil.getFirstDayOfMonth(new Date());


        DecimalFormat decimalFormat = new DecimalFormat("0%");
        String IOBeginTime = (isNotifiedObject != null && isNotifiedObject.getThisMonthUpgradeLevel() != null && isNotifiedObject.getThisMonthUpgradeLevel()) ? rootAccount.getModifyPricelevelTime() : firstDayOfThisMonth;

        BigInteger lastMonthEventNum=new BigInteger("0");
        BigInteger thisMonthEventNum=new BigInteger("0");
        BigInteger lastThreeDaysEventNum=new BigInteger("0");
        if(apps.size()>0){
        lastMonthEventNum = getTotalNum(firstDayOfLastMonth, lastDayOfLastMonth, appids, "account_io_flow_restrict", "event_sum");
        thisMonthEventNum = getTotalNum(IOBeginTime, currentDateStr, appids, "account_io_flow_restrict", "event_sum");
        lastThreeDaysEventNum = getTotalNum(IOBeginTime, currentDateStr, appids, "account_io_three_days_flow_restrict", "event_sum");
    }

        BigInteger lastMonthExceedNum = (lastMonthEventNum.subtract(packageType.getIoFlow()).compareTo(new BigInteger("0")) == 1) ? lastMonthEventNum.subtract(packageType.getIoFlow()) : new BigInteger("0");
        if (isNotifiedObject != null && isNotifiedObject.getThisMonthUpgradeLevel() != null && isNotifiedObject.getThisMonthUpgradeLevel()) {
            lastMonthExceedNum = new BigInteger("0");
        }
        double v = packageType.getIoFlow().doubleValue() * 1 - lastMonthExceedNum.doubleValue();
        DecimalFormat decimalFormat1 = new DecimalFormat("0");
        String format = decimalFormat1.format(v);
        BigInteger thisMonthAvailableTotalFlow = new BigInteger(format);
        BigInteger thisMonthRemainingFlow = thisMonthAvailableTotalFlow.subtract(thisMonthEventNum);
        int IORemainDays = -1;
        if (lastThreeDaysEventNum.compareTo(new BigInteger("1")) == 1) {
            IORemainDays = (int) (Math.floor(Double.valueOf(thisMonthRemainingFlow.divide(lastThreeDaysEventNum.divide(new BigInteger("3"))).toString())));
        }
        double ioRemainPercent = thisMonthRemainingFlow.doubleValue() / thisMonthAvailableTotalFlow.doubleValue();
        String ioRemainPercent1 = decimalFormat.format(ioRemainPercent);
        accountRestrict4Web.setPastDate(pastDate);
        accountRestrict4Web.setPackageName(packageType.getPackageName());
        accountRestrict4Web.setOriginalName(packageType.getOriginalName());
        accountRestrict4Web.setIOLimit(packageType.getIoFlow());
        accountRestrict4Web.setTrackLimit(packageType.getTrackFlow());
        accountRestrict4Web.setThisMonthIOFlow(thisMonthEventNum);
        accountRestrict4Web.setAccountId(rootParent);
        accountRestrict4Web.setPriceLevel(rootAccount.getPricelevel().intValue());
        accountRestrict4Web.setLastMonthIOFlow(lastMonthEventNum);
        accountRestrict4Web.setIORemainPercent(ioRemainPercent);
        accountRestrict4Web.setiOremainingDays(IORemainDays);
        accountRestrict4Web.setPackLevel(new Long(packageType.getId()));
        accountRestrict4Web.setFlowRestrict(flowRestrict);
        accountRestrict4Web.setSuperLevel(packageType.getSuperLevel());

        if (packageType.getSuperLevel()) {
            accountRestrict4Web.setPackageName("包年套餐");
        }

        if (rootParent.equals(accountId) && rootAccount.getFlowRestrict()) {
            /**
             * 判断用户有没有变更过套餐
             */
            if (isNotifiedObject != null && isNotifiedObject.getPreviousPackageLevel() != packageType.getId()) {
                isNotifiedRepository.deleteByAccountId(rootAccount.getId());
                IsNotified isNotified1 = new IsNotified();
                isNotified1.setAccountId(rootParent);
                isNotified1.setPreviousPackageLevel(packageType.getId());
                isNotified1.setThisMonthUpgradeLevel(true);
                isNotifiedRepository.save(isNotified1);
                isNotifiedObject = isNotifiedRepository.findIsNotifiedByAccountId(rootParent);
            }


            if (isNotifiedObject == null) {
                IsNotified isNotified1 = new IsNotified();
                isNotified1.setAccountId(rootParent);
                isNotified1.setPreviousPackageLevel(packageType.getId());
                isNotified1.setFirstDayOfThisMonth(firstDayOfThisMonth);
                isNotifiedRepository.save(isNotified1);
                isNotifiedObject = isNotifiedRepository.findIsNotifiedByAccountId(rootParent);
            } else if (isNotifiedObject != null && !packageType.getSuperLevel() && (DateUtil.compareDate(isNotifiedObject.getFirstDayOfThisMonth(), firstDayOfThisMonth) != 0)) {
                isNotifiedObject.setIoThirtyPercentNotified(false);
                isNotifiedObject.setIoTwentyPercentNotified(false);
                isNotifiedObject.setIoTenPercentNotified(false);
                isNotifiedObject.setIoFivePercentNotified(false);
                isNotifiedObject.setIoExhaustPercentNotified(false);
                isNotifiedObject.setThisMonthUpgradeLevel(false);

                isNotifiedRepository.save(isNotifiedObject);
                isNotifiedObject = isNotifiedRepository.findIsNotifiedByAccountId(rootParent);
            }


            if (isNotifiedObject != null && (DateUtil.compareDate(isNotifiedObject.getFirstDayOfThisMonth(), firstDayOfThisMonth) != 0)) {
                isNotifiedObject.setThisMonthUpgradeLevel(false);
                isNotifiedRepository.save(isNotifiedObject);
                isNotifiedObject = isNotifiedRepository.findIsNotifiedByAccountId(rootParent);
            }


            if (flowRestrict) {

                /**
                 * 是行为分析产品
                 */
                if (remainingDays > 1 && remainingDays <= 10 && (isNotifiedObject.getIoTenDaysNotified() == null || !isNotifiedObject.getIoTenDaysNotified())) {
                    isNotifiedObject.setIoTenDaysNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOPastTimeNotified(true);
                    String contents = String.format(SUPER_USER_IO_EMAIL_NOTIFY_CONTENT,
                            companyOrEmail, packageType.getPackageName(), "还有" + remainingDays + "天即将到期");
                    String accountContents = "您购买的用户行为分析" + packageType.getPackageName() + "将在"+remainingDays+"天后("+rootAccount.getPastDate()+")到期，为了不影响您的正常使用，请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收，但数据展示服务将暂时无法使用。";
                    try {
                        Thread emailThread = new EmailThread(SUPER_USER_EMAIL_NOTIFY_SUBJECT, contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoTenDaysNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOPastTimeNotified(false);
                        e.printStackTrace();
                    }
                } else if (remainingDays > 10 && remainingDays <= 30 && (isNotifiedObject.getIoOneMonthNotified() == null || !isNotifiedObject.getIoOneMonthNotified())) {
                    isNotifiedObject.setIoOneMonthNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOPastTimeNotified(true);
                    String contents = String.format(SUPER_USER_IO_EMAIL_NOTIFY_CONTENT, companyOrEmail, packageType.getPackageName(), "还有" + remainingDays + "天即将到期");
                    String accountContents = "您购买的用户行为分析" + packageType.getPackageName() + "将在"+remainingDays+"天后("+rootAccount.getPastDate()+")到期，为了不影响您的正常使用，请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收，但数据展示服务将暂时无法使用。";
                    try {
                        Thread emailThread = new EmailThread(SUPER_USER_EMAIL_NOTIFY_SUBJECT, contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoOneMonthNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOPastTimeNotified(false);
                        e.printStackTrace();
                    }
                } else if (remainingDays <= 0 && (isNotifiedObject.getIoExpireNotified() == null || !isNotifiedObject.getIoExpireNotified())) {
                    isNotifiedObject.setIoExpireNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOPastTimeNotified(true);
                    String contents = String.format(SUPER_USER_IO_EMAIL_NOTIFY_CONTENT, companyOrEmail, packageType.getPackageName(), ALREADY_EXPIRE);
                    try {
                        Thread emailThread = new EmailThread(SUPER_USER_EMAIL_NOTIFY_SUBJECT, contents, emailList);
                        emailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoExpireNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOPastTimeNotified(false);
                        e.printStackTrace();
                    }
                } else if (remainingDays == 1 && (isNotifiedObject.getIoOneDaysNotified() == null || !isNotifiedObject.getIoOneDaysNotified())) {
                    isNotifiedObject.setIoOneDaysNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOPastTimeNotified(true);
                    String contents = String.format(SUPER_USER_IO_EMAIL_NOTIFY_CONTENT, companyOrEmail, packageType.getPackageName(), "还有1天到期");
                    String accountContents = "您购买的用户行为分析" + packageType.getPackageName() + "将在明天到期，为了不影响您的正常使用，请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收，但数据展示服务将暂时无法使用。";
                    try {
                        Thread emailThread = new EmailThread(SUPER_USER_EMAIL_NOTIFY_SUBJECT, contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoOneDaysNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOPastTimeNotified(false);
                        e.printStackTrace();
                    }
                } else if (remainingDays > 30 && remainingDays <= 60 && (isNotifiedObject.getIoTwoMonthNotified() == null || !isNotifiedObject.getIoTwoMonthNotified())) {
                    isNotifiedObject.setIoTwoMonthNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOPastTimeNotified(true);
                    String contents = String.format(SUPER_USER_IO_EMAIL_NOTIFY_CONTENT, companyOrEmail, packageType.getPackageName(), "还有" + remainingDays + "天即将到期");
                    try {
                        Thread emailThread = new EmailThread(SUPER_USER_EMAIL_NOTIFY_SUBJECT, contents, emailList);
                        emailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoTwoMonthNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOPastTimeNotified(false);
                        e.printStackTrace();
                    }
                }
            }

            if (!packageType.getSuperLevel() && flowRestrict) {
                boolean thirtyToTwenty = (thisMonthAvailableTotalFlow.doubleValue() * 0.7 <= thisMonthEventNum.doubleValue()) && (thisMonthAvailableTotalFlow.doubleValue() * 0.8 > thisMonthEventNum.doubleValue());
                boolean twentyToTen = (thisMonthAvailableTotalFlow.doubleValue() * 0.8 <= thisMonthEventNum.doubleValue()) && (thisMonthAvailableTotalFlow.doubleValue() * 0.9 > thisMonthEventNum.doubleValue());
                boolean tenPercent = (thisMonthAvailableTotalFlow.doubleValue() * 0.9 <= thisMonthEventNum.doubleValue()) && (thisMonthAvailableTotalFlow.doubleValue() * 0.95 > thisMonthEventNum.doubleValue());
                boolean fivePercent = (thisMonthAvailableTotalFlow.doubleValue() * 0.95 <= thisMonthEventNum.doubleValue()) && (thisMonthAvailableTotalFlow.doubleValue() * 1 > thisMonthEventNum.doubleValue());
                boolean exPercent = thisMonthAvailableTotalFlow.doubleValue() * 1 <= thisMonthEventNum.doubleValue();
                if (thirtyToTwenty && (isNotifiedObject.getIoThirtyPercentNotified() == null || !isNotifiedObject.getIoThirtyPercentNotified())) {
                    isNotifiedObject.setIoThirtyPercentNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOFlowNotified(true);
                    String contents = companyOrEmail + "购买的" + packageType.getPackageName() + "用户行为分析当月剩余流量不足" + ioRemainPercent1 + "，请尽快跟进。";
                    String accountContents = "您订阅的用户行为分析" + packageType.getPackageName() + "中本月剩余流量已不足" + ioRemainPercent1 + "，请关注您的套餐流量使用情况。";
                    try {
                        Thread emailThread = new EmailThread("用户行为分析产品流量提醒", contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoThirtyPercentNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOFlowNotified(false);
                        e.printStackTrace();
                    }
                } else if (twentyToTen && (isNotifiedObject.getIoTwentyPercentNotified() == null || !isNotifiedObject.getIoTwentyPercentNotified())) {
                    isNotifiedObject.setIoTwentyPercentNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOFlowNotified(true);
                    String contents = companyOrEmail + "购买的" + packageType.getPackageName() + "用户行为分析当月剩余流量不足" + ioRemainPercent1 + "，请尽快跟进。";
                    String accountContents = "您订阅的用户行为分析" + packageType.getPackageName() + "中本月剩余流量已不足" + ioRemainPercent1 + "，请关注您的套餐流量使用情况。";
                    try {
                        Thread emailThread = new EmailThread("用户行为分析产品流量提醒", contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoTwentyPercentNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOFlowNotified(false);
                        e.printStackTrace();
                    }
                } else if (tenPercent && (isNotifiedObject.getIoTenPercentNotified() == null || !isNotifiedObject.getIoTenPercentNotified())) {
                    isNotifiedObject.setIoTenPercentNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOFlowNotified(true);
                    String contents = companyOrEmail + "购买的" + packageType.getPackageName() + "用户行为分析当月剩余流量不足" + ioRemainPercent1 + "，请尽快跟进。";
                    String accountContents = "您订阅的用户行为分析" + packageType.getPackageName() + "中本月剩余流量已不足" + ioRemainPercent1 + "，请关注您的套餐流量使用情况。";
                    try {
                        Thread emailThread = new EmailThread("用户行为分析产品流量提醒", contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoTenPercentNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOFlowNotified(false);
                        e.printStackTrace();
                    }
                } else if (fivePercent && (isNotifiedObject.getIoFivePercentNotified() == null || !isNotifiedObject.getIoFivePercentNotified())) {
                    isNotifiedObject.setIoFivePercentNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOFlowNotified(true);
                    String contents = companyOrEmail + "购买的" + packageType.getPackageName() + "用户行为分析当月剩余流量不足" + ioRemainPercent1 + "，请尽快跟进。";
                    String accountContents = "您订阅的用户行为分析" + packageType.getPackageName() + "中本月剩余流量已不足" + ioRemainPercent1 + "，请关注您的套餐流量使用情况。";
                    try {
                        Thread emailThread = new EmailThread("用户行为分析产品流量提醒", contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoFivePercentNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOFlowNotified(false);
                        e.printStackTrace();
                    }
                } else if (exPercent && (isNotifiedObject.getIoExhaustPercentNotified() == null || !isNotifiedObject.getIoExhaustPercentNotified())) {
                    isNotifiedObject.setIoExhaustPercentNotified(true);
                    isNotifiedRepository.save(isNotifiedObject);
                    accountRestrict4Web.setIOFlowNotified(true);
                    String contents = companyOrEmail + "购买的" + packageType.getPackageName() + "中用户行为分析当月流量已用尽，请尽快跟进。";
                    String accountContents = "您订阅的用户行为分析" + packageType.getPackageName() + "中本月事件数已经用完，本月超出部分将占用下周流量限额，最高使用量不超出5%。服务到期后我们将会继续支持您的数据上报和接收，但数据展示服务将暂时无法使用。请您预估下月的流量使用，如果产品统计需求增加，请联系商务升级您的套餐。";
                    try {
                        Thread emailThread = new EmailThread("用户行为分析产品流量提醒", contents, emailList);
                        emailThread.start();
                        Thread accountEmailThread = new EmailThread("热云数据用户行为分析套餐提醒",accountContents, accountEmailList);
                        accountEmailThread.start();
                    } catch (Exception e) {
                        isNotifiedObject.setIoExhaustPercentNotified(false);
                        isNotifiedRepository.save(isNotifiedObject);
                        accountRestrict4Web.setIOFlowNotified(false);
                        e.printStackTrace();
                    }
                }
            }

            isNotifiedObject.setFirstDayOfThisMonth(firstDayOfThisMonth);
            isNotifiedRepository.save(isNotifiedObject);
        }
        return accountRestrict4Web;
    }


    /**
     * 查询广告效果监控产品的点击量和行为分析产品的点击量的方法
     */
    @Override
    public BigInteger getTotalNum(String createTime, String pastDate, String appids, String reportName, String
            sumType) {
        Long appId = 1218L;
        Map<String, String> conditions = new HashMap<String, String>();
        conditions.put("appids", appids);
        conditions.put("startdate", createTime);
        conditions.put("enddate", pastDate);
        conditions.put("datatype", "list");
        conditions.put("iscache", Constant.iscache);
        String url = Constant.reportUrl + "/api/trackingio/" + reportName + "/" + appId;
        String responseJson = HttpClientUtil.doHttpPostRequest(url, "trackingio", conditions);
        HashMap<String, String> resultValMap = new HashMap<>();
        String click_sum = "";
        String s = "0";
        if(responseJson!=null) {
            try {
                JSONObject jsonObject = new JSONObject(responseJson);
                Iterator keys = jsonObject.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    String value = jsonObject.getString(key);
                    resultValMap.put(key, value);
                }
                String val = resultValMap.get("val");
                JSONArray jsonArray = new JSONArray(val);
                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                click_sum = jsonObject1.getString(sumType);
                if (StringUtils.isEmpty(click_sum) || "0".equals(click_sum)) {
                    click_sum = "0";
                }
                Double aDouble = Double.valueOf(click_sum);
                BigDecimal bigDecimal = new BigDecimal(aDouble);
                s = bigDecimal.toPlainString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return new BigInteger(s);
    }

    @Override
    public Boolean isIoExhaust(Long accountId) {
        Long rootParent = accountRepository.findRootParentByAccountId(accountId).longValue();
        List<App> apps = appRepository.listAppByRootAccount(rootParent);
        Boolean isBothExhaust = false;
        if (apps.size() != 0) {
            Account rootAccount = accountRepository.findOne(rootParent);
            StringBuffer appsStr = new StringBuffer();
            for (App app : apps) {
                appsStr = appsStr.append("\'" + app.getAppkey() + "\'" + ",");
            }
            String appids = appsStr.substring(0, appsStr.length() - 1);

            /**
             * 1.根据母帐号获取用户等级
             */
            PackageType packageType = packageTypeRepository.findPackageTypeByRootParent(rootParent);
            Boolean flowRestrict = rootAccount.getFlowRestrict();

            String currentDateStr = DateUtil.getCurrentDateStr();

            Date lastMonth = getLastMonth(1);
            String firstDayOfLastMonth = DateUtil.getFirstDayOfMonth(lastMonth);
            String lastDayOfLastMonth = DateUtil.getLastDayOfMonth(lastMonth);
            String firstDayOfThisMonth = DateUtil.getFirstDayOfMonth(new Date());

            IsNotified isNotifiedObject = isNotifiedRepository.findIsNotifiedByAccountId(rootParent);
            String IOBeginTime = (isNotifiedObject != null && isNotifiedObject.getThisMonthUpgradeLevel() != null && isNotifiedObject.getThisMonthUpgradeLevel()) ? rootAccount.getModifyPricelevelTime() : firstDayOfThisMonth;
            BigInteger lastMonthEventNum = getTotalNum(firstDayOfLastMonth, lastDayOfLastMonth, appids, "account_io_flow_restrict", "event_sum");
            BigInteger thisMonthEventNum = getTotalNum(IOBeginTime, currentDateStr, appids, "account_io_flow_restrict", "event_sum");
            BigInteger lastMonthExceedNum = (lastMonthEventNum.subtract(packageType.getIoFlow()).compareTo(new BigInteger("0")) == 1) ? lastMonthEventNum.subtract(packageType.getIoFlow()) : new BigInteger("0");
            if (isNotifiedObject != null && isNotifiedObject.getThisMonthUpgradeLevel() != null && isNotifiedObject.getThisMonthUpgradeLevel()) {
                lastMonthExceedNum = new BigInteger("0");
            }
            double v = packageType.getIoFlow().doubleValue() * 1 - lastMonthExceedNum.doubleValue();
            DecimalFormat decimalFormat1 = new DecimalFormat("0");
            String format = decimalFormat1.format(v);
            BigInteger thisMonthAvailableTotalFlow = new BigInteger(format);
            BigInteger thisMonthRemainingFlow = thisMonthAvailableTotalFlow.subtract(thisMonthEventNum);

            if (!packageType.getSuperLevel() && flowRestrict) {
                isBothExhaust = thisMonthRemainingFlow.doubleValue() < 0;
            }
        }
        return isBothExhaust;
    }


    @Override
    public AccountRestrict4Web RestrictFlowByAccountTask(Long accountId) {
        AccountRestrict4Web flowRestrict = findRestrictByAccount(accountId);
        AccountRestrict4Web byAccountId = accountRestrict4WebRepository.findByAccountId(flowRestrict.getAccountId());
        if(byAccountId!=null){
            Boolean ioFlowNotified = byAccountId.getIOFlowNotified()!=null?byAccountId.getIOFlowNotified():false;
            Boolean ioPastTimeNotified = byAccountId.getIOPastTimeNotified()!=null?byAccountId.getIOPastTimeNotified():false;
            Boolean trackFlowNotified = byAccountId.getTrackFlowNotified()!=null?byAccountId.getTrackFlowNotified():false;
            Boolean trackPastTimeNotified = byAccountId.getTrackPastTimeNotified()!=null?byAccountId.getTrackPastTimeNotified():false;
            accountRestrict4WebRepository.delete(byAccountId.getId());

            if(flowRestrict.getTrackPastTimeNotified()==null || !flowRestrict.getTrackPastTimeNotified()){
                flowRestrict.setTrackPastTimeNotified(trackPastTimeNotified);
            }

            if(flowRestrict.getIOPastTimeNotified()==null || !flowRestrict.getIOPastTimeNotified()){
                flowRestrict.setIOPastTimeNotified(ioPastTimeNotified);
            }

            if(flowRestrict.getTrackFlowNotified()==null || !flowRestrict.getTrackFlowNotified()){
                flowRestrict.setTrackFlowNotified(trackFlowNotified);
            }

            if(flowRestrict.getIOFlowNotified()==null || !flowRestrict.getIOFlowNotified()){
                flowRestrict.setIOFlowNotified(ioFlowNotified);
            }
            accountRestrict4WebRepository.save(flowRestrict);
        }else{
            accountRestrict4WebRepository.save(flowRestrict);
        }
        return flowRestrict;
    }


    public Date getLastMonth(int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -i);
        Date time = calendar.getTime();
        calendar.setTime(new Date());
        return time;
    }
}
