AuthServiceImpl.java 105 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 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
package com.reyun.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.reyun.dic.LanguageTypeEnum;
import com.reyun.dic.RoleEnumType;
import com.reyun.model.*;
import com.reyun.repository.*;
import com.reyun.security.TokenManager;
import com.reyun.service.*;
import com.reyun.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class AuthServiceImpl implements AuthService {

    protected Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private DataAuthRepository dataAuthRepository;

    @Autowired
    private ThirdAccountAuthRepository thirdAccountAuthRepository;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    RoleAuthDetailRepository roleAuthDetailRepository;

    @Autowired
    AuthRepository authRepository;

    @Autowired
    ChannelRepository channelRepository;

    @Autowired
    CampaignRepository campaignRepository;

    @Autowired
    AppRepository appRepository;

    @Autowired
    RoleAuthRepository roleAuthRepository;

    @Autowired
    ChannelAccountMapRepository channelAccountMapRepository;

    @Autowired
    DataAuthPkgsubcampaignRepository dataAuthPkgsubcampaignRepository;

    @Autowired
    UserViewColumnRepository userViewColumnRepository;

    @Autowired
    ChannelAccountService channelAccountService;

    @Autowired
    AccountService accountService;
    @Autowired
    CampaignService campaignService;


    @Autowired
    TipService tipService;

    @Autowired
    private ChannelService channelServiceImpl;

    @PersistenceContext
    private EntityManager entityManager;

    private static final int MAX_CUSTOM_ROLE_NUM = 5;

    private static final int MAX_MANAGE_NUM = 3;

    /**
     * 获取自定义角色和渠道账号的MENU
     * created by sunhao 20170607
     */
    @Override
    public RoleAuth getMenuAthByRole(Account loginAccount, Long roleId, String lanType) {
        RoleAuth roleAuth = roleAuthRepository.findOne(roleId);

        //自定义角色,渠道账号
        if (null != roleAuth && (roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_AUTH.getKey())
                || roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_ROLE.getKey())
                || roleAuth.getRoleCategory().equals(RoleEnumType.CHANNEL_PERSON.getKey()))) {

            List<RoleAuthDetail> roleAuthDetailList = roleAuthDetailRepository.findDetailByRole(roleId);

            List<RoleAuthDetail> roleAuthDetails = new ArrayList<>();
            for (RoleAuthDetail roleAuthDetail : roleAuthDetailList) {
                if (entityManager.contains(roleAuthDetail)) {//判断是否对象处于托管状态(取消托管,防止自动同步到数据库)
                    entityManager.clear();
                }
                roleAuthDetail = roleAuthDetail.toTransEng(roleAuthDetail, lanType);
                roleAuthDetails.add(roleAuthDetail);
            }

            roleAuth.setRoleAuthDetails(roleAuthDetails);
        }

        return roleAuth;
    }

    @Override
    public Account getSubAccountInfo(Long subAccountId) {
        return accountRepository.findOne(subAccountId);
    }

    @Override
    public Account getChannelAccountInfoByEmail(Account loginAccount, String email) {

        Account channelAccount = accountRepository.findAccountByEmail(email);

        //判断此渠道账号是否已经授权
        if (null != channelAccount && channelAccount.getIsChannelPerson()) {

            List<Long> subAccountIds = this.getAllSubAccountList(loginAccount);

            List<Auth> authList = authRepository.findAuthByCreateAndAuth(subAccountIds, channelAccount.getId());

            channelAccount.setAuthList(authList);
        }

        return channelAccount;
    }

    /**
     * 获取所有的角色
     * created by sunhao 20170607
     */
    @Override
    public List<RoleAuth> getAllCustomRoleList(Account loginAccount) {

        List<RoleAuth> roleAuthList = new ArrayList<>();

        RoleAuth roleAuth = roleAuthRepository.findOne(loginAccount.getRoleCategory());

        //母账号、管理员、子账号管理员
        if (loginAccount.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {

            List<Long> accountList = this.getAllSubAccountList(loginAccount);
            roleAuthList = roleAuthRepository.findAllCustomRoleList(accountList);
        }

        return roleAuthList;
    }

    /**
     * 查询子账户菜单权限信息,用于登陆
     */
    @Override
    public Account getSubAccountAuthById(Long subAccountId) {

        Account account = accountRepository.findOne(subAccountId);

        if (null != account && !account.getIsSuperUser()) {
            //角色
            RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

            //角色为空,跳出
            if (null == roleAuth) {
                return account;
            }

            //构建菜单权限信息
            if (roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {

                //2,子应用管理员,只有App权限
                List<Auth> authList = authRepository.findAuthByAccountId(subAccountId);
                account.setAuthStr(this.parseAuthList2Str(authList));

            } else if (roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_AUTH.getKey())
                    || roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_ROLE.getKey())
                    || roleAuth.getRoleCategory().equals(RoleEnumType.CHANNEL_PERSON.getKey())) {

                //3,自定义权限,4,自定义角色,5,渠道账号,菜单权限来自auth.getControlAuth()
                List<Auth> authList = authRepository.findAuthByAccountId(subAccountId);
                account.setAuthStr(this.parseAuthList2Str(authList));

            }

        }

        return account;
    }

    /**
     * 获取单个子账号信息,权限信息为全量信息
     * created bu sunhao 20170606
     */
    @Override
    public Account getSubAccountById(Account loginAccount, Long subAccountId) {

        List<Auth> authList = new ArrayList<>();


        Account account = accountRepository.findOne(subAccountId);
        if (null != account) {

            //查询角色
            RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());
            //角色为空,跳出
            if (null == roleAuth) {
                return account;
            }

            //设置母账号的角色
            Account parentAccount = accountRepository.findOne(account.getParent());
            account.setParentRole(null != parentAccount ? parentAccount.getRoleCategory() : 0L);

            //查询权限
            if (roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {

                //2,子应用管理员
                authList = authRepository.findAuthByAccountId(subAccountId);

            } else if (roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_AUTH.getKey())) {

                //3,自定义角色,
                authList = authRepository.findAuthByAccountId(subAccountId);
                List<DataAuth> dataAuthList = dataAuthRepository.findDataAuthByAccount(subAccountId);

                authList = this.buildAuthListWithDataAuth(authList, dataAuthList, true, false);

            } else if (roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_ROLE.getKey())) {

                //4,选择的保存自定义角色,无需填充菜单权限
                authList = authRepository.findAuthByAccountId(subAccountId);
                List<DataAuth> dataAuthList = dataAuthRepository.findDataAuthByAccount(subAccountId);

                authList = this.buildAuthListWithDataAuth(authList, dataAuthList, false, false);

            } else if (roleAuth.getRoleCategory().equals(RoleEnumType.CHANNEL_PERSON.getKey())) {

                //5,渠道账号
//                List<Long> accountList = this.getAllSubAccountList(loginAccount);
                // modify on 2019/09/29
                List<Long> accountList = accountRepository.findAllAccountByAccount(loginAccount);
                authList = authRepository.findAuthByCreateIds(subAccountId, accountList);
                List<DataAuth> dataAuthList = dataAuthRepository.findDataAuthByAccount(subAccountId);

                authList = this.buildAuthListWithDataAuth(authList, dataAuthList, true, true);
            }

            //设置权限LIST
            account.setAuthList(authList);
        }

        return account;
    }

    /**
     * 构建AuthList,包含数据权限,参数addMenuAuth 控制是否加入menu权限
     * created by sunhao
     */
    private List<Auth> buildAuthListWithDataAuth(List<Auth> authList, List<DataAuth> dataAuthList, boolean addMenuAuth, boolean isChannelPerson) {

        //数据权限
        Map<Long, Map<Long, DataAuth>> appDataAuthMap = this.getAppChannelCampaignMap(dataAuthList);

        //APP权限
        for (Auth auth : authList) {

            if (addMenuAuth) {

                //全部的菜单权限
                Map<String, RoleAuthDetail> roleAuthDetailMap = isChannelPerson ? this.getChannelAccountRoleAuthMap() : this.getAllRoleAuthMap();

                //拥有的菜单权限
                JSONArray jsonArray = JSONArray.fromObject(auth.getControlAuth());

                //聚合权限到列表中
                for (int i = 0; i < jsonArray.size(); i++) {

                    JSONObject authObject = jsonArray.getJSONObject(i);
                    RoleAuthDetail roleAuthDetail = roleAuthDetailMap.get(authObject.getString("auth"));

                    if (null != roleAuthDetail) {

                        roleAuthDetail.setEdit(authObject.getBoolean("edit"));
                        roleAuthDetail.setView(authObject.getBoolean("view"));
                    }
                }

                auth.setRoleAuthDetailList(new ArrayList<>(roleAuthDetailMap.values()));
            }

            //设置数据权限
            Map<Long, DataAuth> channelDataAuth = appDataAuthMap.get(auth.getApp());
            auth.setDataAuth(null != channelDataAuth ? new ArrayList<>(channelDataAuth.values()) : new ArrayList<DataAuth>());
        }

        return authList;
    }

    /**
     * 获取APP-渠道-活动MAP
     */
    private Map<Long, Map<Long, DataAuth>> getAppChannelCampaignMap(List<DataAuth> dataAuthList) {

        Map<Long, Map<Long, DataAuth>> appDataAuthMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(dataAuthList)) {

            for (DataAuth dataAuth : dataAuthList) {

                Long channelId = dataAuth.getChannel();
                Long campaignId = dataAuth.getCampaign();

                //是否包含此渠道
                Map<Long, DataAuth> dataAuthMap = appDataAuthMap.get(dataAuth.getApp());
                dataAuthMap = null != dataAuthMap ? dataAuthMap : new HashMap<Long, DataAuth>();

                //是否包含此推广活动
                DataAuth dataAuthTemp = dataAuthMap.get(channelId);
                dataAuthTemp = null != dataAuthTemp ? dataAuthTemp : new DataAuth();
                dataAuthTemp.setChannel(channelId);

                //写入推广活动ID
                if (dataAuth.getAllCampaign()) {

                    dataAuthTemp.setAllCampaign(true);

                } else {

                    List<Long> campaignList = dataAuthTemp.getCampaignList();
                    campaignList = null != campaignList ? campaignList : new ArrayList<Long>();

                    if (!campaignList.contains(campaignId) && 0 != campaignId) {
                        campaignList.add(campaignId);
                    }
                    dataAuthTemp.setCampaignList(campaignList);
                    Channel channel = channelRepository.findOne(channelId);
                    if (channel != null && "APPMARKET".equals(channel.getCategory())) {
                        Map<String, List<String>> subMap = new HashMap<>();
                        Account loginaccount = null;
                        if (loginaccount == null) {
                            loginaccount = accountRepository.findOne(dataAuth.getAccount());
                        }
                        List<Campaign> result = campaignService.listCampaignByAppAndChannelAll(dataAuth.getApp(), channelId, loginaccount);
                        List<DataAuthPkgsubcampaign> pkgsubcampaignListByApp = dataAuthPkgsubcampaignRepository.findPkgsubcampaignListByApp(loginaccount.getId(), dataAuth.getApp());
                        Multimap<Long, String> map = ArrayListMultimap.create();
                        for (DataAuthPkgsubcampaign dataAuthPkgsubcampaign : pkgsubcampaignListByApp) {
                            map.put(dataAuthPkgsubcampaign.getCampaign(), dataAuthPkgsubcampaign.getPkgSubCampaign().toString());
                        }
                        for (Campaign campaign : result) {
                            //List<DataAuthPkgsubcampaign> pkgsubcampaignList = dataAuthPkgsubcampaignRepository.findPkgsubcampaignList(loginaccount.getId(), campaign.getApp(), campaign.getId());
                            Collection<String> pkgsubcampaignList = map.get(campaign.getId());
                            if (!CollectionUtils.isEmpty(pkgsubcampaignList)) {
                                List<String> SubIdList = new ArrayList<>();
                                SubIdList.addAll(pkgsubcampaignList);
                                subMap.put(campaign.getId().toString(), SubIdList);
                            }
                        }
                        dataAuthTemp.setPkgsubcampaign(subMap);
                    }

                    dataAuthTemp.setAllCampaign(false);

                    if (dataAuth.getChannelPermit() == null) {
                        if (dataAuthTemp.getChannelPermit() == null || dataAuthTemp.getChannelPermit() == false) {
                            dataAuthTemp.setChannelPermit(false);
                        }
                    } else {
                        if (dataAuthTemp.getChannelPermit() == null || dataAuthTemp.getChannelPermit() == false) {
                            dataAuthTemp.setChannelPermit(dataAuth.getChannelPermit());
                        }
                    }

                }

                //写入渠道
                dataAuthMap.put(channelId, dataAuthTemp);
                appDataAuthMap.put(dataAuth.getApp(), dataAuthMap);
            }
        }

        return appDataAuthMap;
    }

    /**
     * 获取母账号及下面所有子账号列表
     * created bu sunhao 20170606
     */

    private List<Long> getAllSubAccountList(Account loginAccount) {

        Long rootAccount;

        if (loginAccount.getIsSuperUser()) {
            rootAccount = loginAccount.getId();
        } else {
            rootAccount = this.findRootParentAccount(loginAccount.getId()).getId();
        }

        return accountRepository.findAllAccountList(rootAccount);
    }

    /**
     * 获取子账号的菜单权限。仅仅输出已授权的信息
     * created by sunhao 20170612
     */
    private String parseAuthList2Str(List<Auth> authList) {

        JSONObject resultObject = new JSONObject();

        for (Auth auth : authList) {

            JSONObject authJsonObject = new JSONObject();

            //菜单权限
            JSONArray menuAuthArray = JSONArray.fromObject(auth.getControlAuth() == null ? "[]" : auth.getControlAuth());

            authJsonObject.put("payAuth", auth.isPayAuth());
            authJsonObject.put("retentionAuth", auth.isRetentionAuth());
            authJsonObject.put("isNatureOpen", auth.getIsNatureOpen());
            authJsonObject.put("topAuth", auth.getTopAuth());
            authJsonObject.put("orderAuth", auth.getOrderAuth());
            authJsonObject.put("roleAuthDetailList", menuAuthArray);
            authJsonObject.put("eventAuth", auth.getEventAuth());
            resultObject.put(auth.getApp(), authJsonObject);
        }

        return resultObject.toString();
    }

    /**
     * 获取有次APP权限的所有有效的子账号和渠道账号
     *
     * @param loginAccount
     * @return
     */
    @Override
    public List<Account> getAuthorizedSubAndChannelAccount(Account loginAccount, Long appId) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        return accountRepository.findAuthorizedSubAndChannelAccount(appId, simpleDateFormat.format(new Date()));
    }

    /**
     * 获取所属生效的子账号
     * created by sunhao 20170606
     */
    @Override
    public List<Account> getAllActiveSubAccount(Account loginAccount) {

        List<Account> activeSubAccountList;
        RoleAuth roleAuth = roleAuthRepository.findByRoleCategory(loginAccount.getRoleCategory());

        if (null != roleAuth && roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())) {
            //管理员,需要看到同级别的管理员
            activeSubAccountList = accountRepository.findActiveByRootExcludeSelf(loginAccount.getRootParent(), loginAccount.getId());

        } else if (null != roleAuth && roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {
            //子应用管理员
            activeSubAccountList = accountRepository.findActiveByParent(loginAccount.getId());

        } else {
            //母账号
            activeSubAccountList = accountRepository.findActiveByRoot(loginAccount.getId());

        }

        activeSubAccountList = this.dealWithOriginalAccount(loginAccount, activeSubAccountList);

        return activeSubAccountList;
    }

    /**
     * 查询所属失效的子账号
     * created by sunhao 20170606
     */
    @Override
    public List<Account> getAllDisableSubAccount(Account loginAccount) {

        List<Account> disableSubAccountList;

        RoleAuth roleAuth = roleAuthRepository.findByRoleCategory(loginAccount.getRoleCategory());

        if (null != roleAuth && roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())) {
            //管理员,需要看到同级别的管理员
            disableSubAccountList = accountRepository.findDisableByRootExcludeSelf(loginAccount.getRootParent(), loginAccount.getId());

        } else if (null != roleAuth && roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {
            //子应用管理员
            disableSubAccountList = accountRepository.findDisableByParent(loginAccount.getId());

        } else {
            //母账号
            disableSubAccountList = accountRepository.findDisableByRoot(loginAccount.getId());
        }

        disableSubAccountList = this.dealWithOriginalAccount(loginAccount, disableSubAccountList);

        return disableSubAccountList;
    }

    /**
     * 查询有效的渠道账号
     * created by sunhao 20170612
     */
    @Override
    public List<Account> getAllActiveChannelAccount(Account loginAccount) {

        List<Account> channelAccountList = new ArrayList<>();

        List<Long> channelAccountIds;

        RoleAuth roleAuth = roleAuthRepository.findByRoleCategory(loginAccount.getRoleCategory());

        if (loginAccount.getIsSuperUser() || RoleEnumType.MANAGER.getKey().equals(roleAuth.getRoleCategory())) {

            //查询root_parent下面
            channelAccountIds = channelAccountMapRepository.findChannelAccountIdByRoot(loginAccount.getRootParent(), true);

        } else {
            //查询自己名下的渠道账号
            channelAccountIds = channelAccountMapRepository.findChannelAccountByCreate(loginAccount.getId(), true);

        }

        //查询这些有权限的所有渠道账号
        if (!CollectionUtils.isEmpty(channelAccountIds)) {
            channelAccountList = accountRepository.findChannelAccountByAccountIds(channelAccountIds);
        }

        channelAccountList = this.dealWithOriginalAccount(loginAccount, channelAccountList);

        return channelAccountList;
    }

    /**
     * 查询停用的渠道账号
     * created by sunhao 20170612
     */
    @Override
    public List<Account> getAllDisableChannelAccount(Account loginAccount) {

        List<Account> channelAccountList = new ArrayList<>();

        List<Long> channelAccountIds;

        RoleAuth roleAuth = roleAuthRepository.findByRoleCategory(loginAccount.getRoleCategory());

        if (loginAccount.getIsSuperUser() || RoleEnumType.MANAGER.getKey().equals(roleAuth.getRoleCategory())) {

            //查询root_parent下面
            channelAccountIds = channelAccountMapRepository.findChannelAccountIdByRoot(loginAccount.getRootParent(), false);

        } else {
            //查询自己名下的渠道账号
            channelAccountIds = channelAccountMapRepository.findChannelAccountByCreate(loginAccount.getId(), false);
        }

        //查询这些有权限的所有渠道账号
        if (!CollectionUtils.isEmpty(channelAccountIds)) {
            channelAccountList = accountRepository.findChannelAccountByAccountIds(channelAccountIds);
        }

        channelAccountList = this.dealWithOriginalAccount(loginAccount, channelAccountList);

        return channelAccountList;
    }

    /**
     * 填充角色名字,修改人名字,检验账户是否过期,
     */
    private List<Account> dealWithOriginalAccount(Account loginAccount, List<Account> subAccountList) {
        //设置角色名字
        if (!CollectionUtils.isEmpty(subAccountList)) {

            //账号列表
            List<Long> accountIdList = Lists.transform(subAccountList, new Function<Account, Long>() {
                @Override
                public Long apply(Account account) {
                    return account.getId();
                }
            });

            //角色列表
            List<Long> roleCategoryList = Lists.transform(subAccountList, new Function<Account, Long>() {
                @Override
                public Long apply(Account account) {
                    return account.getRoleCategory();
                }
            });

            //所有角色MAP
            List<RoleAuth> roleAuthList = roleAuthRepository.findCustomRoleList(roleCategoryList);
            Map<Long, RoleAuth> roleAuthMap = Maps.uniqueIndex(roleAuthList, new Function<RoleAuth, Long>() {
                @Override
                public Long apply(RoleAuth roleAuth) {
                    return roleAuth.getId();
                }
            });

            //所有管理账户MAP(此处作为优化,将复杂的子语句分开处理)
//            List<Account> accountList = accountRepository.findCreateAndModifyAccount(accountIdList);
            List<Long> accountIds = accountRepository.findCreateAndModifyAccountIds(accountIdList);
            List<Account> accountList = accountRepository.findAccounts(accountIds);

            Map<Long, Account> accountMap = Maps.uniqueIndex(accountList, new Function<Account, Long>() {
                @Override
                public Long apply(Account account) {
                    return account.getId();
                }
            });

            //渠道账号备注映射
            Long rootAccount = this.findRootParentAccount(loginAccount.getId()).getId();
            List<ChannelAccountMap> channelAccountMapList = channelAccountMapRepository.findAllChannelAccount(rootAccount);
            Map<Long, ChannelAccountMap> channelRemarkMap = Maps.uniqueIndex(channelAccountMapList, new Function<ChannelAccountMap, Long>() {
                @Override
                public Long apply(ChannelAccountMap channelAccountMap) {
                    return channelAccountMap.getChannelAccount();
                }
            });

            //设置名字
            for (Account account : subAccountList) {

                RoleAuth roleAuth = roleAuthMap.get(account.getRoleCategory());
                account.setRoleName(null != roleAuth ? roleAuth.getRoleName() : null);

                //创建和修改人
                Account modifyAccount = accountMap.get(account.getModifyAccount());
                Account createAccount = accountMap.get(account.getCreateAccount());
                account.setModifyAccountName(null != modifyAccount ? modifyAccount.getEmail() : null);
                account.setCreateAccountName(null != createAccount ? createAccount.getEmail() : null);

                //账户是否过期 true 有效,  false 过期
                account.setValid(true);

                //渠道账号备注
                if (RoleEnumType.CHANNEL_PERSON.getKey().equals(account.getRoleCategory()) && channelRemarkMap.containsKey(account.getId())) {
                    account.setRemark(channelRemarkMap.get(account.getId()).getRemark());
                    if (channelRemarkMap.get(account.getId()).getAuthConfig() != null)
                        account.setAuthConfig(channelRemarkMap.get(account.getId()).getAuthConfig());
                }
            }
        }

        return subAccountList;
    }

    /**
     * 启用子账号
     * created by sunhao 20170606
     */
    @Override
    public int enableSubAccountById(Account loginAccount, Long subAccountId) {
        return accountRepository.enableSubAccount(loginAccount.getId(), new Date(), subAccountId);
    }

    /**
     * 停用子账号
     * created by sunhao 20170606
     */
    @Override
    public int disableSubAccountById(Account loginAccount, Long subAccountId) {

        int affectNum = accountRepository.disableSubAccount(loginAccount.getId(), new Date(), subAccountId);

        if (affectNum > 0) {

            //禁用后踢出所有已经登陆的此子账号
            tokenManager.delMultiRelationshipByKey(subAccountId.toString());
        }

        return affectNum;
    }

    /**
     * 启用渠道账号
     */
    @Override
    public int enableChannelAccountById(Account loginAccount, Long channelAccountId) {

        List<Long> accountIds = this.getAllSubAccountList(loginAccount);

        channelAccountMapRepository.enableChannelAccount(loginAccount.getRootParent(), channelAccountId);

        return authRepository.updateStatusByCreateAccount(channelAccountId, accountIds, true);
    }

    /**
     * 停用渠道账号
     */
    @Override
    public int disableChannelAccountById(Account loginAccount, Long channelAccountId) {

        List<Long> accountIds = this.getAllSubAccountList(loginAccount);

        channelAccountMapRepository.disableChannelAccount(loginAccount.getRootParent(), channelAccountId);

        return authRepository.updateStatusByCreateAccount(channelAccountId, accountIds, false);
    }

    @Override
    public RoleAuth getRoleAuthById(Long roleId) {
        return roleAuthRepository.findOne(roleId);
    }


    /**
     * 创建渠道子账号
     * created by sunhao 20170608
     */
    @Override
    public Account createChannelAccount(Account loginAccount, Account subAccount, String lanType) {

        //是都需要邮件激活
        boolean needMail2Active = false;

        //查询渠道账号是否存在
        Account account = accountRepository.findAccountByEmail(subAccount.getEmail());

        if (null == account) {

            //渠道账号不存在
            account = this.buildAccount(loginAccount, subAccount);
            account = accountRepository.save(account);

            needMail2Active = true;

        } else if (!StringUtils.isEmpty(subAccount.getName()) && !subAccount.getName().equals(account.getName())) {
            //保存姓名
            account.setName(subAccount.getName());
            account = accountRepository.save(account);
        }

        //保存APP权限和数据权限
//        this.saveChannelAuthAndDataAuth(subAccount.getAuthList(), loginAccount, account);

        //创建渠道账号备注对应关系,设置权限配置状态为false
        this.createOrUpdateChannelRemark(loginAccount.getId(), account.getId(), subAccount.getRemark());

        if (needMail2Active) {
            //激活邮件
            this.sendSubAccountActivateEmail(loginAccount, account, lanType);
            account.setFirstSend(true);
            return account;
        } else {
            //通知邮件
            this.sendChannelAccountAuthEmail(loginAccount, account, lanType);
            return account;
        }


    }

    /**
     * 保存渠道账号的权限和数据权限
     */
    public boolean saveChannelAuthAndDataAuth(List<Auth> authList, Account loginAccount, Account channelAccount) {

        List<Auth> saveAuthList = new ArrayList<>();
        List<DataAuth> saveDataAuthList = new ArrayList<>();

        //查询这个渠道账号下的和登陆账号有关联的账号给此渠道账号的授权。
        List<Long> allAccount = this.getAllSubAccountList(loginAccount);
        List<Auth> oldAuthList = authRepository.findAuthByCreateAccount(allAccount, channelAccount.getId());
        List<DataAuth> oldDataAuthList = dataAuthRepository.findDataAuthByCreateAccount(allAccount, channelAccount.getId());

        if (!CollectionUtils.isEmpty(authList)) {
            //删除老权限
            authRepository.delete(oldAuthList);
//            dataAuthRepository.delete(oldDataAuthList);
        }
        this.saveDataAuthPkgsubcampaign(loginAccount, channelAccount);
        //新权限加入。
        for (Auth auth : authList) {
            //构建数据权限
            saveDataAuthList.addAll(this.getDataAuthByAuth(channelAccount.getId(), auth));
            //构建auth权限
            List<RoleAuthDetail> roleAuthDetailList = auth.getRoleAuthDetailList();
            Auth saveAuth = this.buildAuth(auth, channelAccount, loginAccount.getId(), roleAuthDetailList);

            saveAuthList.add(saveAuth);
        }

        if (!CollectionUtils.isEmpty(saveAuthList)) {
            authRepository.save(saveAuthList);
        }

        saveNewOnlyDataAuth(saveDataAuthList, oldDataAuthList);


        //修改对应关系表中,配置权限的状态为true
        Long rootAccountId = loginAccount.getRootParent();
        ChannelAccountMap channelAccountMap = channelAccountMapRepository.findAccount(rootAccountId, channelAccount.getId());
        channelAccountMap.setAuthConfig(true);
        channelAccountMapRepository.save(channelAccountMap);

        return true;
    }


    /**
     * 保存新增的权限  删除取消的老权限
     *
     * @param saveDataAuthList
     * @param oldDataAuthList
     */
    public void saveNewOnlyDataAuth(List<DataAuth> saveDataAuthList, List<DataAuth> oldDataAuthList) {
        //处理老权限
        List<DataAuth> shouldSaveList = new ArrayList();
        List<DataAuth> shouldDelList = new ArrayList();

        if (oldDataAuthList == null) {
            oldDataAuthList = new ArrayList<>();
        }

        //删除部分老权限  保存新增权限
        Map<String, DataAuth> saveDataAuthMap = saveDataAuthList.stream().collect(Collectors.toMap(
                k -> k.getApp() + "_" + k.getCampaign() + "_" + k.getChannel() + "_" + k.getAccount()
                        + "_" + ((k.getChannelPermit() == null || k.getChannelPermit()) ? 1 : 0)
                        + "_" + ((k.getAllCampaign() == null || k.getAllCampaign()) ? 1 : 0),
                java.util.function.Function.identity(), (k1, k2) -> k2));


        Map<String, DataAuth> oldDataAuthMap = oldDataAuthList.stream().collect(Collectors.toMap(
                k -> k.getApp() + "_" + k.getCampaign() + "_" + k.getChannel() + "_" + k.getAccount()
                        + "_" + ((k.getChannelPermit() == null || k.getChannelPermit()) ? 1 : 0)
                        + "_" + ((k.getAllCampaign() == null || k.getAllCampaign()) ? 1 : 0),
                java.util.function.Function.identity(), (k1, k2) -> k2
        ));


        for (DataAuth dataAuth : saveDataAuthList) {
            if (oldDataAuthMap.get(dataAuth.getApp() + "_" + dataAuth.getCampaign() + "_" + dataAuth.getChannel() + "_" + dataAuth.getAccount()
                    + "_" + ((dataAuth.getChannelPermit() == null || dataAuth.getChannelPermit()) ? 1 : 0)
                    + "_" + ((dataAuth.getAllCampaign() == null || dataAuth.getAllCampaign()) ? 1 : 0)) == null) {
                shouldSaveList.add(dataAuth);
            }
        }

        for (DataAuth dataAuth : oldDataAuthList) {
            if (saveDataAuthMap.get(dataAuth.getApp() + "_" + dataAuth.getCampaign() + "_" + dataAuth.getChannel() + "_" + dataAuth.getAccount()
                    + "_" + ((dataAuth.getChannelPermit() == null || dataAuth.getChannelPermit()) ? 1 : 0)
                    + "_" + ((dataAuth.getAllCampaign() == null || dataAuth.getAllCampaign()) ? 1 : 0)) == null) {
                shouldDelList.add(dataAuth);
            }
        }

//        if (!CollectionUtils.isEmpty(saveDataAuthList)) {
//            dataAuthRepository.save(saveDataAuthList);
//        }

        if (!CollectionUtils.isEmpty(shouldSaveList)) {
            dataAuthRepository.save(shouldSaveList);
        }

        if (!CollectionUtils.isEmpty(shouldDelList)) {
            dataAuthRepository.delete(shouldDelList);
        }
    }


    /**
     * 修改渠道账号,无法修改渠道账号的名称。编辑账号的时候,不涉及权限修改03-01,zxy
     * created by sunhao 20170612
     */
    @Override
    public Account modifyChannelAccount(Account loginAccount, Account subAccount) {

        Account account = accountRepository.findAccountByEmail(subAccount.getEmail());

        logger.info(entityManager.contains(account) + "");

        if (null != account && account.getRoleCategory().equals(RoleEnumType.CHANNEL_PERSON.getKey())) {

            //如果渠道账号姓名为空,则更新渠道账号名字
            if (StringUtils.isEmpty(account.getName()) && !StringUtils.isEmpty(subAccount.getName())) {
                account.setName(subAccount.getName());
            }

            //更新时间
            account.setModifyAccount(loginAccount.getId());
            account.setModifyTime(new Date());
            account.setRemark(subAccount.getRemark());
            accountRepository.save(account);

            //更新备注
            Long rootAccount = this.findRootParentAccount(loginAccount.getId()).getId();
            ChannelAccountMap accountMap = channelAccountMapRepository.findAccount(rootAccount, account.getId());
            accountMap.setRemark(account.getRemark());
            channelAccountMapRepository.save(accountMap);

        }

        return account;
    }

    /**
     * 创建子账号,渠道账号
     * created by sunhao 20170607
     */
    @Override
    public Account createSubAccount(Account loginAccount, Account subAccount, RoleAuth roleAuth, String lanType) {

        //新建账号 account  渠道账号
        Account saveAccount = this.buildAccount(loginAccount, subAccount);
        //新创建的账号(除去管理员,管理员不需要配置权限),还没有配置权限
        if (!subAccount.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())) {
            saveAccount.setAuthConfig(false);
        }

        saveAccount = accountRepository.save(saveAccount);

        //构建权限 auth  权限配置和账号创建分开  03-01,zxy
