AccountFlowRestrictServiceImpl.java 50.4 KB
Newer Older
shenggui.li committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
package com.reyun.service.impl;

import com.reyun.dic.LanguageTypeEnum;
import com.reyun.model.*;
import com.reyun.repository.*;
import com.reyun.service.AccountFlowRestrictService;
import com.reyun.service.TipService;
import com.reyun.util.*;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by song on 2017/10/19.
 */
@Service
public class AccountFlowRestrictServiceImpl implements AccountFlowRestrictService {
	private static org.slf4j.Logger logger = LoggerFactory.getLogger(AccountFlowRestrictService.class);
	@Autowired
	private AppRepository appRepository;

	@Autowired
	private AccountRepository accountRepository;

	@Autowired
	private PackageTypeRepository packageTypeRepository;

	@Autowired
	private IsNotifiedRepository isNotifiedRepository;

	@Autowired
	private BussinessManRepository bussinessManRepository;

	@Autowired
	private AccountRestrict4WebRepository accountRestrict4WebRepository;

	@Autowired
	private Restrict4NewContractRepository restrict4NewContractRepository;

	@Autowired
	private ConfigParamRepository configParamRepository;

	@Autowired
	private IncrementFlowRepository incrementFlowRepository;

	@Autowired
	private RestrictFlowsLogRepository restrictFlowsLogRepository;


	@Autowired
	private TipService tipService;

	@Autowired
	private PackageFlowRepository packageFlowRepository;

	@Autowired
	private PackageFlowService packageFlowService;

	@PersistenceContext
	private EntityManager entityManager;

	private static final String SUPER_USER_EMAIL_NOTIFY_SUBJECT = "客户包年套餐到期提醒";
	private static final String ENG_SUPER_USER_EMAIL_NOTIFY_SUBJECT = "Expiration reminder for the yearly package";

	@Override
	public AccountRestrict4Web findRestrictByAccount(Long accountId, String lanType) {

		if (lanType == null) {
			lanType = LanguageTypeEnum.CHINESE.getCode();
		}

		AccountRestrict4Web accountRestrict4Web = this.getRestrictData(accountId, null);
		Account rootAccount = accountRestrict4Web.getRootAccoount();
		Boolean flowRestrict = rootAccount.getFlowRestrict();

		Map<String, String> logo_txt = tipService.getLogoData(rootAccount, "logo_res_taocan", "logo_res_zhqingqiu", SendCommonPostMail.EMAIL_HOST, SendCommonPostMail.EMAIL_USERNAME, SendCommonPostMail.EMAIL_PASSWORD);

		// String user_email_notify_subject = rootAccount.getRegSource()==0?"热云数据广告效果监控套餐提醒":"新华频媒广告效果监控套餐提醒";
		String user_email_notify_subject = logo_txt.get("logo_res_taocan");

		String companyName = rootAccount != null && !org.apache.commons.lang.StringUtils.isEmpty(rootAccount.getCompany())
				? "尊敬的" + rootAccount.getCompany() + "," : "尊敬的客户您好,";
		String companyOrEmail = rootAccount.getCompany() != null ? rootAccount.getCompany() : rootAccount.getEmail();
		Long rootParent = rootAccount.getId();
		IsNotified isNotifiedObject = isNotifiedRepository.findIsNotifiedByAccountId(rootParent);

		boolean isTrackProduct = true;
		List<String> bccList = new ArrayList<String>();//密送列表

		//配置的收件人
		String package_email = configParamRepository.findParamsByKey("package_notify_email");
		if (!StringUtils.isEmpty(package_email)) {

			bccList.addAll(Arrays.asList(package_email.split(",")));
		}

		String salesManLeaderEmail = bussinessManRepository.findEmialWithLeader(rootAccount.getBussinessman());

		String[] busEmails = salesManLeaderEmail == null ? new String[]{} : salesManLeaderEmail.split(",");

		for (String emialSal : busEmails) {
			// 销售不在配置收件人中时,不是 petter 时 密送给对应销售
			if (!bccList.contains(emialSal)) {
				bccList.add(emialSal);
			}
		}

		List<String> accountMail = new ArrayList<>();
		if (Constant.mailNeed != null && Boolean.parseBoolean(Constant.mailNeed)) {
			//正式环境 发送客户邮件
			accountMail.add(rootAccount.getEmail());
		}


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

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

		if (rootParent.equals(accountId) && rootAccount.getFlowRestrict()) {

			if (isNotifiedObject != null && !isNotifiedObject.getPreviousPackageLevel().equals(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);
			}

			String title = SUPER_USER_EMAIL_NOTIFY_SUBJECT;
			String titleWarn = "热云数据广告效果监控套餐提醒";
			String titleTraffic = "广告效果监控产品流量提醒";

			//处理国际化
			if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
				title = ENG_SUPER_USER_EMAIL_NOTIFY_SUBJECT;
				titleWarn = "Reminder for advertising effect monitoring package of Reyun";
				titleTraffic = "Traffic reminder for advertising effect monitoring products";
			}
			//end
			int remainingDays = accountRestrict4Web.getRemainDays();
			int trackRemainDays = accountRestrict4Web.getTrackRemainingDays();

			BigInteger clickNum = accountRestrict4Web.getTrackTotalFlow();

			DecimalFormat decimalFormat = new DecimalFormat("0%");
			String trackRemainPercent1 = decimalFormat.format(accountRestrict4Web.getTrackRemainPercent());

			if (flowRestrict) {
				if (isTrackProduct) {
					/**
					 * 是广告检测产品
					 */
					if (remainingDays > 1 && remainingDays <= 10 && (isNotifiedObject.getTrackTenDaysNotified() == null || !isNotifiedObject.getTrackTenDaysNotified())) {
						isNotifiedObject.setTrackTenDaysNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackPastTimeNotified(true);
//                        String contents = String.format(SUPER_USER_TRACK_EMAIL_NOTIFY_CONTENT,
//                                companyOrEmail, packageType.getPackageName(), "还有" + remainingDays + "天即将到期");
						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "将在" + remainingDays + "天后(" + rootAccount.getPastDate() + ")到期,为了不影响您的正常使用," +
								"请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收,但数据展示服务将暂时无法使用。";

						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring " + packageType.getPackageName()
									+ "will be expired in " + remainingDays + "days(" + rootAccount.getPastDate() + "). To ensure normal use, please contact the commercial personnel to renew the service ASAP. ";
						}
						//end

						try {

//                            Thread emailThread = new EmailThread(SUPER_USER_EMAIL_NOTIFY_SUBJECT, contents, emailList);
//                            emailThread.start();
//                            Thread accountEmailThread = new EmailThread("热云数据广告效果监控套餐提醒",accountContents, accountEmailList);
//                            accountEmailThread.start();
							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);

						} catch (Exception e) {
							isNotifiedObject.setTrackTenDaysNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackPastTimeNotified(false);

							logger.error("套餐提醒邮件错误", e);
						}
					} else if (remainingDays > 10 && remainingDays <= 30 && (isNotifiedObject.getTrackOneMonthNotified() == null || !isNotifiedObject.getTrackOneMonthNotified())) {
						isNotifiedObject.setTrackOneMonthNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackPastTimeNotified(true);

						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "将在" + remainingDays + "天后(" + rootAccount.getPastDate() + ")到期,为了不影响您的正常使用,请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收,但数据展示服务将暂时无法使用。";
						try {

							//处理国际化
							if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
								accountContents = "Your advertising effect monitoring " + packageType.getPackageName()
										+ "will be expired in " + remainingDays + "days(" + rootAccount.getPastDate() + "). To ensure normal use, please contact the commercial personnel to renew the service ASAP. ";
							}


							//end
							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);
						} catch (Exception e) {
							isNotifiedObject.setTrackOneMonthNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackPastTimeNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					} else if (remainingDays <= 0 && (isNotifiedObject.getTrackExpireNotified() == null || !isNotifiedObject.getTrackExpireNotified())) {
						isNotifiedObject.setTrackExpireNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackPastTimeNotified(true);

						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "已到期,为了不影响您的正常使用,请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收,但数据展示服务将暂时无法使用。";
						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring " + packageType.getPackageName()
									+ "will be expired in " + remainingDays + "days(" + rootAccount.getPastDate() + "). To ensure normal use, please contact the commercial personnel to renew the service ASAP. ";
						}
						//end
						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							// MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);

						} catch (Exception e) {
							isNotifiedObject.setTrackExpireNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackPastTimeNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					} else if (remainingDays == 1 && (isNotifiedObject.getTrackOneDaysNotified() == null || !isNotifiedObject.getTrackOneDaysNotified())) {
						isNotifiedObject.setTrackOneDaysNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackPastTimeNotified(true);


						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "将在明天到期,为了不影响您的正常使用,请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收,但数据展示服务将暂时无法使用。";
						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {

							accountContents = "Your advertising effect monitoring " + packageType.getPackageName()
									+ "will be expired tomorrow. To ensure normal use, please contact the commercial personnel to renew the service ASAP. ";
						}
						//end

						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);
						} catch (Exception e) {
							isNotifiedObject.setTrackOneDaysNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackPastTimeNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					} else if (remainingDays > 30 && remainingDays <= 60 && (isNotifiedObject.getTrackTwoMonthNotified() == null || !isNotifiedObject.getTrackTwoMonthNotified())) {
						isNotifiedObject.setTrackTwoMonthNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackPastTimeNotified(true);


						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "将在" + remainingDays + "天后(" + rootAccount.getPastDate() + ")到期,为了不影响您的正常使用,请尽快联系商务续订服务。服务到期后我们将会继续支持您的数据上报和接收,但数据展示服务将暂时无法使用。";
						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring " + packageType.getPackageName()
									+ "will be expired in " + remainingDays + "days(" + rootAccount.getPastDate() + "). To ensure normal use, please contact the commercial personnel to renew the service ASAP. ";
						}
						//end
						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);
						} catch (Exception e) {
							isNotifiedObject.setTrackTwoMonthNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackPastTimeNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					}
				}
			}