//        this.saveAuthAndDataAuth(subAccount.getAuthList(), roleAuth, saveAccount, loginAccount.getId());

        this.sendSubAccountActivateEmail(loginAccount, saveAccount, lanType);


        return saveAccount;
    }

    /**
     * 构建数据和菜单权限
     */
    @Override
    public boolean saveAuthAndDataAuth(List<Auth> authList, RoleAuth roleAuth, Account saveAccount, Long loginAccountId, List<DataAuth> dataAuthList) {

        List<Auth> saveAuthList = new ArrayList<>();
        List<DataAuth> saveDataAuthList = new ArrayList<>();

        if (roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {

            //2,子应用管理员,创建auth 无需创建data_auth ;无需control_auth字段数据
            for (Auth auth : authList) {
                //默认设置
                auth.setIsNatureOpen(true);
                auth.setRetentionAuth(true);
                auth.setTopAuth(true);
                auth.setCampaign(true);
                auth.setOrderAuth(true);
                auth.setArouseAuth(true);
                Auth saveAuth = this.buildAuth(auth, saveAccount, loginAccountId, null);
                saveAuthList.add(saveAuth);
            }

        } else if (roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_AUTH.getKey())) {

            //3,自定义,创建auth和data_auth
            for (Auth auth : authList) {
                //构建数据权限
                saveDataAuthList.addAll(this.getDataAuthByAuth(saveAccount.getId(), auth));
                //构建auth权限
                List<RoleAuthDetail> roleAuthDetailList = auth.getRoleAuthDetailList();
                Auth saveAuth = this.buildAuth(auth, saveAccount, loginAccountId, roleAuthDetailList);
                saveAuthList.add(saveAuth);
            }

        } else if (roleAuth.getRoleCategory().equals(RoleEnumType.CUSTOM_ROLE.getKey())) {

            //5,选定的自定义角色,创建auth ,创建data_auth ;
            List<RoleAuthDetail> roleAuthDetailList = roleAuthDetailRepository.findValidDetailByRole(roleAuth.getId());

            for (Auth auth : authList) {
                //构建数据权限
                saveDataAuthList.addAll(this.getDataAuthByAuth(saveAccount.getId(), auth));

                //自定义角色设置
                auth.setPayAuth(roleAuth.getPayAuth());
                auth.setIsNatureOpen(roleAuth.getIsNatureOpen());
                auth.setRetentionAuth(roleAuth.getRetentionAuth());
                auth.setTopAuth(roleAuth.getTopAuth());
                auth.setOrderAuth(roleAuth.getOrderAuth());
                auth.setArouseAuth(roleAuth.getArouseAuth());
                auth.setEventAuth(roleAuth.getEventAuth());
                //构建auth权限
                Auth saveAuth = this.buildAuth(auth, saveAccount, loginAccountId, roleAuthDetailList);
                saveAuthList.add(saveAuth);
            }

        }

        //保存 auth
        if (!CollectionUtils.isEmpty(saveAuthList)) {
            authRepository.save(saveAuthList);
        }
//        //保存 data_auth
//        if (!CollectionUtils.isEmpty(saveDataAuthList)) {
//            dataAuthRepository.save(saveDataAuthList);
//        }


        //仅保存本次新增权限,删除取消掉的权限
        saveNewOnlyDataAuth(saveDataAuthList, dataAuthList);

        Account accountNew = accountRepository.findOne(saveAccount.getId());
        //保存完权限之后,更新账号权限配置状态为true
        accountNew.setAuthConfig(true);
        accountNew.setRoleCategory(saveAccount.getRoleCategory());
        accountRepository.save(accountNew);
        return true;
    }

    /**
     * 菜单权限转换
     */
    private JSONArray parseAuth2JsonArray(List<RoleAuthDetail> roleAuthDetailList) {

        JSONArray authArray = new JSONArray();

        if (!CollectionUtils.isEmpty(roleAuthDetailList)) {

            for (RoleAuthDetail roleAuthDetail : roleAuthDetailList) {

                JSONObject authObject = new JSONObject();
                authObject.put("auth", roleAuthDetail.getAuth());
                authObject.put("view", roleAuthDetail.getView());
                authObject.put("edit", roleAuthDetail.getEdit());
                authObject.put("sort", roleAuthDetail.getSort());
                authObject.put("parentAuth", roleAuthDetail.getParentAuth());

                authArray.add(authObject);
            }
        }

        return authArray;
    }

    /**
     * 构建Auth
     */
    private Auth buildAuth(Auth auth, Account subAccount, Long createAccount, List<RoleAuthDetail> roleAuthDetailList) {

        Auth saveAuth = new Auth();

        Date operateDate = new Date();

        saveAuth.setApp(auth.getApp());
        saveAuth.setAccount(subAccount.getId());
        saveAuth.setRoleCategory(subAccount.getRoleCategory());
        saveAuth.setControlAuth(this.parseAuth2JsonArray(roleAuthDetailList).toString());
        saveAuth.setModifyTime(operateDate);
        saveAuth.setModifyAccount(createAccount.toString());
        saveAuth.setCreateAccount(null != auth.getCreateAccount() ? auth.getCreateAccount() : createAccount);
        saveAuth.setCreateTime(null != auth.getCreateTime() ? auth.getCreateTime() : operateDate);
        saveAuth.setStatus(true);
        //付费,留存,自然量,Top指标,订单,调起,自定义事件
        saveAuth.setPayAuth(auth.isPayAuth());
        saveAuth.setIsNatureOpen(auth.getIsNatureOpen());
        saveAuth.setRetentionAuth(auth.isRetentionAuth());
        saveAuth.setTopAuth(auth.getTopAuth());
        saveAuth.setOrderAuth(auth.getOrderAuth());
        saveAuth.setArouseAuth(auth.getArouseAuth());
        saveAuth.setEventAuth(auth.getEventAuth());
        return saveAuth;
    }

    /**
     * 构建Account
     */
    private Account buildAccount(Account loginAccount, Account subAccount) {

        Account account = new Account();

        account.setName(subAccount.getName());
        account.setCompany(loginAccount.getCompany());
        account.setCreateTime(new Date());
        account.setDelFlag(false);
        account.setCreateAccount(loginAccount.getId());
        account.setModifyAccount(loginAccount.getId());
        account.setModifyTime(new Date());
        account.setEmail(subAccount.getEmail());
        account.setIsChannelPerson(false);
        account.setIsSuperUser(false);
        account.setIsChannelPerson(subAccount.getRoleCategory().equals(RoleEnumType.CHANNEL_PERSON.getKey()));
        //未激活,需要发送邮件后激活
        account.setStatus(-3);
        account.setPricelevel(loginAccount.getPricelevel());
        account.setParent(loginAccount.getId());
        //根节点账号,取登陆账号的rootParent
        account.setRootParent(loginAccount.getRootParent());
        account.setPastDate(loginAccount.getPastDate());
        account.setRoleCategory(subAccount.getRoleCategory());
        account.setRemark(subAccount.getRemark());

        return account;
    }

    /**
     * 构建数据权限data_auth
     */
    private List<DataAuth> getDataAuthByAuth(Long subAccountId, Auth auth) {

        List<DataAuth> result = new ArrayList<>();

        //渠道和活动列表
        List<DataAuth> dataAuthList = auth.getDataAuth();

        for (DataAuth dataAuthTemp : dataAuthList) {

            //校验channel和campaign
            Long channelId = dataAuthTemp.getChannel();
            List<Long> campaignList = dataAuthTemp.getCampaignList();

            //构建data_auth
            if (null != channelId) {
                if (dataAuthTemp.getAllCampaign()) {
                    //按渠道授权
                    DataAuth dataAuth = this.buildDataAuth(subAccountId, auth.getApp(), channelId, null);
                    result.add(dataAuth);

                } else {
                    Boolean flag;
                    if (dataAuthTemp.getChannelPermit() == null) {
                        flag = false;
                    } else {
                        flag = dataAuthTemp.getChannelPermit();
                    }
                    if (!CollectionUtils.isEmpty(campaignList)) {
                        //按照渠道和推广活动授权
                        for (Long campaignId : campaignList) {
                            DataAuth dataAuth = this.buildDataAuth(subAccountId, auth.getApp(), channelId, campaignId);
                            dataAuth.setChannelPermit(flag);

                            result.add(dataAuth);
                        }
                    } else {
                        if (flag) {//改成新版的只按渠道授权
                            DataAuth dataAuth = this.buildDataAuth(subAccountId, auth.getApp(), channelId, null);

                            dataAuth.setChannelPermit(flag);
                            dataAuth.setAllCampaign(false);//非第一种全选按渠道授权
                            result.add(dataAuth);
                        } else if (!CollectionUtils.isEmpty(dataAuthTemp.getPkgsubcampaign())) {
                            DataAuth dataAuth = this.buildDataAuth(subAccountId, auth.getApp(), channelId, null);
                            dataAuth.setChannelPermit(flag);
                            dataAuth.setAllCampaign(false);
                            result.add(dataAuth);
                        }
                    }
                }
            }
        }

        return result;
    }

    /**
     * 构建Data_Auth
     */
    private DataAuth buildDataAuth(Long accountId, Long appId, Long channelId, Long campaignId) {

        DataAuth dataAuth = new DataAuth();

        dataAuth.setAccount(accountId);
        dataAuth.setApp(appId);
        dataAuth.setChannel(channelId);
        dataAuth.setCampaign(null == campaignId ? 0L : campaignId);
        dataAuth.setModifyTime(new Date());
        dataAuth.setAllCampaign(null == campaignId);
        dataAuth.setDelFlag(false);

        return dataAuth;
    }

    /**
     * 修改子账户信息
     * create by sunhao 20170609
     */
    @Override
    public Account modifySubAccount(Account loginAccount, Account subAccount, RoleAuth roleAuth) {

        Account account = accountRepository.findOne(subAccount.getId());

        boolean isRoleChange = !account.getRoleCategory().equals(subAccount.getRoleCategory());


        //3,更新基本信息,激活之前,email可修改 03-01,zxy
        account.setEmail(subAccount.getEmail());
        account.setName(subAccount.getName());
        account.setRoleCategory(subAccount.getRoleCategory());
        account.setRemark(subAccount.getRemark());

        account.setModifyTime(new Date());
        account.setModifyAccount(loginAccount.getId());

        if (isRoleChange) {
            account.setAuthConfig(false);
        }
        accountRepository.save(account);

        //删除来源分析显示的列数据,判断角色发生变化时候再删除03-01,zxy
        if (isRoleChange) {
            List<UserViewColumn> userViewColumn = userViewColumnRepository.findByAccount(account.getId());
            if (null != userViewColumn && userViewColumn.size() > 0) {
                userViewColumnRepository.delete(userViewColumn);
            }

            //1,删除旧权限,渠道账号的不在这里操作
            List<Auth> authList = authRepository.findAuthByAccountId(subAccount.getId());
            List<DataAuth> dataAuthList = dataAuthRepository.findDataAuthByAccount(subAccount.getId());

            if (!CollectionUtils.isEmpty(authList)) {
                authRepository.delete(authList);
            }

            if (!CollectionUtils.isEmpty(authList)) {
                dataAuthRepository.delete(dataAuthList);
            }
        }

        return account;
    }

    /**
     * 修改子账户信息
     * create by sunhao 20170609
     */
    @Override
    public boolean modifySubAccountAuth(Account loginAccount, Account subAccount, RoleAuth roleAuth) {

        List<DataAuth> dataAuthList = null;
        if (subAccount.getAuthConfig() == null || subAccount.getAuthConfig()) {
            //1,删除旧权限,渠道账号的不在这里操作
            List<Auth> authList = authRepository.findAuthByAccountId(subAccount.getId());
            long st = System.currentTimeMillis();
            dataAuthList = dataAuthRepository.findDataAuthByAccount(subAccount.getId());
            logger.info("获取data_auth用时{}", (System.currentTimeMillis() - st) / 1000);
//            String sql = "select * from data_auth where account =" + subAccount.getId();
//            RowMapper<DataAuth> rowMapper = new BeanPropertyRowMapper<DataAuth>(DataAuth.class);
//            List<DataAuth> users = jdbcTemplate.query(sql, rowMapper);

            if (!CollectionUtils.isEmpty(authList)) {
                authRepository.delete(authList);
            }
            this.saveDataAuthPkgsubcampaign(loginAccount, subAccount);

//            if (!CollectionUtils.isEmpty(authList)) {
//                dataAuthRepository.delete(dataAuthList);
//            }
        }


        //2,保存新权限
        boolean result = this.saveAuthAndDataAuth(subAccount.getAuthList(), roleAuth, subAccount, loginAccount.getId(), dataAuthList);
        return result;
    }

    public void saveDataAuthPkgsubcampaign(Account loginAccount, Account subAccount) {
        dataAuthPkgsubcampaignRepository.delByAccount(subAccount.getId());
        List<Auth> authList = subAccount.getAuthList();
        List<DataAuthPkgsubcampaign> pkgs = new ArrayList<>();
        if (!CollectionUtils.isEmpty(authList)) {
            for (Auth auth : authList) {
                List<DataAuth> dataAuths = auth.getDataAuth();
                if (!CollectionUtils.isEmpty(dataAuths)) {
                    for (DataAuth dataAuth : dataAuths) {
                        Map<String, List<String>> pkgsubcampaignMap = dataAuth.getPkgsubcampaign();
                        if (!CollectionUtils.isEmpty(pkgsubcampaignMap)) {
                            for (String campaign : pkgsubcampaignMap.keySet()) {
                                List<String> pkgCampaigns = pkgsubcampaignMap.get(campaign);
                                if (!CollectionUtils.isEmpty(pkgCampaigns)) {
                                    for (String pkgCampaign : pkgCampaigns) {
                                        DataAuthPkgsubcampaign dataAuthPkgsubcampaign = new DataAuthPkgsubcampaign();
                                        dataAuthPkgsubcampaign.setAccount(subAccount.getId());
                                        dataAuthPkgsubcampaign.setApp(auth.getApp());
                                        dataAuthPkgsubcampaign.setCampaign(Long.valueOf(campaign));
                                        dataAuthPkgsubcampaign.setChannel(dataAuth.getChannel());
                                        dataAuthPkgsubcampaign.setModifyAccount(loginAccount.getId());
                                        dataAuthPkgsubcampaign.setPkgSubCampaign(Long.valueOf(pkgCampaign));
                                        pkgs.add(dataAuthPkgsubcampaign);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (pkgs.size() > 0) {
            dataAuthPkgsubcampaignRepository.save(pkgs);
        }
    }

    @Override
    public int updateAuthConfig(Long id, Boolean status) {
        return accountRepository.updateAuthConfig(id, status);
    }

    @Override
    public boolean isNeedAuthConfig(Long roleCategory) {
        return roleCategory.equals(RoleEnumType.CUSTOM_AUTH.getKey()) || roleCategory.equals(RoleEnumType.CHANNEL_PERSON.getKey());
    }

    /**
     * 创建自定义角色
     * create by sunhao 20170607
     */
    @Override
    public RoleAuth createCustomRole(Account loginAccount, RoleAuth roleAuth) {

        RoleAuth saveRoleAuth = new RoleAuth();

        //创建并保存 ROLE_AUTH
        saveRoleAuth.setCreateAccount(loginAccount.getId());
        saveRoleAuth.setRoleName(roleAuth.getRoleName());
        saveRoleAuth.setCreateTime(new Date());
        saveRoleAuth.setRoleCategory(RoleEnumType.CUSTOM_ROLE.getKey());
        saveRoleAuth.setDelFlag(false);
        saveRoleAuth.setPayAuth(roleAuth.getPayAuth());
        saveRoleAuth.setRetentionAuth(roleAuth.getRetentionAuth());
        saveRoleAuth.setIsNatureOpen(roleAuth.getIsNatureOpen());
        saveRoleAuth.setTopAuth(roleAuth.getTopAuth());
        saveRoleAuth.setOrderAuth(roleAuth.getOrderAuth());
        saveRoleAuth.setArouseAuth(roleAuth.getArouseAuth());
        saveRoleAuth.setEventAuth(roleAuth.getEventAuth());
        saveRoleAuth = roleAuthRepository.save(saveRoleAuth);

        //构建 ROLE_AUTH_DETAIL,全量detail
        List<RoleAuthDetail> roleAuthDetailList = this.getInitRoleAuthList();

        Map<String, RoleAuthDetail> roleAuthDetailMap = Maps.uniqueIndex(roleAuth.getRoleAuthDetails(), new Function<RoleAuthDetail, String>() {
            @Override
            public String apply(RoleAuthDetail roleAuthDetail) {
                return roleAuthDetail.getAuth();
            }
        });

        //构建选中信息
        for (RoleAuthDetail roleAuthDetail : roleAuthDetailList) {
            RoleAuthDetail newRoleAuthDetail = roleAuthDetailMap.get(roleAuthDetail.getAuth());

            if (null != newRoleAuthDetail) {
                roleAuthDetail.setEdit(newRoleAuthDetail.getEdit());
                roleAuthDetail.setView(newRoleAuthDetail.getView());
            }

            roleAuthDetail.setRoleId(saveRoleAuth.getId());
        }

        //保存 ROLE_AUTH_DETAIL
        roleAuthDetailRepository.save(roleAuthDetailList);

        return saveRoleAuth;
    }

    /**
     * 获取全部未选中的所有的菜单权限MAP,
     */
    private Map<String, RoleAuthDetail> getAllRoleAuthMap() {
        return getRoleAuthMapByRoleType(RoleEnumType.CUSTOM_AUTH.getKey());
    }

    /**
     * 获取渠道账号全部的菜单权限MAP,
     */
    private Map<String, RoleAuthDetail> getChannelAccountRoleAuthMap() {
        return getRoleAuthMapByRoleType(RoleEnumType.CHANNEL_PERSON.getKey());
    }

    /**
     * 获取全部未选中的所有的菜单权限MAP,
     */
    private Map<String, RoleAuthDetail> getRoleAuthMapByRoleType(Long roleType) {

        Map<String, RoleAuthDetail> result = new HashMap<>();

        List<RoleAuthDetail> roleAuthDetailList = roleAuthDetailRepository.findDetailByRole(roleType);

        for (RoleAuthDetail roleAuthDetail : roleAuthDetailList) {
            result.put(roleAuthDetail.getAuth(), new RoleAuthDetail(roleAuthDetail));
        }

        return result;
    }

    /**
     * 获取全部未选中的所有的菜单权限LIST,
     */
    private List<RoleAuthDetail> getInitRoleAuthList() {

        List<RoleAuthDetail> result = new ArrayList<>();

        List<RoleAuthDetail> roleAuthDetailList = roleAuthDetailRepository.findDetailByRole(RoleEnumType.CUSTOM_AUTH.getKey());

        for (RoleAuthDetail roleAuthDetail : roleAuthDetailList) {
            result.add(new RoleAuthDetail(roleAuthDetail));
        }

        return result;
    }


    /**
     * 修改自定义角色,参数只传了选中的权限
     * created by sunhao 20170609
     */
    @Override
    public RoleAuth modifyCustomRole(Account loginAccount, RoleAuth roleAuth) {

        //修改保存基础信息
        RoleAuth customRoleAuth = roleAuthRepository.findOne(roleAuth.getId());
        customRoleAuth.setRoleName(!StringUtils.isEmpty(roleAuth.getRoleName()) ? roleAuth.getRoleName() : customRoleAuth.getRoleName());
        customRoleAuth.setPayAuth(null != roleAuth.getPayAuth() ? roleAuth.getPayAuth() : customRoleAuth.getPayAuth());
        customRoleAuth.setRetentionAuth(null != roleAuth.getRetentionAuth() ? roleAuth.getRetentionAuth() : customRoleAuth.getRetentionAuth());
        customRoleAuth.setIsNatureOpen(null != roleAuth.getIsNatureOpen() ? roleAuth.getIsNatureOpen() : customRoleAuth.getIsNatureOpen());
        customRoleAuth.setTopAuth(null != roleAuth.getTopAuth() ? roleAuth.getTopAuth() : customRoleAuth.getTopAuth());
        customRoleAuth.setOrderAuth(null != roleAuth.getOrderAuth() ? roleAuth.getOrderAuth() : customRoleAuth.getOrderAuth());
        customRoleAuth.setArouseAuth(null != roleAuth.getArouseAuth() ? roleAuth.getArouseAuth() : customRoleAuth.getArouseAuth());
        customRoleAuth.setEventAuth(null != roleAuth.getEventAuth() ? roleAuth.getEventAuth() : customRoleAuth.getEventAuth());
        customRoleAuth.setModifyTime(new Date());
        customRoleAuth.setModifyAccount(loginAccount.getId());

        customRoleAuth = roleAuthRepository.save(customRoleAuth);

        //原始权限
        List<RoleAuthDetail> customRoleAuthDetailList = roleAuthDetailRepository.findDetailByRole(roleAuth.getId());

        //新权限
        List<RoleAuthDetail> sourceRoleAuthDetailList = roleAuth.getRoleAuthDetails();
        Map<String, RoleAuthDetail> sourceRoleAuthDetailMap = Maps.uniqueIndex(sourceRoleAuthDetailList, new Function<RoleAuthDetail, String>() {
            @Override
            public String apply(RoleAuthDetail roleAuthDetail) {
                return roleAuthDetail.getAuth();
            }
        });

        for (RoleAuthDetail oldRoleAuthDetail : customRoleAuthDetailList) {

            RoleAuthDetail newRoleAuthDetail = sourceRoleAuthDetailMap.get(oldRoleAuthDetail.getAuth());

            if (null != newRoleAuthDetail) {
                //修改
                oldRoleAuthDetail.setView(newRoleAuthDetail.getView());
                oldRoleAuthDetail.setEdit(newRoleAuthDetail.getEdit());

            } else {
                //初始化
                oldRoleAuthDetail.setEdit(false);
                oldRoleAuthDetail.setView(false);
            }
        }

        //保存
        roleAuthDetailRepository.save(customRoleAuthDetailList);

        //修改相应自定义角色的权限
        this.updateCustomRoleAuthByRoleId(roleAuth.getRoleAuthDetails(), customRoleAuth);

        return customRoleAuth;
    }

    /**
     * 批量更新相应自定义角色的权限
     */
    private void updateCustomRoleAuthByRoleId(List<RoleAuthDetail> roleAuthDetailList, RoleAuth customRoleAuth) {

        List<Auth> authList = authRepository.findAuthByRoleCategory(customRoleAuth.getId());

        for (Auth auth : authList) {
            auth.setControlAuth(parseAuth2JsonArray(roleAuthDetailList).toString());
            auth.setPayAuth(customRoleAuth.getPayAuth());
            auth.setRetentionAuth(customRoleAuth.getRetentionAuth());
            auth.setIsNatureOpen(customRoleAuth.getIsNatureOpen());
            auth.setTopAuth(customRoleAuth.getTopAuth());
            auth.setOrderAuth(customRoleAuth.getOrderAuth());
            auth.setEventAuth(customRoleAuth.getEventAuth());
        }

        authRepository.save(authList);
    }

    /**
     * 删除自定义角色
     * created by sunhao 20170609
     */
    @Override
    public int deleteCustomRole(Account loginAccount, Long roleId) {

        return roleAuthRepository.deleteCustomRole(roleId, loginAccount.getId(), new Date());
    }

    /**
     * 删除未激活的子账号
     * created by sunhao 20170609
     */
    @Override
    public boolean deleteInactivateSubAccount(Long subAccountId) {

        Account account = accountRepository.findOne(subAccountId);

        if (account.getStatus() == -3) {

            //删除账户
            accountRepository.delete(account);

            //删除权限
            authRepository.deleteAuthByAccount(subAccountId);
            dataAuthRepository.deleteAuthByAccount(subAccountId);

            return true;
        }

        return false;
    }

    /**
     * 校验自定义权限名称是否重复,true:重复,false:没重复
     * create by sunhao 20170608
     */
    @Override
    public boolean checkCustomRoleName(Account loginAccount, String roleName, Long roleId) {

        boolean result = false;

        //如果检查编辑角色的名字,查看名字是否和之前一样,不一样就按原逻辑检查,一样就直接返回false
        if (null != roleId) {

            RoleAuth roleAuth = roleAuthRepository.findOne(roleId);
            if (!roleAuth.getRoleName().equals(roleName)) {
                roleId = null;
            }
        }

        //检查名字
        if (null == roleId) {

            List<Long> subAccountList = this.getAllSubAccountList(loginAccount);

            BigInteger number = roleAuthRepository.findByAccountAndName(subAccountList, roleName);

            result = null != number && number.intValue() > 0;

        }

        return result;
    }

    /**
     * 校验自定义权限的数量,true:超过,false:没超过
     * create by sunhao 20170608
     */
    @Override
    public boolean checkCustomRoleNumber(Account loginAccount) {

        List<Long> subAccountList = this.getAllSubAccountList(loginAccount);

        BigInteger number = roleAuthRepository.findCustomNumByAccount(subAccountList);

        return null != number && number.intValue() >= MAX_CUSTOM_ROLE_NUM;
    }

    /**
     * 校验已开启子管理员的数量 true:超过,false:没超过
     * create by sunhao 20170608
     * update by zhangyao  2018-11-19   管理员数量可以根据数据库中的mng_count判断最高数量
     */
    @Override
    public boolean checkSubMangerNumber(Account loginAccount) {

        BigInteger number = accountRepository.findSubMangerNumByParent2(loginAccount.getIsSuperUser() ? loginAccount.getId() : loginAccount.getParent());
        return number != null && number.intValue() >= accountRepository.checkMngCount(loginAccount.getIsSuperUser() ? loginAccount.getId() : loginAccount.getParent());
    }

    @Override
    public boolean checkUpdateSubMangerNumber(Account loginAccount, Account updateAccount) {

        Account originalAccount = accountRepository.findOne(updateAccount.getId());

        if (!originalAccount.getRoleCategory().equals(updateAccount.getRoleCategory()) && RoleEnumType.MANAGER.getKey().equals(updateAccount.getRoleCategory())) {

            return this.checkSubMangerNumber(loginAccount);

        } else {
            return false;
        }
    }

    /**
     * 校验Email存在,true:存在,false:不存在
     * create by sunhao 20170616
     */
    @Override
    public boolean checkEmailExists(String email) {

        Account account = accountRepository.findAccountByEmail(email);

        return null != account;
    }

    @Override
    public boolean checkChannelEmailExists(String email) {

        Account account = accountRepository.findAccountByEmail(email);
        if (null != account && account.getRoleCategory().equals(RoleEnumType.CHANNEL_PERSON.getKey())) {
            return true;
        } else if (null == account) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 校验此角色下面有无子账号 true:有,false:没有
     * created by sunhao 20170609
     */
    @Override
    public List<String> checkCustomRoleAccount(Long roleId) {

        List<String> result = accountRepository.findAccountByRoleId(roleId);
        return result;
    }

    /**
     * 根据账户和APP获取权限数据
     */
    @Override
    public Auth findAuth(Long account, Long app) {
        return authRepository.findAuthByAccountAndApp(account, app);
    }

    /**
     * 是否包含自然量
     * modify by sunhao 20170613
     */
    @Override
    public boolean isNature(Long accountId, Long app) {

        boolean isNatureOpen = true;

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

        //不是管理员且不是应用管理员的时候,通过auth判断
        if (!account.getIsSuperUser() && null != roleAuth && !roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                && !roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {

            Auth auth = this.findAuth(accountId, app);
            isNatureOpen = auth != null && auth.getIsNatureOpen();
        }

        return isNatureOpen;
    }

    /**
     * 查询子账号的根节点母账号
     */
    @Override
    public Account findRootParentAccount(Long childAccountId) {

        Account account = accountRepository.findOne(childAccountId);

        while (null != account.getParent() && 0 != account.getParent()) {

            account = accountRepository.findOne(account.getParent());
        }

        return account;
    }

    /**
     * 校验母账号是否过期
     */
    @Override
    public boolean isOriginAccountPast(Long account) {

        Account accountObject = accountRepository.findOne(account);

        String nowDate = DateUtil.format(new Date(), DateUtil.C_DATE_PATTON_DEFAULT);

        return !StringUtil.isEmpty(accountObject.getPastDate()) && DateUtil.compare_date(nowDate, accountObject.getPastDate()) == 1;
    }

    @Override
    public Account check(String email) {
        return accountRepository.findAccountByEmail(email);
    }


    /**
     * 查询账号下面所有的渠道ID
     */
    @Override
    public List<Long> getAuthChannelList(Long accountId) {

        List<Long> result = new ArrayList<>();

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());


        //母账号,管理员,子应用管理员。合作渠道和创建的所有自定义渠道
        if (account.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())) {

            //合作渠道
            List<Channel> coopChannelList = channelRepository.findCoopIdChannel();
            result.addAll(this.transformChannelToChannelId(coopChannelList));

            //自己以及所属子账号创建的自定义渠道
            List<Channel> createChannelList = account.getIsSuperUser() ? channelRepository.listAllByMainAccount(account.getId())
                    : channelRepository.listAllByManager(account.getId(), account.getParent());
            result.addAll(this.transformChannelToChannelId(createChannelList));

        } else {

            //自定义角色,自定义权限,渠道账号。授权的渠道权限
            List<Channel> authorizedChannelList = channelRepository.listChannelIdByDataAuth(accountId);
            result.addAll(this.transformChannelToChannelId(authorizedChannelList));

            //自己创建的渠道
            List<Channel> createdChannelList = channelRepository.listOwnChannelByAccount(accountId);
            result.addAll(this.transformChannelToChannelId(createdChannelList));

        }

        return result;
    }

    private List<Long> transformChannelToChannelId(List<Channel> channelList) {

        List<Long> result = new ArrayList<>();

        if (!CollectionUtils.isEmpty(channelList)) {
            result = Lists.transform(channelList, new Function<Channel, Long>() {
                @Override
                public Long apply(Channel channel) {
                    return channel.getId();
                }
            });
        }

        return result;
    }

    @Override
    public List<Channel> getAuthChannelListByAppIngnorDel(Long accountId, Long appId) {

        return getAuthChannelListByApp(accountId, appId, true);
    }

    @Override
    public List<String> getAuthCampaignIdListByAccount(Long accountId, Long appId) {
        return getAuthCampaignListIdByAccount(accountId, appId, false);
    }

    @Override
    public List<String> getAuthCampaignIdListByAccount(Long accountId, Long appId, int type) {

        return getAuthCampaignListIdByAccount(accountId, appId, true);
    }

    private List<String> getAuthCampaignListIdByAccount(Long accountId, Long appId, boolean forReport) {
        List<String> resultList = new ArrayList<>();

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());


        if (account.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || (account.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey()) && null != authRepository.findAuthByAccountAndApp(account.getId(), appId))) {

            //母账号,管理员,有此权限的子应用管理员
            resultList.addAll(this.campaignRepository.findAllCampaignIdsByApp(appId));

        } else {

            resultList = ChannelPersionAuth(accountId, appId);

        }

        return resultList;
    }

    private List<String> ChannelPersionAuth(Long accountId, Long appId) {

        List<String> resultList = new ArrayList<>();

        //自定义角色,渠道账号,授权+自己创建
        Auth auth = this.findAuth(accountId, appId);

        if (null != auth) {

            //自己创建的活动
            List<String> campaignIdList = campaignRepository.findCampaignIdsByAccountApp(accountId, appId);

            if (!CollectionUtils.isEmpty(campaignIdList)) {
                resultList.addAll(campaignIdList);
            }

            //授权的活动
            List<String> dataAuthCampaignIdListWithoutCreate = campaignRepository.findDataAuthCampaignIdListWithoutCreate(accountId, appId);

            if (!CollectionUtils.isEmpty(dataAuthCampaignIdListWithoutCreate)) {
                resultList.addAll(dataAuthCampaignIdListWithoutCreate);
            }

        }

        return resultList;
    }


    @Override
    public List<Object[]> getCampaignIdsByAuth(Account accountnew, App app) {
        Account account = accountRepository.findOne(accountnew.getId());
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

        if (account.getIsSuperUser()
                || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || (account.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey())
                && null != authRepository.findAuthByAccountAndApp(account.getId(), app.getId()))) {
            return new ArrayList<>();

        } else {
            List<Object[]> resultList = new ArrayList<>();

            Long accountId = account.getId();
            Long appId = app.getId();

            //自定义角色,渠道账号,授权+自己创建
            Auth auth = this.findAuth(accountnew.getId(), app.getId());

            if (null != auth) {

                //自己创建的活动
                List<Object[]> campaignIdList = campaignRepository.findCampaignIdsCidByAccountApp(accountId, appId);

                if (!CollectionUtils.isEmpty(campaignIdList)) {
                    resultList.addAll(campaignIdList);
                }

                //授权的活动
                List<Object[]> dataAuthCampaignIdListWithoutCreate = campaignRepository.findDataAuthCampaignIdCidListWithoutCreate(accountId, appId);

                if (!CollectionUtils.isEmpty(dataAuthCampaignIdListWithoutCreate)) {
                    resultList.addAll(dataAuthCampaignIdListWithoutCreate);
                }

            }

            return resultList;
        }
    }


    @Override
    public List<Channel> getAuthChannelListByApp(Long accountId, Long appId) {
        return getAuthChannelListByApp(accountId, appId, false);
    }


    public List<Channel> getAuthChannelListByApp(Long accountId, Long appId, boolean ignore) {

        List<Channel> result = new ArrayList<>();

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

        //母账号,管理员,子应用管理员。
        if (account.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || (roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey()) && null != authRepository.findAuthByAccountAndApp(account.getId(), appId))) {

            //根据创建的活动查APP下所有渠道
            result = channelRepository.listAllCampaignChannel(appId);
            //筛选改渠道是否是更细粒度的单独用户控制
            //result=channelServiceImpl.filterChannelControl(accountId,result);
        } else {

            if (ignore) {
                //自定义角色,自定义权限,渠道账号。授权的渠道权限
                List<Channel> authorizedChannelList = channelRepository.listChannelIdByDataAuthIgnoreDel(accountId, appId);
                result.addAll(authorizedChannelList);

            } else {
                //自定义角色,自定义权限,渠道账号。授权的渠道权限
                List<Channel> authorizedChannelList = channelRepository.listChannelIdByDataAuth(accountId, appId);
                result.addAll(authorizedChannelList);
            }

            //自己创建的推广活动的渠道
            List<Channel> createdChannelList = channelRepository.listSubAccountCampaignChannel(accountId, appId);
            result.addAll(createdChannelList);
        }

        return result;
    }


    /**
     * 根据账户和APP获取使用的渠道
     * 1,母账号,管理员,子应用管理员:APP下所使用的所有渠道
     * 2,自定义角色,渠道账号:授权的渠道+自己创建的活动的渠道
     */
    @Override
    public List<Channel> getUsedChannelByAccountAndApp(Long accountId, Long appId) {

        List<Channel> result = new ArrayList<>();

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

        //母账号,非渠道账号
        if (account.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || (roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey()) && null != authRepository.findAuthByAccountAndApp(account.getId(), appId))) {

            //查询APP下面所有的推广活动的渠道
            List<Channel> appChannelList = channelRepository.listAllCampaignChannel(appId);

            if (ValidateUtil.isValid(appChannelList)) {
                result.addAll(appChannelList);
            }

        } else {

            //自定义角色,自定义权限,渠道账号。授权的渠道权限
            List<Channel> authorizedChannelList = channelRepository.listChannelByDataAuth(accountId, appId);

            if (ValidateUtil.isValid(authorizedChannelList)) {
                result.addAll(authorizedChannelList);
            }

            //自己创建的推广活动渠道
            List<Channel> createdChannelList = channelRepository.listCampaignChannelByAccount(accountId, appId);

            if (ValidateUtil.isValid(createdChannelList)) {
                result.addAll(createdChannelList);
            }
        }

        return result;
    }

    /**
     * 根据APP获取所有授权的活动,只包含生效的
     */
    @Override
    public List<Long> getAuthCampaignList(Long accountId, Long app) {

        List<Long> result = new ArrayList<>();

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

        if (account.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || (roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey()) && null != authRepository.findAuthByAccountAndApp(account.getId(), app))) {

            //母账号,管理员,子应用管理员
            List<Campaign> campaignList = campaignRepository.findCampaignByApp(app);

            if (CollectionUtils.isEmpty(campaignList)) {
                result = Lists.transform(campaignList, new Function<Campaign, Long>() {
                    @Override
                    public Long apply(Campaign campaign) {
                        return campaign.getId();
                    }
                });
            }

        } else {

            //自定义权限,自定义角色,渠道账号
            result = getCustomRoleAuthorizedCampaignList(accountId, app, true);
        }

        return result;
    }


    @Override
    public List<Campaign> getAuthCampaignListLimit(Account account, String name, Long appid, Map jsond, int limit) {
        // 自定义权限,自定义角色,渠道账号

        BigInteger count = campaignRepository.findAuthCampaignCount(account.getId(), appid);
        jsond.put("total", count);

        List<Campaign> campaign4Webs;
        if (StringUtil.isEmpty(name)) {
            campaign4Webs = campaignRepository.findAuthCampaign(account.getId(), appid, limit);
        } else {
            campaign4Webs = campaignRepository.findAuthCampaignName(account.getId(), appid, name, limit);
        }

        return campaign4Webs;
    }

    /**
     * 根据APP获取所有授权的活动,只包含生效的
     */
    @Override
    public List<Long> getAuthCampaignListByDelflag(Long accountId, Long app, String delflag_condition) {

        List<Long> result = new ArrayList<>();

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

        if (account.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || (roleAuth.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey()) && null != authRepository.findAuthByAccountAndApp(account.getId(), app))) {

            //母账号,管理员,子应用管理员
            List<Campaign> campaignList = new ArrayList<>();
            if (!StringUtil.isEmpty(delflag_condition)) {
                campaignList = campaignRepository.listAllCampByAppAndDelflag(app, Boolean.valueOf(delflag_condition));
            } else {
                campaignList = campaignRepository.listCampByApp(app);
            }


            if (CollectionUtils.isEmpty(campaignList)) {
                result = Lists.transform(campaignList, new Function<Campaign, Long>() {
                    @Override
                    public Long apply(Campaign campaign) {
                        return campaign.getId();
                    }
                });
            }

        } else {

            //自定义权限,自定义角色,渠道账号
            result = getCustomRoleAuthorizedCampaignListByDelflag(accountId, app, StringUtil.isEmpty(delflag_condition) ? null : Boolean.valueOf(delflag_condition));
        }

        return result;
    }


    /**
     * 获取自定义权限授权的推广活动列表
     * 参数isIncludeDisable表示是否查出停用的推广活动
     */
    private List<Long> getCustomRoleAuthorizedCampaignList(Long accountId, Long appId, boolean isIncludeDisable) {

        List<Long> result = new ArrayList<>();

        //自定义权限,自定义角色,渠道账号
        List<DataAuth> dataList = dataAuthRepository.findDataAuthByAccountAndApp(accountId, appId);

        if (ValidateUtil.isValid(dataList)) {

            //渠道权限的渠道ID
            List<Long> channelIds = new ArrayList<>();

            for (DataAuth data : dataList) {

                if (data.getAllCampaign() && !channelIds.contains(data.getChannel())) {
                    //全部推广活动
                    channelIds.add(data.getChannel());

                } else if (!data.getAllCampaign()) {
                    //部分推广活动
                    result.add(data.getCampaign());
                }
            }

            //有按渠道授权的
            if (!CollectionUtils.isEmpty(channelIds)) {

                List<Campaign> authCampaignList = isIncludeDisable ? campaignRepository.findAllByChannelApp(channelIds, appId)
                        : campaignRepository.findActiveByChannelApp(channelIds, appId);

                if (!CollectionUtils.isEmpty(authCampaignList)) {
                    for (Campaign campaign : authCampaignList) {
                        result.add(campaign.getId());
                    }
                }
            }
        }

        //自己创建的推广活动
        List<Campaign> createdCampaignList = isIncludeDisable ? campaignRepository.findAllByCreate(accountId, appId)
                : campaignRepository.findActiveByCreate(accountId, appId);

        if (!CollectionUtils.isEmpty(createdCampaignList)) {
            for (Campaign campaign : createdCampaignList) {
                result.add(campaign.getId());
            }
        }

        return result;
    }

    /**
     * 获取自定义权限授权的推广活动列表
     * 参数isIncludeDisable表示是否查出停用的推广活动
     */
    private List<Long> getCustomRoleAuthorizedCampaignListByDelflag(Long accountId, Long appId, Boolean delflag) {

        List<Long> result = new ArrayList<>();

        //自定义权限,自定义角色,渠道账号
        List<DataAuth> dataList = delflag == null ? dataAuthRepository.findDataAuthByAccountAndApp(accountId, appId) : dataAuthRepository.findDataAuthByAccountAndAppDelflag(accountId, appId, delflag);

        if (ValidateUtil.isValid(dataList)) {

            //渠道权限的渠道ID
            List<Long> channelIds = new ArrayList<>();

            for (DataAuth data : dataList) {

                if (data.getAllCampaign() && !channelIds.contains(data.getChannel())) {
                    //全部推广活动
                    channelIds.add(data.getChannel());

                } else if (!data.getAllCampaign()) {
                    //部分推广活动
                    result.add(data.getCampaign());
                }
            }

            //有按渠道授权的
            if (!CollectionUtils.isEmpty(channelIds)) {

                List<Campaign> authCampaignList = delflag == null ? campaignRepository.findAllByChannelApp(channelIds, appId)
                        : campaignRepository.findCampByChannelAppDelflag(channelIds, appId, delflag);

                if (!CollectionUtils.isEmpty(authCampaignList)) {
                    for (Campaign campaign : authCampaignList) {
                        result.add(campaign.getId());
                    }
                }
            }
        }

        //自己创建的推广活动
        List<Campaign> createdCampaignList = delflag == null ? campaignRepository.findAllByCreate(accountId, appId)
                : campaignRepository.findActiveByCreateDelflag(accountId, appId, delflag);

        if (!CollectionUtils.isEmpty(createdCampaignList)) {
            for (Campaign campaign : createdCampaignList) {
                result.add(campaign.getId());
            }
        }

        return result;
    }


    public List<Campaign> getAuthCampaignListByAccount(Long accountId, Long appId) {

        return getAuthCampaignListByAccount(accountId, appId, false);
    }


    /**
     * 获取授权活动列表
     * 1.母账号,管理员,子应用管理员:获取APP下所有
     * 2.自定义角色,渠道账号:获取授权+创建
     */
    public List<Campaign> getAuthCampaignListByAccount(Long accountId, Long appId, boolean forReport) {

        List<Campaign> resultList = new ArrayList<>();

        Account account = accountRepository.findOne(accountId);
        RoleAuth roleAuth = roleAuthRepository.findOne(account.getRoleCategory());

        if (account.getIsSuperUser() || roleAuth.getRoleCategory().equals(RoleEnumType.MANAGER.getKey())
                || (account.getRoleCategory().equals(RoleEnumType.SUB_APP_MANAGER.getKey()) && null != authRepository.findAuthByAccountAndApp(account.getId(), appId))) {

            //母账号,管理员,有此权限的子应用管理员
            List<Campaign> allByApp = this.campaignRepository.findAllByApp(appId);
            for (Campaign campaign : allByApp) {
                campaign.setDeeplink(this.isDeeplink(campaign));
            }
            resultList.addAll(allByApp);

            if (forReport) {
                Campaign natureCamp = new Campaign();
                natureCamp.setChannel(-1L);
                natureCamp.setCampaignid("_default_");
                natureCamp.setName("自然量");
                resultList.add(natureCamp);
            }

        } else {

            //自定义角色,渠道账号,授权+自己创建
            Auth auth = this.findAuth(accountId, appId);

            if (null != auth) {

                //自己创建的活动
                List<Campaign> campaignList = campaignRepository.findByAccountApp(accountId, appId);

                if (!CollectionUtils.isEmpty(campaignList)) {
                    for (Campaign campaign : campaignList) {
                        campaign.setDeeplink(this.isDeeplink(campaign));
                    }
                    resultList.addAll(campaignList);
                }

                //授权的活动
                List<Campaign> dataAuthCampaignListWithoutCreate = campaignRepository.findDataAuthCampaignListWithoutCreate(accountId, appId);

                if (!CollectionUtils.isEmpty(dataAuthCampaignListWithoutCreate)) {
                    for (Campaign campaign : dataAuthCampaignListWithoutCreate) {
                        campaign.setDeeplink(this.isDeeplink(campaign));
                    }
                    resultList.addAll(dataAuthCampaignListWithoutCreate);
                }

                if (auth.getIsNatureOpen()) {
                    Campaign natureCamp = new Campaign();
                    natureCamp.setChannel(-1L);
                    natureCamp.setCampaignid("_default_");
                    natureCamp.setName("自然量");
                    resultList.add(natureCamp);
                }
            }
        }

        return resultList;
    }

    private boolean isDeeplink(Campaign campaign) {
        String containsUrl = Constant.deeplinkHost;
        if ((!StringUtil.isEmpty(campaign.getUrl()) && campaign.getUrl().contains(containsUrl)) || campaign.getDeeplink()) {
            return true;
        }
        return false;
    }

    // modify 2018-12-06
    @Override
    public Map<Long, Map<String, Campaign>> getAllCampaignByParentAccount(Long accountId, Long appId) {

        return getAllCampaignByParentAccount(accountId, appId, false);

    }

    /**
     * 查询母账号下面所有子账号的创建活动以及权限活动
     * created by sunhao
     */
    @Override
    public Map<Long, Map<String, Campaign>> getAllCampaignByParentAccount(Long accountId, Long appId, boolean forReport) {

        Map<Long, Map<String, Campaign>> result = Maps.newHashMap();

        Account acc = accountRepository.findOne(accountId);
        Long rootParent = acc.getRootParent();
        List<Account> accountList;
        if (acc.getIsSuperUser()) {
            accountList = accountRepository.findAccountByRootParent(rootParent);
        } else if (RoleEnumType.MANAGER.getKey().equals(acc.getRoleCategory())) {
            accountList = accountRepository.findAccountByRootParentExManager(rootParent, acc.getId());
        } else {
            accountList = accountRepository.findAccountByParent(accountId);
        }


        //获取子账号所有授权的活动数据
        for (Account act : accountList) {

            List<Campaign> campaignList = getAuthCampaignListByAccount(act.getId(), appId, forReport);

            if (!CollectionUtils.isEmpty(campaignList)) {
                Map<String, Campaign> campaignMap = Maps.uniqueIndex(campaignList, new Function<Campaign, String>() {
                    @Override
                    public String apply(Campaign campaign) {
                        return campaign.getCampaignid();
                    }
                });

                result.put(act.getId(), campaignMap);
            }
        }

        return result;
    }


    /**
     * 根据账号查询授权的APP
     */
    @Override
    public List<Long> findAuthAppListByAccount(Long accountId) {

        List<Long> idListOne = authRepository.findAppsByAccountAuthRole(accountId, 2);
        List<Long> idListTwo = authRepository.findAppsByAccountWithOutNew(accountId);
        List allIds = new ArrayList();
        allIds.addAll(idListOne);
        allIds.addAll(idListTwo);
        return allIds;

        //return authRepository.findAppListByAccount(accountId);
    }

    /**
     * 发送激活邮件,激活链接复用忘记密码方法
     * 亲爱的用户,已为您xxxxx@xxx.com邮箱创建TrackingIO子账号。点击此链接设置密码:http://trackingio.com/resetpwd.html#?
     */
    @Override
    public boolean sendSubAccountActivateEmail(Account loginAccount, Account subAccount, String lanType) {

        boolean result = true;

        try {
            //修改忘记密码时间
            subAccount.setForgetPwdTime(new Date().getTime());
            subAccount.setForgetPwdStatus(false);
            accountRepository.save(subAccount);

            Account root = subAccount;

            if (!subAccount.getId().equals(subAccount.getRootParent())) {
                root = accountRepository.findOne(subAccount.getRootParent());
            }

            Map<String, String> logo_txt = tipService.getLogoData(root, "logo_res_company", "active_email_url", "logo_res_create", SendCommonPostMail.EMAIL_HOST, SendCommonPostMail.EMAIL_USERNAME, SendCommonPostMail.EMAIL_PASSWORD);


//            final String url = Constant.accountCheckUrl + "/resetpwd.html#?message=" + HashAlgorithms.MD5("superuser_" + subAccount.getId() + subAccount.getForgetPwdTime()) + subAccount.getId();
            final String url = logo_txt.get("active_email_url") + "/resetpwd.html#?message=" + HashAlgorithms.MD5("superuser_" + subAccount.getId() + subAccount.getForgetPwdTime()) + subAccount.getId();

//            String sourceName = accountService.getAccountSoureceName(loginAccount,null,1);

            //邮件主题

            String subject = logo_txt.get("logo_res_company") + (subAccount.getIsChannelPerson() ? "渠道账号" : "子账号") + "激活";
            //邮件内容
            StringBuilder content = new StringBuilder();
            content.append("<!doctype html> <html><head></head><body> ")
                    .append("亲爱的用户:</br>")
                    .append("您好,").append(loginAccount.getEmail())
                    .append("已为您的").append(subAccount.getEmail()).append(logo_txt.get("logo_res_create")).append(subAccount.getIsChannelPerson() ? "渠道账号。" : "子账号。")
                    .append("点击此链接设置密码激活账号: </br>")
                    .append("<a href=\"").append(url).append("\">").append(url).append("</a>")
                    .append("</body></html>");

            //处理国际化
            if (LanguageTypeEnum.ENGLISH.getCode().equals(lanType)) {
                subject = (subAccount.getIsChannelPerson() ? "channel account" : "subaccount") + " activation for TrackingIO";

                content = new StringBuilder();
                content.append("<!doctype html> <html><head></head><body> ")
                        .append("Dear user:</br>")
                        .append(loginAccount.getEmail())
                        .append(" create TrackingIO").append(subAccount.getIsChannelPerson() ? " channel account" : " subaccount").append(" for your ").append(subAccount.getEmail())
                        .append(". You can activate the account by clicking the following link: </br>")
                        .append("<a href=\"").append(url).append("\">").append(url).append("</a>")
                        .append("</body></html>");
            }
            //end

            //收件人列表
            List<String> mailList = new ArrayList<>();
            Map<String, String> mailConfig = null;
            if (root.getRegSource() != 0) {
                mailConfig = logo_txt;
            }
            mailList.add(subAccount.getEmail());
            //MailUtils.sendHtmlEmail(subject, content.toString(), mailList, mailConfig);
            SendCommonPostMail.sendMailReuse(mailList, subject, content.toString(), null, null, mailConfig);
//            MailUtils.sendHtmlEmail(subject, content.toString(), mailList);
        } catch (Exception e) {

            logger.error(e.getMessage(), e);
            result = false;
        }

        return result;
    }

    @Override
    public boolean sendChannelAccountAuthEmail(Account loginAccount, Account subAccount, String lanType) {

        boolean result = true;
        //邮件主题
        Account root = subAccount;
        if (!subAccount.getId().equals(subAccount.getRootParent())) {
            root = accountRepository.findOne(subAccount.getRootParent());
        }
        Map<String, String> logo_txt = tipService.getLogoData(root, "logo_res_company", "active_email_url", "logo_res_create",
                "logo_res_host", SendCommonPostMail.EMAIL_HOST, SendCommonPostMail.EMAIL_USERNAME, SendCommonPostMail.EMAIL_PASSWORD);


        String subject = logo_txt.get("logo_res_company") + "渠道账号权限分配";
        //邮件内容
        StringBuilder content = new StringBuilder();
        content.append("<!doctype html> <html><head></head><body> ")
                .append("亲爱的用户:</br>")
                .append("您好,").append(loginAccount.getEmail())
                .append("已为您的 ").append(subAccount.getEmail()).append(" 邮箱分配" + logo_txt.get("logo_res_company") + "渠道账号权限。")
                .append("点击此链接查看详情: </br>")
                .append("<a href=\"http://" + logo_txt.get("logo_res_host") + "/login.html\">").append("http://" + logo_txt.get("logo_res_host") + "/login.html").append("</a>")
                .append("</body></html>");

        //处理国际化
        if (LanguageTypeEnum.ENGLISH.getCode().equals(lanType)) {
            subject = "Allocation of channel account rights for TrackingIO";

            content = new StringBuilder();
            content.append("<!doctype html> <html><head></head><body> ")
                    .append("Dear user:</br>")
                    .append(loginAccount.getEmail())
                    .append(" have allocated  TrackingIO account authority").append(" for your ").append(subAccount.getEmail())
                    .append(". You can activate the account by clicking the following link: </br>")
                    .append("<a href=\"http://" + logo_txt.get("logo_res_host") + "/login.html\">").append("http://" + logo_txt.get("logo_res_host") + "/login.html").append("</a>")
                    .append("</body></html>");
        }
        //end

        //收件人列表
        List<String> mailList = new ArrayList<>();
        mailList.add(subAccount.getEmail());

        try {
            //发送邮件
//            Thread emailThread = new EmailThread(subject, content.toString(), mailList);
//            emailThread.start();
            Map<String, String> mailConfig = null;
            if (root.getRegSource() != 0) {
                mailConfig = logo_txt;
            }
            //MailUtils.sendHtmlEmail(subject,  content.toString(), mailList, mailConfig);
            SendCommonPostMail.sendMailReuse(mailList, subject, content.toString(), null, null, mailConfig);
        } catch (Exception e) {

            logger.error(e.getMessage(), e);
            result = false;
        }

        return result;
    }

    @Override
    public void createOrUpdateChannelRemark(Long loginAccountId, Long channelAccountId, String remark) {

        Long rootAccountId = this.findRootParentAccount(loginAccountId).getId();

        ChannelAccountMap channelAccountMap = channelAccountMapRepository.findAccount(rootAccountId, channelAccountId);

        if (null != channelAccountMap) {

            channelAccountMap.setRemark(remark);
            channelAccountMap.setAuthConfig(false);

        } else {

            channelAccountMap = new ChannelAccountMap(rootAccountId, loginAccountId, channelAccountId, remark, true);
            channelAccountMap.setAuthConfig(false);
        }

        channelAccountMapRepository.save(channelAccountMap);
    }

    /**
     * 上线数据处理
     * 临时处理
     */
    @Override
    public boolean dealWithOldAuth() {

        //获取全部的菜单
        Map<String, RoleAuthDetail> roleAuthDetailMap = this.getAllRoleAuthMap();

        //所有的权限
        List<Auth> authList = authRepository.findAll();

        for (Auth auth : authList) {

            if (null != auth.getControlAuth() && auth.getControlAuth().startsWith("[") && auth.getControlAuth().endsWith("]")) {

                JSONArray authArray = JSONArray.fromObject(auth.getControlAuth());
                JSONArray newAuthArray = new JSONArray();

                if (!CollectionUtils.isEmpty(authArray)) {

                    Set<String> authNameSet = new HashSet<>();

                    for (int i = 0; i < authArray.size(); i++) {

                        JSONObject authObject = authArray.getJSONObject(i);
                        if (authObject != null) {
                            String authName = authObject.getString("auth");

                            authNameSet.add(authName);

                            if (roleAuthDetailMap.containsKey(authName)) {

                                RoleAuthDetail roleAuthDetail = roleAuthDetailMap.get(authName);

                                String parentName = roleAuthDetail.getParentAuth();
                                if (!StringUtil.isEmpty(parentName) && !authNameSet.contains(parentName) && roleAuthDetailMap.containsKey(parentName)) {
                                    RoleAuthDetail roleAuthDetailParent = roleAuthDetailMap.get(parentName);
                                    JSONObject authObjectParent = new JSONObject();
                                    authObjectParent.put("auth", roleAuthDetailParent.getAuth());
                                    authObjectParent.put("view", true);
                                    authObjectParent.put("edit", true);
                                    authObjectParent.put("sort", roleAuthDetailParent.getSort());
                                    authObjectParent.put("parentAuth", roleAuthDetailParent.getParentAuth());
                                    newAuthArray.add(authObjectParent);
                                    authNameSet.add(parentName);
                                }

                                authObject.put("parentAuth", parentName);
                                authObject.put("sort", roleAuthDetail.getSort());

                                newAuthArray.add(authObject);
                            }
                        }


                    }

                    auth.setControlAuth(newAuthArray.toString());
                }
            }
        }

        authRepository.save(authList);

        return true;
    }

    @Override
    public void dealWithOldRoleDetail() {
        //获取全部的菜单
        Map<String, RoleAuthDetail> roleAuthDetailMap = this.getAllRoleAuthMap();
        List<RoleAuthDetail> detailList = roleAuthDetailRepository.findByNeedAddFirstMenu();
        Map<String, List<String>> middle = new HashMap<>();
        List<RoleAuthDetail> result = new ArrayList<>();
        for (RoleAuthDetail detail : detailList) {
            List<String> names = null;
            if (middle.containsKey(detail.getRoleId().toString())) {
                names = middle.get(detail.getRoleId().toString());
            } else {
                names = new ArrayList<>();
            }
            if (!names.contains(detail.getParentAuth())) {
                RoleAuthDetail newFirstMenu = new RoleAuthDetail();
                newFirstMenu.setAuth(detail.getParentAuth());
                newFirstMenu.setRoleId(detail.getRoleId());
                newFirstMenu.setEdit(detail.getEdit());
                newFirstMenu.setView(detail.getView());
                RoleAuthDetail custom = roleAuthDetailMap.get(detail.getParentAuth());
                newFirstMenu.setSort(custom.getSort());
                newFirstMenu.setAuthName(custom.getAuthName());
                result.add(newFirstMenu);
                names.add(detail.getParentAuth());
                middle.put(detail.getRoleId().toString(), names);
            }

        }
        roleAuthDetailRepository.save(result);
    }

    @Override
    public Map<String, Object> findGuangDianTongChannel(Long appId, long cid) {
        HashMap<String, Object> map = new HashMap<>();
        //HashMap<String, String> resultValMap = new HashMap<>();

        //广点通和微信mp
        Channel gdt = new Channel();
        Channel weixinmp = new Channel();
        gdt.setName("广点通");
        gdt.setId(1L);
        weixinmp.setName("微信mp");
        weixinmp.setId(21L);
        List<Channel> channellist = new ArrayList<Channel>(2);
        channellist.add(gdt);
        channellist.add(weixinmp);
        map.put("gdtMap", channellist);
        App app = appRepository.findOne(appId);
        List<String> spAccountNumber = this.findSpAccountNumber(app);
        List<Object> splist = new ArrayList<>(spAccountNumber.size());
        HashMap<String, String> nameMap = this.thirdAccount(appId);
        for (String s : spAccountNumber) {
            HashMap<Object, Object> mp = new HashMap<>(2);
            mp.put("sp_account_number", s);
            mp.put("alias", nameMap.containsKey(s) ? nameMap.get(s) : s);
            splist.add(mp);
        }
        map.put("channelAccounts", splist);
        return map;
    }


    private HashMap<String, String> thirdAccount(Long appid) {
        List<Object> rs = campaignRepository.findThirdAccountByAppChannel(appid, 5305L);
        HashMap<String, String> nameMap = new HashMap<>();

        if (ValidateUtil.isValid(rs)) {
            for (Object ob : rs) {
                JSONArray jsonA = JSONArray.fromObject(ob);
                String key = jsonA.getString(0);
                String value = jsonA.getString(1);
                if (!(StringUtil.isEmpty(value) || value == "null")) {
                    nameMap.put(key, value);
                }
            }
        }
        return nameMap;
    }

    @Override
    public Map<String, Object> findGuangDianTongChannelByRole(Long appId, long cid, Long accountid) {
        HashMap<String, Object> map = new HashMap<>();
        //广点通和微信mp
        Channel gdt = new Channel();
        Channel weixinmp = new Channel();
        gdt.setName("广点通");
        gdt.setId(1L);
        weixinmp.setName("微信mp");
        weixinmp.setId(21L);
        List<Channel> channellist = new ArrayList<Channel>(2);
        channellist.add(gdt);
        channellist.add(weixinmp);
        map.put("gdtMap", channellist);
        App app = appRepository.findOne(appId);
        List<String> spAccountNumber = this.findSpAccountNumber(app);
        List<String> spaccounts = null;
        HashMap<String, String> nameMap = thirdAccount(appId);
        if (!CollectionUtils.isEmpty(spAccountNumber)) {
            spaccounts = this.thirdAccountAuthRepository.findByThirdAccountAndAccount(spAccountNumber, accountid);
        }
        List<Object> splist = new ArrayList<>(spAccountNumber.size());
        if (!CollectionUtils.isEmpty(spaccounts)) {
            for (String s : spaccounts) {
                HashMap<String, Object> mp = new HashMap<>(2);
                mp.put("sp_account_number", s);
                mp.put("alias", nameMap.containsKey(s) ? nameMap.get(s) : s);
                splist.add(mp);
            }
        }
        map.put("channelAccounts", splist);
        return map;
    }

    @Override
    public List<Map<String, Object>> findGdtThirdAccount(Long appId, Long account) {
        //System.out.println("开始查询");
        //long l = System.currentTimeMillis();
        App app = appRepository.findOne(appId);
        List<Map<String, Object>> list = new ArrayList<>();
        if (app != null) {
            //List<Map<String, Object>> thirdAccounts = this.findThirdAccount(app);
            List<Object[]> thirdAccountAndId = campaignRepository.findThirdAccountAndId(app.getId());
            DataAuth dataAuth = dataAuthRepository.getByAllCampaign(account, app.getId(), 5305L);
            if (!CollectionUtils.isEmpty(thirdAccountAndId)) {
                for (Object[] thirdAccountObj : thirdAccountAndId) {
                    String thirdAccount = (String) thirdAccountObj[0];
                    if (!StringUtil.isEmpty(thirdAccount)) {
                        Map<String, Object> objects = new HashMap<>(3);
                        objects.put("id", thirdAccount);
                        //List<String> campaignids = (List<String>)thirdAccountMap.get("campaignids");
                        String camids = (String) thirdAccountObj[1];
                        List<String> campaignids = StringUtil.transString2List(camids);
                        objects.put("campaign", campaignids);
                        if (dataAuth != null || thirdAccountAuthRepository.getThirdAccount(thirdAccount, account) != null) {
                            objects.put("checked", true);
                        } else {
                            if (CollectionUtils.isEmpty(campaignids)) {
                                continue;
                            }
                            objects.put("checked", this.dataAuthRepository.checkAuth(appId, account, campaignids) > 0 ? false : null);
                        }
                        list.add(objects);
                    }
                }
                //System.out.println("用时:"+(1.0*(System.currentTimeMillis()-l)/1000));
                return list;
            }
        }
        return null;
    }

    private List<String> findSpAccountNumber(App app) {
        JdbcTemplate tkioJdbcTemplate = TkioStreamDBUtil.newInstance().getTkioJdbcTemplate();
        String sql = "SELECT DISTINCT sp_account_number FROM (SELECT sp_account_number FROM tkio.tkio_rlt_account_history_info WHERE appid= '" + app.getAppkey() + "' UNION ALL SELECT sp_account_number FROM tkio_stream.tkio_rpt_source_analysis_day WHERE appid='" + app.getAppkey() + "' AND cid = 5305) t where t.sp_account_number!='unknown' AND sp_account_number!=-1";
        //System.out.println("sql = " + sql);
        List<String> query = tkioJdbcTemplate.query(sql, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("sp_account_number");
            }
        });
        return query;
    }

    @Override
    public boolean checkRoleTempCategory(Account account) {
        if (account.getRoleCategory() > 5) {
            RoleAuth category = roleAuthRepository.findOne(account.getRoleCategory());
            account.setRoleCategory(category.getRoleCategory());
            return true;
        }

        return false;
    }
}