//            if ( false && !packageType.getSuperLevel() && flowRestrict ) {
			// 取消此处的流量邮件提醒   采用实时流量邮件提醒
			if (false && !packageType.getSuperLevel() && flowRestrict) {


				/**
				 * 不是超级用户,是包流量的用户
				 */
				if (isTrackProduct) {
					double total = (packageType.getTrackFlow().add(BigInteger.valueOf(rootAccount.getAppentTrackFlow()))).doubleValue();
					boolean thirtyToTwenty = (total * 0.7 <= clickNum.doubleValue()) && (total * 0.8 > clickNum.doubleValue());
					boolean twentyToTen = (total * 0.8 <= clickNum.doubleValue()) && (total * 0.9 > clickNum.doubleValue());
					boolean tenPercent = (total * 0.9 <= clickNum.doubleValue()) && (total * 0.95 > clickNum.doubleValue());
					boolean fivePercent = (total * 0.95 <= clickNum.doubleValue()) && (total * 1 > clickNum.doubleValue());
					boolean exPercent = total <= clickNum.doubleValue();

					if (thirtyToTwenty && (isNotifiedObject.getTrackThirtyPercentNotified() == null || !isNotifiedObject.getTrackThirtyPercentNotified())) {
						isNotifiedObject.setTrackThirtyPercentNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
						accountRestrict4Web.setTrackFlowNotified(true);

						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "中剩余流量已不足" + trackRemainPercent1 + ",请关注您的套餐流量使用情况,并联系商务续订服务。";

						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring package " + packageType.getPackageName()
									+ "is in low traffic " + trackRemainPercent1 + " .Please pay attention to the traffic use of your package and contact the commercial personnel to renew the service.";
						}
						//end
						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);
						} catch (Exception e) {
							isNotifiedObject.setTrackThirtyPercentNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
							accountRestrict4Web.setTrackFlowNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					} else if (twentyToTen && (isNotifiedObject.getTrackTwentyPercentNotified() == null || !isNotifiedObject.getTrackTwentyPercentNotified())) {
						isNotifiedObject.setTrackTwentyPercentNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
						accountRestrict4Web.setTrackFlowNotified(true);

						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "中剩余流量已不足" + trackRemainPercent1 + ",请关注您的套餐流量使用情况,并联系商务续订服务。";

						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring package " + packageType.getPackageName()
									+ "is in low traffic " + trackRemainPercent1 + " .Please pay attention to the traffic use of your package and contact the commercial personnel to renew the service.";
						}
						//end
						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);
						} catch (Exception e) {
							isNotifiedObject.setTrackTwentyPercentNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
							accountRestrict4Web.setTrackFlowNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					} else if (tenPercent && (isNotifiedObject.getTrackTenPercentNotified() == null || !isNotifiedObject.getTrackTenPercentNotified())) {
						isNotifiedObject.setTrackTenPercentNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
						accountRestrict4Web.setTrackFlowNotified(true);
//                        String contents = companyOrEmail + "购买的" + packageType.getPackageName() + "中广告效果监控剩余流量不足" + trackRemainPercent1 + ",请尽快跟进。";

						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "中剩余流量已不足" + trackRemainPercent1 + ",请关注您的套餐流量使用情况,并联系商务续订服务。";
						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring package " + packageType.getPackageName()
									+ "is in low traffic " + trackRemainPercent1 + " .Please pay attention to the traffic use of your package and contact the commercial personnel to renew the service.";
						}
						//end

						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);
						} catch (Exception e) {
							isNotifiedObject.setTrackTenPercentNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
							accountRestrict4Web.setTrackFlowNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					} else if (fivePercent && (isNotifiedObject.getTrackFivePercentNotified() == null || !isNotifiedObject.getTrackFivePercentNotified())) {
						isNotifiedObject.setTrackFivePercentNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
						accountRestrict4Web.setTrackFlowNotified(true);

						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "中剩余流量已不足" + trackRemainPercent1 + ",请关注您的套餐流量使用情况,并联系商务续订服务。";

						//处理国际化
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring package " + packageType.getPackageName()
									+ "is in low traffic " + trackRemainPercent1 + " .Please pay attention to the traffic use of your package and contact the commercial personnel to renew the service.";
						}
						//end
						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);
						} catch (Exception e) {
							isNotifiedObject.setTrackFivePercentNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
							accountRestrict4Web.setTrackFlowNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					} else if (exPercent && (isNotifiedObject.getTrackExhaustPercentNotified() == null || !isNotifiedObject.getTrackExhaustPercentNotified())) {
						isNotifiedObject.setTrackExhaustPercentNotified(true);
						isNotifiedRepository.save(isNotifiedObject);
						accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
						accountRestrict4Web.setTrackFlowNotified(true);

						//处理国际化
						String accountContents = companyName + "您购买的广告效果监控" + packageType.getPackageName() + "流量已经用完,为了不影响您的正常使用,请尽快联系商务续订服务。流量用尽后我们将会继续支持您的数据上报和接收,但数据展示服务将暂时无法使用。";
						if (lanType.equals(LanguageTypeEnum.ENGLISH.getCode())) {
							accountContents = "Your advertising effect monitoring package " + packageType.getPackageName()
									+ "is out of traffic . To ensure normal use, please contact the commercial personnel to renew the service ASAP. After the traffic is exhausted, we’ll continuously support your data reporting and reception, but the data display is unavailable temporarily.";
						}
						//end
						try {

							Map<String, String> mailConfig = null;
							if (rootAccount.getRegSource() != 0) {
								mailConfig = logo_txt;
							}
							//MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList,mailConfig);
							SendCommonPostMail.sendMailReuse(accountMail, user_email_notify_subject, accountContents, null, bccList, mailConfig);
//                            MailUtils.sendHtmlEmailWithCC(user_email_notify_subject, accountContents, accountMail, null, bccList);

						} catch (Exception e) {
							isNotifiedObject.setTrackExhaustPercentNotified(false);
							isNotifiedRepository.save(isNotifiedObject);
							accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
							accountRestrict4Web.setTrackFlowNotified(false);
							logger.error("套餐提醒邮件错误", e);
						}
					}
				}
			}

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

	@Override
	public AccountRestrict4Web toEnglish(AccountRestrict4Web byAccountId) {
		if (byAccountId == null) {
			return null;
		}
		PackageType packageType = this.packageTypeRepository.findPackageTypeByID(byAccountId.getPackLevel());
		if (!StringUtils.isEmpty(byAccountId.getPackageName())) {
			byAccountId.setPackageName(packageType.getPackageNameEng());
		}
		if (!StringUtils.isEmpty(byAccountId.getOriginalName())) {
			byAccountId.setOriginalName(packageType.getOriginalNameEng());
		}
		return byAccountId;
	}

	@Override
	public ResultModel findRestrictByAccountWithoutEmail(String email) {
		Account one = accountRepository.findAccountByEmail(email);
		if (one == null) {
			return new ResultModel(207, "账号不存在", "");
		}
		Account rootAccount = getRootAccountData(one);
		if (rootAccount == null || rootAccount.getRegSource() != 2) {
			return new ResultModel(208, "无查询权限", "");
		}

		Map data = new HashMap();
		data.put("status", rootAccount.getStatus());

		if (rootAccount.getStatus() != 1) {
			return ResultModel.OK(data);
		}

		if (Days.daysBetween(new DateTime(), DateTime.parse(rootAccount.getPastDate())).getDays() < 0) {
			return new ResultModel(210, "账号已过期", "");
		}

		AccountRestrict4Web accountRestrict4Web = accountRestrict4WebRepository.findByAccountId(rootAccount.getId());
		if (accountRestrict4Web == null || Hours.hoursBetween(new DateTime(),
				new DateTime(accountRestrict4Web.getCreateTime()).plusHours(23)).getHours() < 0) {

			if (accountRestrict4Web == null) {
				accountRestrict4Web = this.getRestrictData(one.getId(), rootAccount);
			} else {
				AccountRestrict4Web web = this.getRestrictData(one.getId(), rootAccount);
				accountRestrict4Web.setTrackTotalFlow(web.getTrackTotalFlow());
				accountRestrict4Web.setTrackLimit(web.getTrackLimit());
				accountRestrict4Web.setPastDate(web.getPastDate());
				accountRestrict4Web.setRemainDays(web.getRemainDays());
				accountRestrict4Web.setPackageType(web.getPackageType());
				accountRestrict4Web.setPackageFlowId(web.getPackageFlowId());
				accountRestrict4Web.setPackageLimit(web.getPackageLimit());
				accountRestrict4Web.setPackageTotalFlow(web.getPackageTotalFlow());
				accountRestrict4Web.setPackageFlowName(web.getPackageFlowName());

			}
			accountRestrict4Web.setCreateTime(new Date());
			accountRestrict4WebRepository.save(accountRestrict4Web);
		}

		PackageType packageType = accountRestrict4Web.getPackageType();

		if (packageType == null) {
			packageType = packageTypeRepository.findPackageTypeByID(rootAccount.getBussinessman());

			accountRestrict4Web.setRemainDays(Days.daysBetween(new DateTime(), DateTime.parse(accountRestrict4Web.getPastDate())).getDays() + 1);
		}

		data.put("flow_used", accountRestrict4Web.getTrackTotalFlow());
		data.put("flow_limit", accountRestrict4Web.getTrackLimit());
		data.put("past_date", accountRestrict4Web.getPastDate());
		data.put("pakage_name", packageType.getPackageName());
		data.put("remain_days", accountRestrict4Web.getRemainDays());
		data.put("days_pasted", accountRestrict4Web.getRemainDays() <= 0 ? true : false);
		data.put("flow_empty", accountRestrict4Web.getTrackLimit().compareTo(accountRestrict4Web.getTrackTotalFlow()) <= 0 ? true : false);
		data.put("packageFlowName", accountRestrict4Web.getPackageTotalFlow());
		data.put("packageLimit", accountRestrict4Web.getPackageLimit());
		data.put("packageTotalFlow", accountRestrict4Web.getPackageTotalFlow());

		return ResultModel.OK(data);
	}


	public AccountRestrict4Web getRestrictData(Long accountId, Account rootAccount) {

		AccountRestrict4Web accountRestrict4Web = new AccountRestrict4Web();

		if (rootAccount == null) {
			Account one = accountRepository.findOne(accountId);
			rootAccount = getRootAccountData(one);
		}

        /*List<App> apps;
        if (rootAccount.getEmail().trim().equals("jiboxu773966295525@163.com")) {
            apps = appRepository.listAllAppByRootAccount(rootAccount.getId());
        } else {
            apps = appRepository.listAppByRootAccount(rootAccount.getId());
        }*/

		List<String> appkey;
		if (rootAccount.getEmail().trim().equals("jiboxu773966295525@163.com")) {
			appkey = appRepository.findAllAppIdsByAccount(rootAccount.getId());
		} else if (rootAccount.getPubDate() != null && new DateTime(rootAccount.getPubDate()).isAfter(new DateTime("2021-11-14"))) {
			appkey = appRepository.findAllAppIdsByAccount(rootAccount.getId());
		} else {
			appkey = appRepository.findAppIdsByAccount(rootAccount.getId());
			List<String> delApps = appRepository.findDeleteAppsByDate(rootAccount.getId(), "2021-11-14");
			appkey.addAll(delApps);
		}

		if (rootAccount.equals(6380L)) {
			List<String> keyNext = appRepository.findAppkeyByAccount(17108L);
			if (keyNext != null) {
				appkey.addAll(keyNext);
			}
		}

		Long rootParent = rootAccount.getRootParent();


		Boolean flowRestrict = rootAccount.getFlowRestrict();
		String pastDate = rootAccount.getPastDate();
		String trackBeginTime;
		Date rootCreateTime = rootAccount.getPubDate();
		String createTime = DateUtil.format(rootCreateTime, "yyyy-MM-dd");

		trackBeginTime = createTime;

		if (rootAccount.getNewContract() != null && rootAccount.getNewContract()) {
			trackBeginTime = rootAccount.getModifyPricelevelTime();
			logger.info("新合同用户,流量计算开始时间为{},email[{}]", createTime, rootAccount.getId());
		}

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

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

		BigInteger clickNum = new BigInteger("0");
		BigInteger lastThreeDaysClickNum1 = new BigInteger("0");
		BigInteger clickNumPackage = new BigInteger("0");
		BigInteger lastThreeDaysClickNumPackage = new BigInteger("0");
		BigInteger clickNumPackageAll = new BigInteger("0");
		BigInteger lastThreeDaysClickNumPackageAll = new BigInteger("0");


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

		if (appkey.size() > 0) {
			//查询两天前的离线统计数据(2019-02-25需求)
//            DateTime pasDate = new DateTime(pastDate);
//            DateTime pre2Date = new DateTime().plusDays(-2);
//            DateTime useDate = Days.daysBetween(pasDate,pre2Date).getDays()< 0 ? pre2Date :pasDate ;
//            String psDate = useDate.toString("yyyy-MM-dd");
			String psDate = new DateTime().plusDays(-2).toString("yyyy-MM-dd");

			//当用户开通流量包,查询流量包使用流量
			if (rootAccount.getPackageFlowId() != null && rootAccount.getPackageFlowId().intValue() != -1) {
				String packFlowBegin = new DateTime(rootAccount.getPackageFlowDs()).toString("yyyy-MM-dd");

				clickNumPackageAll = getTotalNum(packFlowBegin, psDate, appids, "account_package_flow_restrict", "click_sum");

				if (rootAccount.getModifyPricelevelTime() != null) {
					packFlowBegin = new DateTime(rootAccount.getModifyPricelevelTime()).isAfter(new DateTime(rootAccount.getPackageFlowDs()))
							? rootAccount.getModifyPricelevelTime() : packFlowBegin;
					//当前合同已使用的流量包
					clickNumPackage = getTotalNum(packFlowBegin, psDate, appids, "account_package_flow_restrict", "click_sum");

				}

				lastThreeDaysClickNumPackage = getTotalNum(packFlowBegin, currentDateStr, appids, "account_package_three_days_flow_restrict", "click_sum");

			}

			clickNum = getTotalNum(trackBeginTime, psDate, appids, "account_track_flow_restrict", "click_sum");
			lastThreeDaysClickNum1 = getTotalNum(trackBeginTime, currentDateStr, appids, "account_track_three_days_flow_restrict", "click_sum");
			//clickNum = clickNum.subtract(clickNumPackage);
			lastThreeDaysClickNum1 = lastThreeDaysClickNum1.subtract(lastThreeDaysClickNumPackage);
		}

		PackageType packageType = packageTypeRepository.findPackageTypeByRootParent(rootParent);
		BigInteger incrementFlow = getIncrementFlow(rootParent);
		//老代码,可能有历史数据,目前加上离时流量不影响数据:2019年3月19日17:07:52,加上附加赠送的流量
		BigInteger packageTotal = packageType.getTrackFlow().add(incrementFlow).add(BigInteger.valueOf(rootAccount.getAppentTrackFlow()));
		BigInteger lastThreeDaysClickNum = lastThreeDaysClickNum1.compareTo(new BigInteger("0")) != 0 ? lastThreeDaysClickNum1 : new BigInteger("1");
		int trackRemainDays = (int) Math.floor((packageTotal.doubleValue() - clickNum.doubleValue()) / ((lastThreeDaysClickNum.doubleValue() / 3)));
		double trackRemainPercent = 1.0 - clickNum.doubleValue() / packageTotal.doubleValue();
		DecimalFormat decimalFormat = new DecimalFormat("0%");

		//String trackRemainPercent1 = decimalFormat.format(trackRemainPercent);
		if (rootAccount.getPackageFlowId() != null && rootAccount.getPackageFlowId().intValue() != -1) {
			PackageFlow packageFlow = packageFlowRepository.findOne(rootAccount.getPackageFlowId());
			accountRestrict4Web.setPackageFlowId(rootAccount.getPackageFlowId());

			//流量包套餐流量
			accountRestrict4Web.setPackageLimit(packageFlow.getFlow().add(rootAccount.getAppentPackageFlow() == null
					? new BigInteger("0") : rootAccount.getAppentPackageFlow()));
			accountRestrict4Web.setPackageTotalFlow(clickNumPackageAll);//流量包所有已使用流量
			accountRestrict4Web.setPackageContractTotalFlow(clickNumPackage);//对应合同流量已使用包流量
			accountRestrict4Web.setPackageFlowName(packageFlow.getPackageName());
		}

		accountRestrict4Web.setPastDate(pastDate);
		accountRestrict4Web.setPackageName(packageType.getPackageName());
		accountRestrict4Web.setOriginalName(packageType.getOriginalName());
		accountRestrict4Web.setIOLimit(packageType.getIoFlow());
		accountRestrict4Web.setTrackLimit(packageTotal);//账号套餐流量
		accountRestrict4Web.setTrackTotalFlow(clickNum);
		accountRestrict4Web.setAccountId(rootParent);
		accountRestrict4Web.setPriceLevel(rootAccount.getPricelevel().intValue());
		accountRestrict4Web.setTrackRemainPercent(trackRemainPercent);
		accountRestrict4Web.setTrackRemainingDays(trackRemainDays);
		accountRestrict4Web.setPackLevel(packageType.getId());
		accountRestrict4Web.setFlowRestrict(flowRestrict);
		accountRestrict4Web.setSuperLevel(packageType.getSuperLevel());
		accountRestrict4Web.setCreateTime(new Date());
		accountRestrict4Web.setFirstDayOfThisMonth(firstDayOfThisMonth);
		accountRestrict4Web.setRemainDays(remainingDays);
		accountRestrict4Web.setRootAccoount(rootAccount);
		accountRestrict4Web.setPackageType(packageType);
		accountRestrict4Web.setPackageFlowId(rootAccount.getPackageFlowId());

		if (clickNum.doubleValue() < 0) {
			accountRestrict4Web.setTrackTotalFlow(new BigInteger("0").subtract(clickNum));
		}

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

		return accountRestrict4Web;
	}

	public Account getRootAccountData(Account account) {
		return account.getRootParent().equals(account.getId()) ? account : accountRepository.findOne(account.getRootParent());
	}


	@Override
	public BigInteger getTotalNum(String createTime, String pastDate, String appids, String reportName, String
			sumType) {

		Map<String, String> conditions = new HashMap<>();
		conditions.put("appids", appids);
		conditions.put("startdate", createTime);
		conditions.put("enddate", pastDate);
		return getTotalNum(conditions, reportName, sumType);
	}

	/**
	 * 查询广告效果监控产品的点击量和行为分析产品的点击量的方法
	 */
	@Override
	public BigInteger getTotalNum(Map<String, String> conditions, String reportName, String sumType) {
		Long appId = 1218L;
		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 HashMap<String, Boolean> getTrackExhaust(List<App> appList) {
		HashMap<String, Boolean> TrackExhaustMap = new HashMap<>();
		for (App app : appList) {
			TrackExhaustMap.put(app.getCreateAccount(), false);
		}
		for (String createAccount : TrackExhaustMap.keySet()) {
			TrackExhaustMap.put(createAccount, isTrackExhaust(Long.valueOf(createAccount)));
		}
		return TrackExhaustMap;
	}

	@Override
	public Boolean isTrackExhaust(Long accountId) {
//        Long rootParent = accountRepository.findRootParentByAccountId(accountId).longValue();
		Account rootAccount = accountRepository.findRootAccountById(accountId);
		Long rootParent = rootAccount.getId();
		List<App> apps = appRepository.listAppByRootAccount(rootAccount.getId());
		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();
			if (flowRestrict == null) {
				flowRestrict = true;
			}

			BigInteger incrementFlow = getIncrementFlow(rootParent);
			BigInteger packageTotal = packageType.getTrackFlow().add(incrementFlow).add(BigInteger.valueOf(rootAccount.getAppentTrackFlow()));

            /*String pastDate = rootAccount.getPastDate();
            String trackBeginTime;
            Date rootCreateTime = rootAccount.getCreateTime();
            String createTime = DateUtil.format(rootCreateTime, "yyyy-MM-dd");
            trackBeginTime = (rootAccount.getNewContract() != null && rootAccount.getNewContract())
                    ? rootAccount.getModifyPricelevelTime() : createTime;

            //查询两天前的离线统计数据(2019-02-25需求)
            String psDate = new DateTime().plusDays(-2).toString("yyyy-MM-dd");

            BigInteger clickNum = new BigInteger("0");

            if (Days.daysBetween(new DateTime(trackBeginTime), new DateTime(psDate)).getDays() >= 0) {
                clickNum = getTotalNum(trackBeginTime, psDate, appids, "account_track_flow_restrict", "click_sum");
                if (rootAccount.getPackageFlowId() != null) {//减去离线流量包产生的流量
                    BigInteger clickNumPackage = getTotalNum(trackBeginTime, psDate, appids, "account_package_flow_restrict", "click_sum");
                    clickNumPackage = clickNumPackage == null ? new BigInteger("0") : clickNumPackage;
                    clickNum = clickNum.subtract(clickNumPackage);
                }
            }*/

			AccountRestrict4Web restrict4Web = accountRestrict4WebRepository.findByAccountId(rootParent);

			if (restrict4Web == null) {
				//首次登陆不校验
				return false;
			}
			BigInteger usedFlow = packageFlowService.getUsedTrackFlow(restrict4Web, rootAccount);

            /*if (restrict4Web != null && restrict4Web.getIncrementFlow() != null) {
                usedFlow = usedFlow.add(restrict4Web.getIncrementFlow());
            }*/

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

	@Override
	public AccountRestrict4Web RestrictFlowByAccountTask(Account account, String lanType) {
		Long accountId = account.getId();
		AccountRestrict4Web flowRestrict = findRestrictByAccount(accountId, lanType);
		AccountRestrict4Web byAccountId = accountRestrict4WebRepository.findByAccountId(flowRestrict.getAccountId());

		if (account.getRootParent() == null) {
			Account root = accountRepository.findRootAccount(accountId);
			account.setModifyPricelevelTime(root.getModifyPricelevelTime());
		}
		if (byAccountId != null) {
			Boolean trackFlowNotified = byAccountId.getTrackFlowNotified() != null ? byAccountId.getTrackFlowNotified() : false;
			Boolean trackPastTimeNotified = byAccountId.getTrackPastTimeNotified() != null ? byAccountId.getTrackPastTimeNotified() : false;
			byAccountId.setTrackFlowNotified(trackFlowNotified);
			byAccountId.setTrackPastTimeNotified(trackPastTimeNotified);
			byAccountId.setModifyTime(new Date());
			byAccountId.setTrackTotalFlow(flowRestrict.getTrackTotalFlow());
			byAccountId.setEtlFlowModifyTime(new Date());
			byAccountId.setPackageTotalFlow(flowRestrict.getPackageTotalFlow());
			byAccountId.setPackageContractTotalFlow(flowRestrict.getPackageContractTotalFlow());
			accountRestrict4WebRepository.save(byAccountId);
			//记录历史日志
			restrictFlowsLogRepository.save(buildFlowLog(byAccountId));

		} else {
			flowRestrict.setEtlFlowModifyTime(new Date());
			flowRestrict.setModifyTime(new Date());
			Restrict4NewContract restrict4NewContract = restrict4NewContractRepository.findLatest(accountId);
			if (restrict4NewContract != null && restrict4NewContract.getTodayFlowBefore() != null && restrict4NewContract.getNewPriceDate().equals(account.getModifyPricelevelTime())) {
				//重置合同节点前的流量
				flowRestrict.setIncrementContanct(restrict4NewContract.getTodayFlowBefore());
			}
			accountRestrict4WebRepository.save(flowRestrict);
			//记录历史日志
			restrictFlowsLogRepository.save(buildFlowLog(flowRestrict));
		}

		DateTime dateTime = DateTime.now();
		if (dateTime.dayOfMonth().get() == 1) {
			//清除一月之前的数据
			List<RestrictFlowsLog> oldLogs = restrictFlowsLogRepository.findNotUseful(dateTime.plusMonths(-1).toString("yyyy-MM-dd"), account.getId());
			if (oldLogs != null && !oldLogs.isEmpty()) {
				restrictFlowsLogRepository.delete(oldLogs);
			}
		}


		return flowRestrict;
	}

	public RestrictFlowsLog buildFlowLog(AccountRestrict4Web byAccountId) {
		RestrictFlowsLog flowsLog = new RestrictFlowsLog();
		flowsLog.setAccountId(byAccountId.getAccountId());
		flowsLog.setAfterFlow(BigInteger.ZERO);
		flowsLog.setBeforeFlow(BigInteger.ZERO);
		flowsLog.setQueryFlow(byAccountId.getTrackTotalFlow());
		flowsLog.setCreatTime(new Date());
		flowsLog.setDsValue(DateTime.now().toString("yyyy-MM-dd"));
		return flowsLog;
	}

	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;
	}


	public BigInteger getIncrementFlow(Long rootAccountid) {

		List<IncrementFlow> list = incrementFlowRepository.findIncrementFlowByAccountId(rootAccountid);

		BigInteger bigIntegerTotal = new BigInteger("0");
		if (list != null) {
			for (IncrementFlow incrementFlow : list) {
				long start = DateUtil.parseDate(incrementFlow.getStartDate()).getTime();
				long end = DateUtil.parseDate(incrementFlow.getEndDate()).getTime();
				long now = new Date().getTime();
				if (now - start >= 0 && now - end <= 0) {
					Long flow = incrementFlow.getFlow();
					bigIntegerTotal = new BigInteger(Long.toString(flow)).add(bigIntegerTotal);
				}
			}
		}
		return bigIntegerTotal;
	}


	@Override
	public AccountRestrict4Web getAccountUsedFlows(AccountRestrict4Web byAccountId, Account account) {

		if (entityManager.contains(byAccountId)) {//判断是否对象处于托管状态(取消托管,防止自动同步到数据库)
			entityManager.clear();
		}

		if (byAccountId.getIncrementFlow() == null) {
			byAccountId.setIncrementFlow(new BigInteger("0"));
		}
		if (byAccountId.getPackageIncrementFlow() == null) {
			byAccountId.setPackageIncrementFlow(new BigInteger("0"));
		}

 /*       PackageType packageType = packageTypeRepository.findOne(byAccountId.getPackLevel());
        if (byAccountId.getTrackLimit().compareTo(packageType.getTrackFlow()) == 0) {
            byAccountId.setTrackTotalFlow(byAccountId.getTrackTotalFlow().add(byAccountId.getIncrementFlow()).add(BigInteger.valueOf(account.getAppentTrackFlow())));
        } else {
            byAccountId.setTrackTotalFlow(byAccountId.getTrackTotalFlow().add(byAccountId.getIncrementFlow()));
        }

        byAccountId.setTrackTotalFlow(byAccountId.getTrackTotalFlow().add(byAccountId.getIncrementFlow()));//老代码逻辑
*/
		if (byAccountId.getPackageIncrementFlow() == null) {
			byAccountId.setPackageIncrementFlow(BigInteger.ZERO);
		}

		if (byAccountId.getPackageContractTotalFlow() == null) {
			byAccountId.setPackageContractTotalFlow(BigInteger.ZERO);
		}

		if (byAccountId.getPackageIncrementContractFlow() == null) {
			byAccountId.setPackageIncrementContractFlow(BigInteger.ZERO);
		}


		if (byAccountId.getIncrementContanct() != null) {
			// 减去重置节点前当天的流量
			byAccountId.setTrackTotalFlow(byAccountId.getTrackTotalFlow().subtract(byAccountId.getIncrementContanct()));
		}

		if (byAccountId.getPackageFlowId() != null && byAccountId.getPackageFlowId().intValue() != -1) {

			//流量包总用量
			BigInteger packFlow = packageFlowService.getPackageFlowUsed(byAccountId, account);
			BigInteger trackFlow = packageFlowService.getUsedTrackFlow(byAccountId, account);
			byAccountId.setPackageTotalFlow(packFlow);
			byAccountId.setTrackTotalFlow(trackFlow);

		} else {
			//流量总用量
			byAccountId.setTrackTotalFlow(byAccountId.getTrackTotalFlow().add(byAccountId.getIncrementFlow()));
		}


		if (byAccountId.getPackageLimit() == null || byAccountId.getPackageLimit().doubleValue() == 0) {
			byAccountId.setPackageFlowPercent(0.0d);
		} else if (byAccountId.getPackageTotalFlow() == null || byAccountId.getPackageTotalFlow().doubleValue() == 0) {
			byAccountId.setPackageFlowPercent(0.0d);
		} else {
			double packPercent = byAccountId.getPackageTotalFlow().doubleValue() / byAccountId.getPackageLimit().doubleValue();
			byAccountId.setPackageFlowPercent(packPercent);
		}

		//重新计算流量百分比
		double trackPercent = byAccountId.getTrackTotalFlow().doubleValue() / byAccountId.getTrackLimit().doubleValue();
		byAccountId.setTrackRemainPercent(1 - trackPercent);

		if (byAccountId.getTrackTotalFlow().doubleValue() < 0) {
			byAccountId.setTrackTotalFlow(BigInteger.ZERO);
		}

		return byAccountId;
	}
}