CustomerService.java 191 KB
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 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462
package cn.com.glsx.entmicro.service;

import cn.com.glsx.bigdatautil.dto.*;
import cn.com.glsx.bigdatautil.model.request.PotentialBasicInfoRequest;
import cn.com.glsx.bigdatautil.model.response.PotentialBasicResponse;
import cn.com.glsx.bigdatautil.remote.CustomerCollectRemote;
import cn.com.glsx.bigdatautil.remote.PotentialBasicInfoRemote;
import cn.com.glsx.bigdatautil.remote.ScrmBigdataUtilRemote;
import cn.com.glsx.datahub.dto.UserQueryByLabelDTO;
import cn.com.glsx.datahub.remote.UserProfileRemote;
import cn.com.glsx.dj.smartcarlife.dto.GoodsOrderDTO;
import cn.com.glsx.dj.smartcarlife.model.GoodsOrderCustomer;
import cn.com.glsx.entmicro.Enum.BusinessExceptionEnum;
import cn.com.glsx.entmicro.annotation.DictionarySupport;
import cn.com.glsx.entmicro.config.RedisLock;
import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.constants.CustomerConstants;
import cn.com.glsx.entmicro.converter.CustomerInfoConvert;
import cn.com.glsx.entmicro.converter.MagicImportCustomerConvert;
import cn.com.glsx.entmicro.dto.SearchCustomerOneIdDto;
import cn.com.glsx.entmicro.dto.*;
import cn.com.glsx.entmicro.entity.*;
import cn.com.glsx.entmicro.enums.customer.ReportTypeEnum;
import cn.com.glsx.entmicro.kafka.converter.MessageConvertService;
import cn.com.glsx.entmicro.kafka.model.CustomerModel;
import cn.com.glsx.entmicro.kafka.model.CustomerRemarkExportModel;
import cn.com.glsx.entmicro.kafka.producer.ProducerComponent;
import cn.com.glsx.entmicro.listener.CustomerRemarkDataListener;
import cn.com.glsx.entmicro.manager.CustomerDetailMagicAsyncComponent;
import cn.com.glsx.entmicro.mapper.*;
import cn.com.glsx.entmicro.model.CustomerListExportModel;
import cn.com.glsx.entmicro.model.CustomerReceiptModel;
import cn.com.glsx.entmicro.model.CustomerViewListExportModel;
import cn.com.glsx.entmicro.model.QGCodeConfig;
import cn.com.glsx.entmicro.model.WechatMessageModel;
import cn.com.glsx.entmicro.model.request.*;
import cn.com.glsx.entmicro.model.request.sop.SopCusSendRequest;
import cn.com.glsx.entmicro.model.response.*;
import cn.com.glsx.entmicro.model.sop.EntmiroCustomerInfo;
import cn.com.glsx.entmicro.model.wechatcloudcontrol.CustomerCallBackModel;
import cn.com.glsx.entmicro.model.wechatcloudcontrol.CustomerListCallBackModel;
import cn.com.glsx.entmicro.model.wechatcloudcontrol.LoginCallBackModel;
import cn.com.glsx.entmicro.rabbitmq.produce.MsgProducer;
import cn.com.glsx.entmicro.rabbitmq.produce.RabbitConfig;
import cn.com.glsx.entmicro.service.common.CommonService;
import cn.com.glsx.entmicro.service.drainage.DracImCustomerCollectionService;
import cn.com.glsx.entmicro.service.drainage.bussinessFactory.AddCustomerReceiptService;
import cn.com.glsx.entmicro.service.drainage.bussinessFactory.AddCustomerType;
import cn.com.glsx.entmicro.service.drainage.bussinessFactory.BussinessFactory;
import cn.com.glsx.entmicro.service.operation.OperationCustomerService;
import cn.com.glsx.entmicro.service.outbound.OutboundCallTaskCustomerService;
import cn.com.glsx.entmicro.util.*;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.com.glsx.idmapping.enums.OneIdEventEnum;
import cn.com.glsx.idmapping.enums.OneIdProEnum;
import cn.com.glsx.idmapping.model.OneIdEevent;
import cn.com.glsx.idmapping.model.OneIdSearch;
import cn.com.glsx.idmapping.remote.OneIdRemote;
import cn.com.glsx.scrm.coupon.dto.BackstageUserDirectionalGiftResponse;
import cn.com.glsx.scrm.coupon.dto.UserDirectionalGiftListDTO;
import cn.com.glsx.scrm.coupon.remote.UserDirectionalGiftRemote;
import cn.com.glsx.scrm.proxy.remote.smartcarlife.GoodsOrderRemote;
import cn.com.glsx.scrm.shopmall.dto.CustomerActivityRecordDTO;
import cn.com.glsx.scrm.shopmall.remote.ActivityRemote;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.request.GetWorkWechatExternalContactRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.response.WorkWechatExternalContactDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.response.WorkWechatExternalContactFollowUserDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.response.WorkWechatExternalContactFollowUserTagDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.response.WorkWechatExternalContactResponseDTO;
import cn.com.glsx.scrm.wechat.remote.WorkWechatExternalContactRemote;
import cn.com.glsx.wika.dto.StaffInfoDTO;
import cn.com.glsx.wika.dto.WeChatContactsDTO;
import cn.com.glsx.wika.remote.VikaWeChatContactsRemote;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.glsx.plat.common.utils.DateUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static cn.com.glsx.entmicro.Enum.ScrmServiceProviderTypeEnum.PROVIDER_GUANG_HUI;
import static java.util.function.Function.identity;

/**
 * @author fengzhi
 * @Description: 客户Service
 * @date 2021/9/16 14:40 matches 120
 */
@Service
@Slf4j
public class CustomerService {

  @Autowired
  private CustomerMapper customerMapper;

  @Autowired
  private CustomerMergeMapper customerMergeMapper;

  @Resource
  private WorkWechatExternalContactRemote contactRemote;

  @Autowired
  private EntmicroFollowService followService;

  @Autowired
  private EntmicroStaffService entmicroStaffService;

  @Autowired
  private RopCommonServie ropCommonServie;

  @Autowired
  private CustomerStatisticsService customerStatisticsService;

  @Autowired
  private DracImCustomerCollectionService dracImService;

  @Autowired
  private RedisLock redisLock;

  private final static String LOCK_ID = "customer";

  @Autowired
  private MerchantService merchantService;

  @Value("${addway.magic}")
  private Integer addwayMagic;

  @Autowired
  private CustomerDetailMagicAsyncComponent customerDetailMagicAsyncComponent;

  @Autowired
  private CommonService commonService;

  @Autowired
  private BussinessModelConvertService bussinessModelConvertService;

  @Resource
  private EntmicroAuthorizeMapper entmicroAuthorizeMapper;

  @Resource
  private ScrmBigdataUtilRemote scrmBigdataUtilRemote;

  @Autowired
  private DracChannelCodeMapper dracChannelCodeMapper;

  @Autowired
  private OneIdRemote oneIdRemote;

  @Autowired
  private EntmicroCustomerFollowMapper entmicroCustomerFollowMapper;

  @Resource
  private MessageConvertService messageConvertService;

  @Value("${customer.delete.url}")
  private String customerDeleteUrl;

  private static final String DEFAULT_DISPLAY = "--";

  @Resource
  private ProducerComponent producerComponent;

  @Autowired
  private CustomerBaseRelationMapper customerBaseRelationMapper;

  @Autowired
  private OperationCustomerService operationCustomerService;

  @Autowired
  private PotentialBasicInfoRemote potentialBasicInfoRemote;

  // scrm服务商配置 GL=广联 GH=广汇
  @Value("${scrm.service.provider.config}")
  private String serviceProviderConfig;

  @Value("${scrm.customer.merge.regex}")
  private String mergeRegex;

  @Resource
  private WechatSubscriberMappingMapper wechatSubscriberMappingMapper;

  @Autowired
  private OutboundCallTaskCustomerService outboundCallTaskCustomerService;

  @Autowired
  private AddEntmicroRelationMapper addEntmicroRelationMapper;

  @Autowired
  private EntmicroAuthorizeService entmicroAuthorizeService;

  @Autowired
  private Environment environment;

  private static final String NOTICE_CONTENT = "客户名称:%S\n添加时间:%S";

  @Autowired
  private DracFileConfigMapper DracFileConfigMapper;

  @Autowired
  private GoodsOrderRemote goodsOrderRemote;

  @Autowired
  private VikaWeChatContactsRemote vikaWeChatContactsRemote;

  @Autowired
  private CustomerCollectRemote customerCollectRemote;

  @Autowired
  private UserProfileRemote userProfileRemote;

  @Autowired
  private UserDirectionalGiftRemote userDirectionalGiftRemote;

  @Autowired
  private ActivityRemote activityRemote;

  @Autowired
  private MsgProducer rabbitProducer;

  @Autowired
  private QGCodeConfigMapper qgCodeConfigMapper;

  /**
   * 客户列表查询
   */
  @DictionarySupport
  public RpcPagination<CustomerListResponse> customerSelect(
      RpcPagination<CustomerSearchRequest> request) throws RpcServiceException {
    PageHelper.startPage(request.getPageNum(), request.getPageSize());
    CustomerSearchRequest requestCondition = request.getCondition();
    log.info("获取客户列表分页条件: {}", JSONArray.toJSONString(request));
    Date endTimeIn = requestCondition.getEndTime();
    if (null != endTimeIn) {
      requestCondition.setEndTime(DateUtils.addDays(endTimeIn, 1));
    }
    //搜索条件emoji转化
    requestCondition.setNickName(
        !StringUtils.isEmpty(requestCondition.getNickName()) ? EmojiUtils.parseToHtmlHexadecimal(
            requestCondition.getNickName()) : null);
    requestCondition.setCustomerName(!StringUtils.isEmpty(requestCondition.getCustomerName())
        ? EmojiUtils.parseToHtmlHexadecimal(requestCondition.getCustomerName()) : null);
    requestCondition.setFollowStaff(
        !StringUtils.isEmpty(requestCondition.getFollowStaff()) ? EmojiUtils.parseToHtmlHexadecimal(
            requestCondition.getFollowStaff()) : null);

    //如果车辆查询条件都为空 则先查出客户信息,再根据客户信息oneId去查询聚合服务车辆信息,避免聚合服务全表查询
    Page<CustomerListResponse> customerByPage;
    Map<String, List<ScrmVehicleBasicInfoDTO>> vehicleMapByOneId;
    String carNumber = requestCondition.getCarNumber();
    String carVin = requestCondition.getCarVin();
    Date beginCarBuyDate = requestCondition.getBeginCarBuyDate();
    Date beginCInsEndDate = requestCondition.getBeginCInsEndDate();
    if (StringUtils.isEmpty(carNumber) && StringUtils.isEmpty(carVin)
        && StringUtils.isEmpty(beginCarBuyDate) && StringUtils.isEmpty(beginCInsEndDate)) {
      //获取客户列表
      customerByPage = customerMergeMapper.getCustomerByPage(requestCondition);
      List<String> oneIds = customerByPage.stream().map(CustomerListResponse::getOneId)
          .collect(Collectors.toList());
      requestCondition.setOneIds(oneIds);
      //车辆条件
      vehicleMapByOneId = getVehicleMapByOneId(requestCondition);
    } else {
      //原逻辑
      //车辆条件
      vehicleMapByOneId = getVehicleMapByOneId(requestCondition);
      if (vehicleMapByOneId == null) {
        return new RpcPagination<>();
      }
      //获取客户列表
      customerByPage = customerMergeMapper.getCustomerByPage(requestCondition);
    }

    //数据组装
    setCustomerInfo(customerByPage, request.getCondition().getMerchantId(), vehicleMapByOneId);

    log.info("客户列表查询: {}", customerByPage);
    return RpcPagination.copyPage(customerByPage);
  }

  /**
   * 车辆条件构建
   *
   * @param requestCondition
   * @return
   */
  private Map<String, List<ScrmVehicleBasicInfoDTO>> getVehicleMapByOneId(
      CustomerSearchRequest requestCondition) {
    //车辆条件
    Map<String, List<ScrmVehicleBasicInfoDTO>> vehicleMapByOneId = new HashMap<>();
    try {
      String carVin = requestCondition.getCarVin();
      String carNumber = requestCondition.getCarNumber();
      Date beginCarBuyDate = requestCondition.getBeginCarBuyDate();
      Date endCarBuyDate = requestCondition.getEndCarBuyDate();
      String carSeries = requestCondition.getCarSeries();
      Date beginCInsEndDate = requestCondition.getBeginCInsEndDate();
      Date endInsEndDate = requestCondition.getEndInsEndDate();
      List<String> oneIds = requestCondition.getOneIds();
      ScrmVehicleSearchDTO record = new ScrmVehicleSearchDTO(requestCondition.getMerchantId(),
          carVin, carNumber, beginCarBuyDate,
          endCarBuyDate, oneIds, carSeries, beginCInsEndDate, endInsEndDate);
      log.info("车辆搜索条件:{}", record);
      RpcResponse<List<ScrmVehicleBasicInfoDTO>> vehicleResponse = scrmBigdataUtilRemote.queryOneIdListByVehicleCondition(
          record);
      log.info("车辆条件查询oneId:{}", vehicleResponse);
      if (vehicleResponse != null && vehicleResponse.isSuccess()) {
        List<ScrmVehicleBasicInfoDTO> vehicleList = vehicleResponse.getResult();
        if (!CollectionUtils.isEmpty(vehicleList)) {
          vehicleMapByOneId = vehicleList.stream().filter(s -> s.getOneid() != null)
              .collect(Collectors.groupingBy(ScrmVehicleBasicInfoDTO::getOneid));
        }
      }
      //车辆查询条件不为空 则当前是车辆条件查询行为
      if (com.glsx.plat.common.utils.StringUtils.isNotBlank(carVin)
          || com.glsx.plat.common.utils.StringUtils.isNotBlank(carNumber)
          || beginCarBuyDate != null || endCarBuyDate != null
          || com.glsx.plat.common.utils.StringUtils.isNotBlank(carSeries)
          || beginCInsEndDate != null || endInsEndDate != null) {
        //1、车辆数据为空 返回空集
        if (CollectionUtils.isEmpty(vehicleMapByOneId)) {
          return null;
        }
        //2、车辆数据不为空 则带出要查询的oneId
        List<String> oneIdList = new ArrayList<>(vehicleMapByOneId.keySet());
        requestCondition.setOneIds(oneIdList);
      }
    } catch (Exception e) {
      log.info("车辆条件构建异常:{}", e);
      throw new RpcServiceException(BusinessExceptionEnum.BIGDATAUTIL_EXCEPTION.getValue(),
          BusinessExceptionEnum.BIGDATAUTIL_EXCEPTION.getDisplayName());
    }
    return vehicleMapByOneId;
  }

  /**
   * 客户首页概览导出
   *
   * @param customerSearchRequest 入参
   * @return
   */
  public String customerViewExport(CustomerSearchRequest customerSearchRequest) {
    List<CustomerViewListExportModel> customerListExportModels = new ArrayList<>();
    //获取客户信息
    List<CustomerListResponse> customerListResponses = customerList(customerSearchRequest);
    if (!CollectionUtils.isEmpty(customerListResponses)) {
      customerListExportModels = customerListResponses.stream().map(index -> {
        CustomerViewListExportModel customerViewListExportModel = new CustomerViewListExportModel();
        BeanUtils.copyProperties(index, customerViewListExportModel);
        customerViewListExportModel.setCustomerSex(sexConvert(index.getCustomerSex()));
        customerViewListExportModel.setIsJoinName(index.getIsJoin().intValue() == 1 ? "是" : "否");
        customerViewListExportModel.setStatusName(
            index.getStatus().byteValue() == 0 ? "正常" : "删除好友");
        customerViewListExportModel.setAddTime(
            customerViewListExportModel != null ? DateUtils.format(index.getAddTime()) : null);
        //设置导出模板的企微名称
        customerViewListExportModel.setNickName(setNickNameInfo(index.getNickNameList()));
        return customerViewListExportModel;
      }).collect(Collectors.toList());
    }
    String fileUrl = ExcelExportUtils.excelExport("客户列表" + System.currentTimeMillis(),
        customerListExportModels, CustomerViewListExportModel.class, null);
    return fileUrl;
  }

  /**
   * 客户列表导出
   *
   * @param customerSearchRequest 入参
   * @return
   */
  public String customerListExport(CustomerSearchRequest customerSearchRequest) {
    List<CustomerListExportModel> customerListExportModels = new ArrayList<>();
    // 大数据基础参数
    ScrmCustomerBatchDTO scrmCustomerDTO = new ScrmCustomerBatchDTO();
    scrmCustomerDTO.setListOneId(customerSearchRequest.getOneIds());
    scrmCustomerDTO.setMerchantId(customerSearchRequest.getMerchantId());
    scrmCustomerDTO.setConsumer("rpc-scrm-entmicro-container");
    scrmCustomerDTO.setVersion("v1.0.0.1");
    String carNumber = customerSearchRequest.getCarNumber();
    String carVin = customerSearchRequest.getCarVin();
    Date beginCarBuyDate = customerSearchRequest.getBeginCarBuyDate();
    Date endCarBuyDate = customerSearchRequest.getEndCarBuyDate();
    scrmCustomerDTO.setCarNumber(carNumber);
    scrmCustomerDTO.setCarVin(carVin);
    scrmCustomerDTO.setBeginCarBuyDate(beginCarBuyDate);
    scrmCustomerDTO.setEndCarBuyDate(endCarBuyDate);

    //如果车辆查询条件都为空 则先查出客户信息,再根据客户信息oneId去查询聚合服务车辆信息,避免聚合服务全表查询
    Map<String, List<ScrmVehicleBasicInfoDTO>> oneIdMap;
    List<CustomerListResponse> customerListResponses;
    if (StringUtils.isEmpty(carNumber) && StringUtils.isEmpty(carVin)
        && StringUtils.isEmpty(beginCarBuyDate) && StringUtils.isEmpty(endCarBuyDate)) {
      customerListResponses = customerList(customerSearchRequest);
      List<String> oneIds = customerListResponses.stream().map(CustomerListResponse::getOneId)
          .collect(Collectors.toList());
      customerSearchRequest.setOneIds(oneIds);
      oneIdMap = getVehicleMapByOneId(customerSearchRequest);
    } else {
      oneIdMap = getVehicleMapByOneId(customerSearchRequest);
      if (oneIdMap == null) {
        return ExcelExportUtils.excelExport("客户列表" + System.currentTimeMillis(),
            customerListExportModels, CustomerListExportModel.class, serviceProviderConfig);
      }
      customerListResponses = customerList(customerSearchRequest);
    }

    //获取客户列表
    if (!CollectionUtils.isEmpty(customerListResponses)) {
      Map<String, List<ScrmVehicleBasicInfoDTO>> finalOneIdMap = oneIdMap;
      customerListResponses.forEach(index -> {
        CustomerListExportModel customerListExportModel = new CustomerListExportModel();
        BeanUtils.copyProperties(index, customerListExportModel);
        if (index.getCustomerSex() != null) {
          customerListExportModel.setCustomerSex(sexConvert(index.getCustomerSex()));
        }
        if (index.getIsJoin() != null) {
          customerListExportModel.setIsJoinName(index.getIsJoin().intValue() == 1 ? "是" : "否");
        }
        if (index.getStatus() != null) {
          customerListExportModel.setStatusName(
              index.getStatus().byteValue() == 0 ? "正常" : "删除好友");
        }
        if (index.getAddTime() != null) {
          customerListExportModel.setAddTime(
              index.getAddTime() != null ? DateUtils.format(index.getAddTime()) : null);
        }
        if (index.getSubscribe() != null) {
          customerListExportModel.setSubscribeName(index.getSubscribe() == 1 ? "是" : "否");
        }
        if (index.getIsLoginApplet() != null) {
          customerListExportModel.setIsLoginAppletName(index.getIsLoginApplet() == 1 ? "是" : "否");
        }
        if (!CollectionUtils.isEmpty(finalOneIdMap)) {
          List<ScrmVehicleBasicInfoDTO> vehicleList = finalOneIdMap.get(index.getOneId());
          if (!CollectionUtils.isEmpty(vehicleList)) {
            ScrmVehicleBasicInfoDTO vehicle = vehicleList.stream()
                .sorted(Comparator.comparing(ScrmVehicleBasicInfoDTO::getBuyTime,
                    Comparator.nullsLast(Date::compareTo)).reversed())
                .collect(Collectors.toList()).get(0);
            customerListExportModel.setBuyDate(
                vehicle.getBuyTime() != null ? DateUtils.format(vehicle.getBuyTime()) : null);
            customerListExportModel.setArrivalDate(
                vehicle.getLastEnteredTime() != null ? DateUtils.format(
                    vehicle.getLastEnteredTime()) : null);
            customerListExportModel.setComInsuranceStarttime(
                vehicle.getMainInsureStartTime() != null ? DateUtils.format(
                    vehicle.getMainInsureStartTime()) : null);
            customerListExportModel.setComInsuranceEndtime(
                vehicle.getMainInsureEndTime() != null ? DateUtils.format(
                    vehicle.getMainInsureEndTime()) : null);
            customerListExportModel.setMaintenanceDate(
                vehicle.getLastMaintainTime() != null ? DateUtils.format(
                    vehicle.getLastMaintainTime()) : null);
            customerListExportModel.setCarBrand(vehicle.getVehicleBrand());
            customerListExportModel.setAudi(vehicle.getVehicleSeries());
            customerListExportModel.setCarType(vehicle.getVehicleType());
            customerListExportModel.setCarNumber(vehicle.getPlateNumber());
            customerListExportModel.setCarVin(vehicle.getStandNo());
            customerListExportModel.setCarPrice(vehicle.getVehiclePrice() == null ? null
                : String.format("%.2f", vehicle.getVehiclePrice()));
          }
        }
        //设置企微名称
        customerListExportModel.setNickName(setNickNameInfo(index.getNickNameList()));
        //手机号脱敏(针对广汇)
        String customerPhone = index.getCustomerPhone();
        log.info("用户手机号:{}", customerPhone);
        if (!StringUtils.isEmpty(serviceProviderConfig) && PROVIDER_GUANG_HUI.getValue()
            .equals(serviceProviderConfig) && !StringUtils.isEmpty(customerPhone)
            && customerPhone.length() > 4) {
          customerListExportModel.setCustomerPhone(DataMaskingUtil.encryptionPhone(customerPhone));
        }
        customerListExportModels.add(customerListExportModel);
      });
    }
    log.info("客户列表导出数据:{}", customerListExportModels);
    String fileUrl = ExcelExportUtils.excelExport("客户列表" + System.currentTimeMillis(),
        customerListExportModels, CustomerListExportModel.class, serviceProviderConfig);
    log.info("客户列表导出fileUrl:{}", fileUrl);
    return fileUrl;
  }

  private String sexConvert(Integer customerSex) {
    String sexName = null;
    switch (customerSex) {
      case 1:
        sexName = "男";
        break;
      case 2:
        sexName = "女";
        break;
      case 0:
        sexName = "未知";
        break;
      default:
        break;
    }
    return sexName;
  }

  /**
   * 客户列表查询
   */
  public Page<CustomerListResponse> customerList(CustomerSearchRequest customerSearchRequest) {
    Date endTimeIn = customerSearchRequest.getEndTime();
    if (null != endTimeIn) {
      customerSearchRequest.setEndTime(DateUtils.addDays(endTimeIn, 1));
    }
    log.info("当前员工UserId{}", customerSearchRequest.getEntmicroId());
    //搜索条件emoji转化
    customerSearchRequest.setNickName(!StringUtils.isEmpty(customerSearchRequest.getNickName())
        ? EmojiUtils.parseToHtmlHexadecimal(customerSearchRequest.getNickName()) : null);
    customerSearchRequest.setCustomerName(
        !StringUtils.isEmpty(customerSearchRequest.getCustomerName())
            ? EmojiUtils.parseToHtmlHexadecimal(customerSearchRequest.getCustomerName()) : null);

    //查询业务表客户
    Page<CustomerListResponse> customerByPage = customerMergeMapper.getCustomerByPage(
        customerSearchRequest);

    long start = System.currentTimeMillis();
    //数据组装
    setCustomerInfo(customerByPage, customerSearchRequest.getMerchantId(), null);
    long end = System.currentTimeMillis();
    log.info("客户数据组装耗时:{}", (end - start));
    return customerByPage;
  }

  /**
   * 设置客户企微昵称对象
   *
   * @param byBatchOneId
   * @param oneId
   * @return
   */
  public List<CustomerNickNameRpcResponse> setNickName(
      List<CustomerNickNameRpcResponse> byBatchOneId, String oneId) {
    List<CustomerNickNameRpcResponse> nickNameRpcResponseList = new ArrayList<>();
    if (!CollectionUtils.isEmpty(byBatchOneId)) {
      for (CustomerNickNameRpcResponse customerNickNameRpcResponse : byBatchOneId) {
        if (oneId.equals(customerNickNameRpcResponse.getOneId())) {
          //类型为空不处理
          if (null == customerNickNameRpcResponse.getType()) {
            continue;
          }
          //昵称emoji转化
          if (!StringUtils.isEmpty(customerNickNameRpcResponse.getNickName())) {
            customerNickNameRpcResponse.setNickName(
                EmojiUtils.parseToUnicode(customerNickNameRpcResponse.getNickName()));
          }
          //微信类型单独赋值
          if (Constants.USER_TYPE_WECHAT == customerNickNameRpcResponse.getType()) {
            customerNickNameRpcResponse.setCorpName(Constants.USER_TYPE_WECHAT_STRING);
          }
          nickNameRpcResponseList.add(customerNickNameRpcResponse);
        }
      }
    }
    return nickNameRpcResponseList;
  }

  /**
   * 客户列表数据组装
   *
   * @param customerByPage
   * @param merchantId
   */
  private void setCustomerInfo(Page<CustomerListResponse> customerByPage, Integer merchantId,
      Map<String, List<ScrmVehicleBasicInfoDTO>> vehicleMapByOneId) {
    if (!CollectionUtils.isEmpty(customerByPage)) {
      //过滤oneId
      List<String> oneIdList = customerByPage.stream()
          .filter(index -> null != index.getOneId()).map(CustomerListResponse::getOneId)
          .collect(Collectors.toList());
      //过滤state
      List<String> stateList = customerByPage.stream()
          .filter(index -> !StringUtils.isEmpty(index.getCustState()))
          .map(CustomerListResponse::getCustState).collect(Collectors.toList());
      //过滤客户基础表主键
      List<Integer> custIdList = customerByPage.stream()
          .filter(index -> null != index.getCustomerId()).map(CustomerListResponse::getCustomerId)
          .collect(Collectors.toList());

      //oneId查询基础表客户昵称
      List<CustomerNickNameRpcResponse> byBatchOneId = customerMapper.findByBatchOneId(oneIdList,
          merchantId);

      //通过oneId查询客户跟进员信息
      Map<String, CustomerFollowStaffResponse> customerStaffByOneId = customerMapper.getAllCustomerStaffByOneId(
          oneIdList, merchantId);

      //字段来源通过查询字典
      List<DictDataResponse> allByDictType = merchantService.findAllByDictType("");

      //替换客户事件表有优先级字段
      replaceCustomerEventInfoFiles(customerByPage.getResult(), merchantId, oneIdList);

      //查询客户渠道
      Map<String, DracChannelCode> channelState = new HashMap<>();
      if (!CollectionUtils.isEmpty(stateList)) {
        channelState = dracChannelCodeMapper.getChannelState(stateList);
      }

      //查询客户群昵称
      Map<Integer, CustomerBaseRelation> nickNameByCustId = new HashMap<>();
      if (!CollectionUtils.isEmpty(custIdList)) {
        nickNameByCustId = customerBaseRelationMapper.getNickNameByCustId(custIdList);
      }

      //遍历客户分页集合
      for (CustomerListResponse response : customerByPage) {
        //设置跟进人信息
        if (customerStaffByOneId.containsKey(
            response.getOneId()) /*&& response.getStatus() != null && response.getStatus() == Constants.NORMAL_FLAG*/) {
          //跟进人emoji转化
          String followStaffName = customerStaffByOneId.get(response.getOneId()).getStaffName();
          response.setFollowStaff(
              !StringUtils.isEmpty(followStaffName) ? EmojiUtils.parseToUnicode(followStaffName)
                  : followStaffName);
        }
        //设置企微名称
        response.setNickNameList(setNickName(byBatchOneId, response.getOneId()));
        //设置来源
        if (response.getAddWay() != null && !CollectionUtils.isEmpty(allByDictType)) {
          List<String> collect = allByDictType.stream().filter(
                  ind -> ind.getDictValue().equals(response.getAddWay()) && ind.getDictType()
                      .equals("add_way")).map(DictDataResponse::getDictLabel)
              .collect(Collectors.toList());
          if (!CollectionUtils.isEmpty(collect)) {
            response.setAddWayName(collect.get(0));
          }
        }
        //匹配渠道来源
        if (!CollectionUtils.isEmpty(channelState) && !StringUtils.isEmpty(response.getCustState())
            && channelState.get(response.getCustState()) != null) {
          response.setSourceChannel(channelState.get(response.getCustState()).getCodeName());
        }
        //客户名Emoji转化
        if (response.getCustomerName() != null) {
          response.setCustomerName(EmojiUtils.parseToUnicode(response.getCustomerName()));
        }
        //客户群昵称
        if (!CollectionUtils.isEmpty(nickNameByCustId)
            && nickNameByCustId.get(response.getCustomerId()) != null) {
          response.setCustomerNickName(
              nickNameByCustId.get(response.getCustomerId()).getGroupNickname());
        }
        //车辆信息
        if (vehicleMapByOneId != null) {
          List<ScrmVehicleBasicInfoDTO> vehicleList = vehicleMapByOneId.get(response.getOneId());
          if (!CollectionUtils.isEmpty(vehicleList)) {
            ScrmVehicleBasicInfoDTO vehicle = vehicleList.get(0);
            response.setCarNumber(vehicle.getPlateNumber());
            response.setCarVin(vehicle.getStandNo());
            response.setAudi(vehicle.getVehicleSeries());
            Date buyTime = vehicle.getBuyTime();
            response.setBuyDate(buyTime == null ? null : DateUtils.formatNormal(buyTime));
          }
        }
        // 小区信息
        response.buildCommunityInfo("-");
      }
    }
  }

  /**
   * 客户详情查询(客户信息+标签+车辆)
   *
   * @param oneId
   * @param merchantId
   */
  public CustomerDetailResponse getCustomerDetail(String oneId, List<Integer> datalist,
      Integer merchantId, Integer staffId) {
    CustomerDetailResponse detailResponse = new CustomerDetailResponse();

    //获取客户信息
    CustomerInfoResponse customerInfo = customerMergeMapper.getCustomerByOneId(oneId, merchantId);
    if (customerInfo == null) {
      throw new RpcServiceException(BusinessExceptionEnum.IS_NOT_OUR_CUSTOMER.getValue(),
          BusinessExceptionEnum.IS_NOT_OUR_CUSTOMER.getDisplayName());
    }
    //替换客户事件表有优先级相关字段
    replaceCustomerEventInfo(customerInfo, merchantId);
    //当前服务业务数据组装
    buildCustomerDetail(customerInfo, detailResponse, oneId, merchantId);

    //=======================================标签数据============================================
    String merchantIds = com.glsx.plat.common.utils.StringUtils.join(datalist, ",");
    try {
      //获取数据中台的标签信息和车辆信息
      CustDetailRopRes detailRopRes = ropCommonServie.getLabelVehicleInfo(oneId, merchantIds,
          merchantId, staffId);
      if (null != detailRopRes) {
        //标签信息
        List<LabelListRopRes> labelInfoList = detailRopRes.getLabelInfoList();
        detailResponse.setLabels(labelInfoList);
        detailResponse.setLabelInfos(detailRopRes.getUserLabelUnitList());
      }
    } catch (Exception e) {
      log.info("获取客户在门店所有标签异常,oneId:{},merchantIds:{},msg:{}", oneId, merchantIds,
          e.getMessage());
    }

    // =====================================车辆等业务数据========================================
    ScrmCustomerDTO scrmCustomerDTO = new ScrmCustomerDTO();
    scrmCustomerDTO.setOneId(oneId);
    scrmCustomerDTO.setMerchantId(merchantId);
    scrmCustomerDTO.setConsumer("rpc-scrm-entmicro-container");
    scrmCustomerDTO.setVersion("v1.0.0.1");
    //维保信息 和 车辆信息
    detailResponse.setVehicleInfoList(getCustomerDetailVehicleAndMaintain(scrmCustomerDTO));
    // 设备信息
    detailResponse.setDeviceInfoList(getCusListDevice(scrmCustomerDTO));
    // 保单信息
    detailResponse.setInsureInfoList(getCustomerDetailListInsure(scrmCustomerDTO));
    log.info("客户详情:{}", detailResponse);

    return detailResponse;
  }

  /**
   * 查询事件表替换客户有优先级顺序的字段内容
   *
   * @param customerInfo 客户信息
   * @param merchantId   门店号
   */
  private void replaceCustomerEventInfo(CustomerInfoResponse customerInfo, Integer merchantId) {
    if (customerInfo.getOneId() == null) {
      return;
    }
    CustomerEventInfoRequestDTO requestDTO = new CustomerEventInfoRequestDTO();
    requestDTO.setListOneId(Collections.singletonList(customerInfo.getOneId()));
    requestDTO.setMerchantId(merchantId);
    RpcResponse<List<CustomerEventInfoResponseDTO>> response = scrmBigdataUtilRemote.getCustomerEventInfoByOneId(
        requestDTO);
    if (response.isSuccess() && response.hasResult()) {
      List<CustomerEventInfoResponseDTO> list = response.getResult();
      if (!CollectionUtils.isEmpty(list)) {
        CustomerEventInfoResponseDTO eventInfoResponseDTO = list.get(0);
        customerInfo.setCommunity(eventInfoResponseDTO.getCommunity());
        customerInfo.setBuilding(eventInfoResponseDTO.getBuilding());
        customerInfo.setRoom(eventInfoResponseDTO.getRoom());
        customerInfo.setHomeownerTypeValue(eventInfoResponseDTO.getHomeownerName());
      }
    } else if (response.isFailed()) {
      throw new RpcServiceException(response.getError(), response.getMessage());
    }
  }

  /**
   * 有优先级字段替换
   *
   * @param result
   * @param merchantId
   * @param oneIdList
   */
  private void replaceCustomerEventInfoFiles(List<CustomerListResponse> result, Integer merchantId,
      List<String> oneIdList) {
    if (CollectionUtils.isEmpty(oneIdList)) {
      return;
    }
    CustomerEventInfoRequestDTO requestDTO = new CustomerEventInfoRequestDTO();
    requestDTO.setListOneId(oneIdList);
    requestDTO.setMerchantId(merchantId);

    RpcResponse<List<CustomerEventInfoResponseDTO>> response = scrmBigdataUtilRemote.getCustomerEventInfoByOneId(
        requestDTO);
    if (response.isSuccess() && response.hasResult()) {
      List<CustomerEventInfoResponseDTO> list = response.getResult();
      if (!CollectionUtils.isEmpty(list)) {
        Map<String, CustomerEventInfoResponseDTO> map = list.stream().collect(
            Collectors.toMap(CustomerEventInfoResponseDTO::getOneId, identity(), (s1, s2) -> s1));
        for (CustomerListResponse customerListResponse : result) {
          if (customerListResponse.getOneId() == null) {
            continue;
          }
          CustomerEventInfoResponseDTO eventInfoResponseDTO = map.get(
              customerListResponse.getOneId());
          if (eventInfoResponseDTO != null) {
            customerListResponse.setCommunity(eventInfoResponseDTO.getCommunity());
            customerListResponse.setBuilding(eventInfoResponseDTO.getBuilding());
            customerListResponse.setRoom(eventInfoResponseDTO.getRoom());
          }
        }
      }
    } else if (response.isFailed()) {
      throw new RpcServiceException(response.getError(), response.getMessage());
    }
  }

  /**
   * 客户详情数据组装
   *
   * @param customerInfo
   * @param detailResponse
   */
  private void buildCustomerDetail(CustomerInfoResponse customerInfo,
      CustomerDetailResponse detailResponse, String oneId, Integer merchantId) {
    //名称emoji转化
    customerInfo.setCustomerName(customerInfo.getCustomerName() != null ? EmojiUtils.parseToUnicode(
        customerInfo.getCustomerName()) : null);

    //所属来源
    List<DictDataResponse> add_way = merchantService.findAllByDictType("add_way");
    List<String> collect = add_way.stream()
        .filter(index -> index.getDictValue().equals(customerInfo.getAddWay()))
        .map(DictDataResponse::getDictLabel).collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(collect)) {
      customerInfo.setAddWayName(collect.get(0));
    }

    //业主类型
//        Map<Integer, String> homeownerTypeMap = new HashMap<>();
//        List<DictDataResponse> businessTypeList = merchantService.findAllByDictType("homeowner_type");
//        if (!CollectionUtils.isEmpty(businessTypeList)) {
//            homeownerTypeMap = businessTypeList.stream().collect(Collectors.toMap(DictDataResponse::getDictValue, DictDataResponse::getDictLabel));
//        }
//        customerInfo.setHomeownerTypeValue(homeownerTypeMap.get(customerInfo.getHomeownerType()));

    //脱敏
    if (StringUtils.hasText(customerInfo.getIdCard())) {
      customerInfo.setIdCard(DataMaskingUtil.encryptionPhone(customerInfo.getIdCard()));
    }
    if (StringUtils.hasText(customerInfo.getCustomerPhone())) {
      customerInfo.setCustomerPhone(DataMaskingUtil.maskPhone(customerInfo.getCustomerPhone()));
    }
    detailResponse.setInfo(customerInfo);

    //所属跟进员工信息
    List<StaffFollowResponse> staffFollows = customerMapper.getStaffFollowByOneId(oneId,
        merchantId);
    log.info("客户:{}, 跟进员工信息:{}", customerInfo, staffFollows);
    if (!CollectionUtils.isEmpty(staffFollows)) {
      staffFollows.forEach(index -> {
        index.setStaffName(com.glsx.plat.common.utils.StringUtils.isNotEmpty(index.getStaffName())
            ? EmojiUtils.parseToUnicode(index.getStaffName()) : null);
        index.setDepartmentName(
            com.glsx.plat.common.utils.StringUtils.isNotEmpty(index.getDepartmentName())
                ? EmojiUtils.parseToUnicode(index.getDepartmentName()) : null);
        index.setRemark(com.glsx.plat.common.utils.StringUtils.isNotEmpty(index.getRemark())
            ? EmojiUtils.parseToUnicode(index.getRemark()) : null);
        String perfectMobiles = index.getRemarkMobiles();
        index.setPerfectMobiles(perfectMobiles);
        index.setAddType(index.getAddType() == null ? 2 : index.getAddType());
      });
    }
    detailResponse.setStaffFollows(staffFollows);

    // 所属客户群
    Map<Integer, BelongCustomerBaseResponse> customerBasesMap = customerMapper.getCustomerBaseByOneId(
        oneId, merchantId);
    // 统计每个群的人数
    ArrayList<BelongCustomerBaseResponse> countList = new ArrayList<>();
    if (null != customerBasesMap && customerBasesMap.size() > 0) {
      Set<Integer> Ids = customerBasesMap.keySet();
      Map<Integer, CustomerBaseCountResponse> countMap = customerMapper.countCustomerBase(Ids);
      for (Map.Entry<Integer, BelongCustomerBaseResponse> entry : customerBasesMap.entrySet()) {
        Integer key = entry.getKey();
        BelongCustomerBaseResponse value = entry.getValue();
        int count = 0;
        if (countMap.containsKey(key)) {
          CustomerBaseCountResponse countResponse = countMap.get(key);
          count = countResponse.getCountNum();
        }
        //emoji转化
        value.setGroupName(
            value.getGroupName() != null ? EmojiUtils.parseToUnicode(value.getGroupName()) : null);
        value.setGroupNickName(
            value.getGroupNickName() != null ? EmojiUtils.parseToUnicode(value.getGroupNickName())
                : null);
        value.setGroupHostName(
            value.getGroupHostName() != null ? EmojiUtils.parseToUnicode(value.getGroupHostName())
                : null);
        value.setMembersNumber(count);
      }
      Collection<BelongCustomerBaseResponse> values = customerBasesMap.values();
      countList.addAll(values);
    }
    detailResponse.setCustomerBases(countList);

    //设置企微名称
    List<String> oneIdList = new ArrayList<>();
    oneIdList.add(customerInfo.getOneId());
    List<CustomerNickNameRpcResponse> byBatchOneId = customerMapper.findByBatchOneId(oneIdList,
        merchantId);
    detailResponse.setNickNameList(setNickName(byBatchOneId, customerInfo.getOneId()));
  }

  /**
   * 车辆和维保信息
   *
   * @param scrmCustomerDTO
   */
  private List<VehicleInfoResponse> getCustomerDetailVehicleAndMaintain(
      ScrmCustomerDTO scrmCustomerDTO) {
    RpcResponse<List<ScrmMaintainBasicInfoDTO>> maintainResponse = scrmBigdataUtilRemote.getMaintain(
        scrmCustomerDTO);
    log.info("维保信息:{}", maintainResponse);
    Map<String, List<ScrmMaintainBasicInfoDTO>> mainByCarId = null;
    Map<String, List<ScrmMaintainBasicInfoDTO>> mainByCarVin = null;
    Map<String, List<ScrmMaintainBasicInfoDTO>> mainByCarNumber = null;
    if (maintainResponse != null && maintainResponse.isSuccess()) {
      List<ScrmMaintainBasicInfoDTO> maintainResult = maintainResponse.getResult();
      if (!CollectionUtils.isEmpty(maintainResult)) {
        mainByCarId = maintainResult.stream().filter(s -> s.getCarId() != null)
            .collect(Collectors.groupingBy(ScrmMaintainBasicInfoDTO::getCarId));
        mainByCarVin = maintainResult.stream().filter(s -> s.getCarVin() != null)
            .collect(Collectors.groupingBy(ScrmMaintainBasicInfoDTO::getCarVin));
        mainByCarNumber = maintainResult.stream().filter(s -> s.getCarNumber() != null)
            .collect(Collectors.groupingBy(ScrmMaintainBasicInfoDTO::getCarNumber));
      }
    }
    RpcResponse<List<ScrmVehicleBasicInfoDTO>> listVehicle = scrmBigdataUtilRemote.getListVehicle(
        scrmCustomerDTO);
    log.info("车辆信息:{}", listVehicle);
    List<ScrmVehicleBasicInfoDTO> vehicleResult = listVehicle.getResult();
    List<VehicleInfoResponse> vehicleInfoList = null;
    if (!CollectionUtils.isEmpty(vehicleResult)) {
      Map<String, List<ScrmMaintainBasicInfoDTO>> finalMainByCarId = mainByCarId;
      Map<String, List<ScrmMaintainBasicInfoDTO>> finalMainByCarVin = mainByCarVin;
      Map<String, List<ScrmMaintainBasicInfoDTO>> finalMainByCarNumber = mainByCarNumber;
      vehicleInfoList = vehicleResult.stream().map(index -> {
        VehicleInfoResponse vehicleInfoResponse = new VehicleInfoResponse();
        vehicleInfoResponse.setStandNo(
            Optional.ofNullable(index.getStandNo()).orElse(DEFAULT_DISPLAY));
        vehicleInfoResponse.setVehicleNo(
            Optional.ofNullable(index.getPlateNumber()).orElse(DEFAULT_DISPLAY));
        vehicleInfoResponse.setEngineNumber(
            Optional.ofNullable(index.getEngineNumber()).orElse(DEFAULT_DISPLAY));
        vehicleInfoResponse.setVehicleBrand(
            Optional.ofNullable(index.getVehicleBrand()).orElse(DEFAULT_DISPLAY));
        vehicleInfoResponse.setVehicleTrain(
            Optional.ofNullable(index.getVehicleSeries()).orElse(DEFAULT_DISPLAY));
        vehicleInfoResponse.setVehicleType(
            Optional.ofNullable(index.getVehicleType()).orElse(DEFAULT_DISPLAY));
        vehicleInfoResponse.setVehicleColor(
            Optional.ofNullable(index.getVehicleColor()).orElse(DEFAULT_DISPLAY));
        vehicleInfoResponse.setVehiclePrice(
            Optional.ofNullable(index.getVehiclePrice()).orElse(0.0));
        vehicleInfoResponse.setBuyTime(
            index.getBuyTime() != null ? DateUtils.format(index.getBuyTime(), "yyyy-MM-dd")
                : DEFAULT_DISPLAY);
        vehicleInfoResponse.setMaintRecTime(
            index.getLastMaintainTime() != null ? DateUtils.formatNormal(
                index.getLastMaintainTime()) : DEFAULT_DISPLAY);
        List<ScrmMaintainBasicInfoDTO> maintainList = null;
        if (finalMainByCarId != null) {
          maintainList = finalMainByCarId.get(index.getCarId());
          if (CollectionUtils.isEmpty(maintainList)) {
            maintainList = finalMainByCarVin.get(index.getStandNo());
            if (CollectionUtils.isEmpty(maintainList)) {
              maintainList = finalMainByCarNumber.get(index.getPlateNumber());
            }
          }
        }
        Date maintRecTime = maintainList == null ? null : maintainList.stream()
            .max(Comparator.comparing(ScrmMaintainBasicInfoDTO::getSettlementDate,
                Comparator.nullsFirst(Date::compareTo))).orElse(new ScrmMaintainBasicInfoDTO())
            .getSettlementDate();
        vehicleInfoResponse.setMaintRecTime(
            maintRecTime != null ? DateUtils.formatNormal(maintRecTime) : DEFAULT_DISPLAY);
        vehicleInfoResponse.setInsBgnTime(
            index.getMainInsureStartTime() != null ? DateUtils.formatNormal(
                index.getMainInsureStartTime()) : DEFAULT_DISPLAY);
        vehicleInfoResponse.setInsEndTime(
            index.getMainInsureEndTime() != null ? DateUtils.formatNormal(
                index.getMainInsureEndTime()) : DEFAULT_DISPLAY);
        return vehicleInfoResponse;
      }).sorted(Comparator.comparing(VehicleInfoResponse::getBuyTime,
          Comparator.nullsLast(String::compareTo)).reversed()).collect(Collectors.toList());
    }
    return vehicleInfoList;
  }

  /**
   * 设备信息
   *
   * @param scrmCustomerDTO
   */
  private List<DeviceInfoResponse> getCusListDevice(ScrmCustomerDTO scrmCustomerDTO) {
    //业务字段为空的情况下退出方法 避免接口查询数据过大导致资源超时,后续接口做了数据量限制处理可删掉
    if (StringUtils.isEmpty(scrmCustomerDTO.getOneId()) && StringUtils.isEmpty(
        scrmCustomerDTO.getMerchantId())) {
      return null;
    }
    RpcResponse<List<ScrmDeviceBasicInfoDTO>> listDevice = scrmBigdataUtilRemote.getListDevice(
        scrmCustomerDTO);
    log.info("设备信息:{}", listDevice);
    List<ScrmDeviceBasicInfoDTO> deviceResult = listDevice.getResult();
    List<DeviceInfoResponse> deviceInfoList = null;
    if (!CollectionUtils.isEmpty(deviceResult)) {
      deviceInfoList = deviceResult.stream().map(index -> {
        DeviceInfoResponse deviceInfoResponse = new DeviceInfoResponse();
        deviceInfoResponse.setSn(Optional.ofNullable(index.getSn()).orElse(DEFAULT_DISPLAY));
        deviceInfoResponse.setIccId(Optional.ofNullable(index.getIccid()).orElse(DEFAULT_DISPLAY));
        deviceInfoResponse.setDeviceType(
            Optional.ofNullable(index.getDeviceType()).orElse(DEFAULT_DISPLAY));
        deviceInfoResponse.setDeviceModel(
            Optional.ofNullable(index.getDeviceModel()).orElse(DEFAULT_DISPLAY));
        deviceInfoResponse.setVerificationCode(
            Optional.ofNullable(index.getVerificationCode()).orElse(DEFAULT_DISPLAY));
        deviceInfoResponse.setBatchNo(
            Optional.ofNullable(index.getBatchNo()).orElse(DEFAULT_DISPLAY));
        deviceInfoResponse.setStandNo(
            Optional.ofNullable(index.getStandNo()).orElse(DEFAULT_DISPLAY));
        deviceInfoResponse.setDeviceActiveTime(
            index.getDeviceActiveTime() != null ? DateUtils.formatNormal(
                index.getDeviceActiveTime()) : DEFAULT_DISPLAY);
        return deviceInfoResponse;
      }).sorted(Comparator.comparing(DeviceInfoResponse::getDeviceActiveTime,
          Comparator.nullsLast(String::compareTo)).reversed()).collect(Collectors.toList());
    }
    return deviceInfoList;
  }

  /**
   * 保单信息
   *
   * @param scrmCustomerDTO
   */
  private List<InsureInfoResponse> getCustomerDetailListInsure(ScrmCustomerDTO scrmCustomerDTO) {
    //业务字段为空的情况下退出方法 避免接口查询数据过大导致资源超时,后续接口做了数据量限制处理可删掉
    if (StringUtils.isEmpty(scrmCustomerDTO.getOneId()) && StringUtils.isEmpty(
        scrmCustomerDTO.getMerchantId()) && StringUtils.isEmpty(scrmCustomerDTO.getInsNo())) {
      return null;
    }
    RpcResponse<List<ScrmInsureBasicInfoDTO>> listInsure = scrmBigdataUtilRemote.getListInsure(
        scrmCustomerDTO);
    log.info("保单信息:{}", listInsure);
    List<ScrmInsureBasicInfoDTO> insureResult = listInsure.getResult();
    List<InsureInfoResponse> insureBasicInfoList = null;
    if (!CollectionUtils.isEmpty(insureResult)) {
      insureBasicInfoList = insureResult.stream().map(index -> {
        InsureInfoResponse insureInfoResponse = new InsureInfoResponse();
        insureInfoResponse.setAttInsureOrder(
            Optional.ofNullable(index.getAttInsureOrder()).orElse(DEFAULT_DISPLAY));
        insureInfoResponse.setAttProductName(
            Optional.ofNullable(index.getAttProductName()).orElse(DEFAULT_DISPLAY));
        Double term = index.getAttServicePeriod();
        insureInfoResponse.setAttServicePeriod(
            term == null || term <= 0 ? DEFAULT_DISPLAY : term.intValue() + "年");
        insureInfoResponse.setAttServiceCompany(
            Optional.ofNullable(index.getAttServiceCompany()).orElse(DEFAULT_DISPLAY));
        insureInfoResponse.setAttInsureStartTime(
            index.getAttInsureStartTime() != null ? DateUtils.formatNormal(
                index.getAttInsureStartTime()) : DEFAULT_DISPLAY);
        insureInfoResponse.setAttInsureEndTime(
            index.getAttInsureEndTime() != null ? DateUtils.formatNormal(
                index.getAttInsureEndTime()) : DEFAULT_DISPLAY);
        insureInfoResponse.setAttInsureSubmitTime(
            index.getAttInsureSubmitTime() != null ? DateUtils.formatNormal(
                index.getAttInsureSubmitTime()) : DEFAULT_DISPLAY);
        insureInfoResponse.setStandNo(
            Optional.ofNullable(index.getStandNo()).orElse(DEFAULT_DISPLAY));
        return insureInfoResponse;
      }).sorted(Comparator.comparing(InsureInfoResponse::getAttInsureSubmitTime,
          Comparator.nullsLast(String::compareTo)).reversed()).collect(Collectors.toList());
    }
    return insureBasicInfoList;
  }

  /**
   * 客户新增
   */
  public void customerAdd(CustomerStandardRequest request, boolean statics, Integer merchantId) {
    // 1.客户基本信息
    CustomerInfoRequest customerInfo = request.getCustomerInfo();
    String busType = "";
    String[] codes = {};
    if (request.getState() != null) {
      codes = request.getState().split("-");
      busType = codes[0];
    }
    //获取回调备注的手机号
    if (!StringUtils.isEmpty(request.getState())) {
      //查询智能营销渠道信息
      String phoneByState = null;
      if (AddCustomerType.DARC_HANDER.getBusType().equals(busType)) {
        phoneByState = dracImService.findPhoneByState(request.getState());
        //查询轻改配置专家渠道信息
      } else if (AddCustomerType.OPRATION.getBusType().equals(busType)) {
        OperationCustomer operationCustomer = operationCustomerService.getOperationCustomer(
            request.getState());
        if (null != operationCustomer) {
          phoneByState = operationCustomer.getCustomerPhone();
          // 添加好友成功,删除永久码 修改时间2024-06-11
          QGCodeConfig byCodeState = qgCodeConfigMapper.findByCodeState(request.getState());
          if(byCodeState!=null){
            byCodeState.setDelFlag((byte)-1);
            byCodeState.setUpdatedTime(new Date());
            qgCodeConfigMapper.updateByPrimaryKeySelective(byCodeState);
          }
        }
      } else if (AddCustomerType.RESCUE.getBusType().equals(busType)) {
        if (codes.length > 1) {
          phoneByState = codes[2];
        }
      } else {
        phoneByState = addEntmicroRelationMapper.findByState(request.getState());
      }
      customerInfo.setCustomerPhone(phoneByState);
    }
    log.info("新增客户入参: {}", request);
    // 2.校验客户是否存在,目前通过userid
    Customer customer = customerMapper.getCustomerByUserId(customerInfo.getUserid());
    List<CustomerFollowerStaffRequest> followerStaff = new ArrayList<>();
    // 分布式锁添加
    boolean lock = redisLock.getLock(LOCK_ID + customerInfo.getUserid(), 10 * 1000);
    try {
      if (lock) {
        if (null != customer) {
          followerStaff = setAddWayAndPhone(request, customer);
          log.info("客户{}已经存在", customerInfo.getCustomerName());
          Customer param = new Customer();
          BeanUtils.copyProperties(customerInfo, param);
          log.info("存在客户{}", customer);
          param.setId(customer.getId());
          param.setUpdatedBy(UserLocalUtils.getCreatedId());
          param.setDelFlag(Constants.NORMAL_FLAG);
          param.setUpdatedTime(new Date());
          param.setCustomerName(
              EmojiUtils.parseToHtmlHexadecimal((customerInfo.getCustomerName())));
          param.setAddWay(null);
          param.setState(request.getState());
          log.info("更新客户参数{}", param);
          customerMapper.updateByPrimaryKeySelective(param);
        } else {
          customer = BeanConverUtil.conver(customerInfo, Customer.class);
          customer.setCreatedBy(UserLocalUtils.getCreatedId());
          customer.setDelFlag(Constants.NORMAL_FLAG);
          customer.setCustomerName(EmojiUtils.parseToHtmlHexadecimal((customer.getCustomerName())));
          customer.setState(request.getState());
          //获取跟进人
          followerStaff = setAddWayAndPhone(request, customer);
          if (busType.equals("DARC")) {
            customer.setAddWay(addwayMagic);
          }
          log.info("新增客户{}", customer);
          customerMapper.insertUseGeneratedKeys(customer);
        }
      }
    } catch (Exception e) {
      log.info("更新客户信息异常: {}", e);
    } finally {
      redisLock.releaseLock(LOCK_ID + customerInfo.getUserid());
    }

    //解析备注补充手机号
    readRemark(followerStaff, customerInfo);
    customer.setRemarkPhone(customerInfo.getCustomerPhone());
    log.info("解析补充新增客户手机号:{}", JSONArray.toJSONString(customerInfo));
    int i = customerMapper.updatePhoneByUserId(Arrays.asList(customer));
    if (i > 0) {
      entmicroCustomerFollowMapper.updateBatchInfo(Arrays.asList(customer));
    }

    //跟进人关联信息(如果有就保存)
    Integer customerId = customer.getId();
    log.info("新增客户的跟进人信息{}", followerStaff);
    EntmicroCustomerFollow entmicroCustomerFollow;
    if (!CollectionUtils.isEmpty(followerStaff)) {
      followerStaff.stream().forEach(staff -> {
        staff.setMerchantId(merchantId);
        //如果跟进人没有备注手机号 则使用解析出来的备注手机号补充
        if (StringUtils.isEmpty(staff.getRemarkMobiles())) {
          staff.setRemarkMobiles(customerInfo.getCustomerPhone());
        }
      });

      //查询跟进人
      List<String> userIds = followerStaff.stream().map(CustomerFollowerStaffRequest::getUserId)
          .collect(Collectors.toList());
      List<EntmicroStaffResponse> staffsExist = entmicroStaffService.getListByUserIds(userIds,
          merchantId);
      log.info("customerAdd userIds:{},followerEntmicroStaff:{}", userIds, staffsExist);
      Map<String, String> staffIdNameMap = staffsExist.stream().collect(
          Collectors.toMap(EntmicroStaffResponse::getUserId, EntmicroStaffResponse::getStaffName,
              (o1, o2) -> o1));

      List<EntmicroCustomerFollow> entmicroCustomerFollowList = buildFollowParamAdd(followerStaff,
          customerId);
      entmicroCustomerFollow = followService.insert(entmicroCustomerFollowList);
      if (null != entmicroCustomerFollow) {
        request.setCustomerFollowId(entmicroCustomerFollow.getId());
        request.setStaffId(entmicroCustomerFollow.getStaffId());
      }

      //同步业务数据
      syncCustomerData(entmicroCustomerFollowList, "1", customerInfo, customer);

      //维格表异步更新
      asyncUpdate2Vika(merchantId, customerInfo, followerStaff, staffIdNameMap);
      //  加好友回调更新外呼好友状态
      if (!StringUtils.isEmpty(customerInfo.getCustomerPhone())) {
        outboundCallTaskCustomerService.updatePhoneStatus(entmicroCustomerFollowList,
            customerInfo.getCustomerPhone(), request.getWelcomeCode(), request.getExternalUserId(),
            customer.getId(), request.getState());
      }
    }

        //  客户新增回调添加标签 /发送欢迎语 / 更新好友状态
        String handerType = AddCustomerType.getHanderType(busType);
        if (!StringUtils.isEmpty(handerType)) {
            AddCustomerReceiptService instance = BussinessFactory.getInstance(handerType, AddCustomerReceiptService.class);
            instance.addCustomerReceipt(buildCustomerModel(request, customer.getId(), merchantId));
        }
    }

  private void asyncUpdate2Vika(Integer merchantId, CustomerInfoRequest customerInfo,
      List<CustomerFollowerStaffRequest> followerStaff, Map<String, String> staffIdNameMap) {
    try {
      if (Objects.equals(merchantId.toString(),
          environment.getProperty("vika.authorize.merchantId"))) {
        CompletableFuture.runAsync(
            () -> {
              log.info("start syncVikaWeChatContacts");
              // 过滤配置门店的客户 2023-07-19
              String property = environment.getProperty("vika.sync.merchantId");
              String userId = environment.getProperty("vika.sync.exclude.userId");
              List<Integer> merchantIds = followerStaff.stream()
                  .map(CustomerFollowerStaffRequest::getMerchantId).collect(Collectors.toList());
              List<String> userIdS = followerStaff.stream()
                  .map(CustomerFollowerStaffRequest::getUserId).collect(Collectors.toList());
              if (!StringUtils.isEmpty(property) && merchantIds.contains(Integer.parseInt(property))
                  && !StringUtils.isEmpty(userId) && userIdS.contains(userId)) {
                WeChatContactsDTO weChatContactsDTO = buildWeChatContactsDTO(customerInfo,
                    followerStaff, staffIdNameMap);
                log.info("syncVikaWeChatContacts_update:{}", JSON.toJSONString(weChatContactsDTO));
                vikaWeChatContactsRemote.syncVikaWeChatContacts(weChatContactsDTO);
              }
            }
        );
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error("syncVikaWeChatContacts_update error{}", e.getMessage(), e);
    }
  }

  private static WeChatContactsDTO buildWeChatContactsDTO(CustomerInfoRequest customerInfo,
      List<CustomerFollowerStaffRequest> followList,
      Map<String, String> staffIdNameMap) {
    WeChatContactsDTO weChatContactsDTO = new WeChatContactsDTO();
    weChatContactsDTO.setWeChatId(customerInfo.getUserid());
    weChatContactsDTO.setNickName(customerInfo.getCustomerName());
    weChatContactsDTO.setAvatar(customerInfo.getAvatar());
    weChatContactsDTO.setPhone(customerInfo.getCustomerPhone());
    if (CollectionUtils.isEmpty(followList)) {
      return weChatContactsDTO;
    }
    List<StaffInfoDTO> staffInfoList = followList.stream()
        .map(e -> {
          List<String> cpWxTagIds = Lists.newArrayList();
          if (!CollectionUtils.isEmpty(e.getTagList())) {
            cpWxTagIds = e.getTagList().stream().map(FollowTagRequest::getTagId)
                .collect(Collectors.toList());
          }
          return new StaffInfoDTO(staffIdNameMap.get(e.getUserId()), cpWxTagIds);
        }).collect(Collectors.toList());
    weChatContactsDTO.setStaffInfoList(staffInfoList);
    return weChatContactsDTO;
  }

  /**
   * 构建客户回调model
   *
   * @param request
   * @return
   */
  private CustomerReceiptModel buildCustomerModel(CustomerStandardRequest request, Integer id,
      Integer merchantId) {
    CustomerReceiptModel customerReceiptModel = new CustomerReceiptModel();
    customerReceiptModel.setUserId(request.getExternalUserId());
    customerReceiptModel.setPhone(request.getCustomerInfo().getCustomerPhone());
    customerReceiptModel.setWelcomeCode(request.getWelcomeCode());
    customerReceiptModel.setState(request.getState());
    customerReceiptModel.setId(id);
    customerReceiptModel.setCustomerFollowId(request.getCustomerFollowId());
    customerReceiptModel.setMerchantId(merchantId);
    customerReceiptModel.setStaffId(request.getStaffId());
    customerReceiptModel.setAddStaffUserId(request.getAddStaffUserId());
    List<CustomerFollowerStaffRequest> followerStaff = request.getFollowerStaff();
    if (!CollectionUtils.isEmpty(followerStaff)) {
      List<String> collect = followerStaff.stream().map(CustomerFollowerStaffRequest::getUserId)
          .collect(Collectors.toList());
      customerReceiptModel.setStaffUserIds(collect);
    }
    return customerReceiptModel;
  }

  /**
   * 企微魔方客户新增
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
  public List<CustomerMagicResponse> customerAddMagic(MagicDynamicRequest magicDynamicRequest) {
    log.info("企微魔方客户新增:{}", JSONArray.toJSONString(magicDynamicRequest));
    List<CustomerMagicResponse> resList = new ArrayList<>();
    if (magicDynamicRequest == null || CollectionUtils.isEmpty(
        magicDynamicRequest.getCustomers())) {
      return new ArrayList<>();
    }
    //客户数据
    List<MagicDynamicInfoRequest> customers = magicDynamicRequest.getCustomers();
    Map<String, MagicDynamicInfoRequest> customer_phone = customers.stream().collect(
        Collectors.toMap(MagicDynamicInfoRequest::getCustomerPhone, identity(), (t1, t2) -> t1));
    // 查询导入的手机号
    List<String> phones = new ArrayList<>(customer_phone.keySet());
    if (CollectionUtils.isEmpty(phones)) {
      return new ArrayList<>();
    }
    // 查询库里已有的手机号
    List<Customer> existPhones = customerMapper.findCustomerByPhones(phones,
        magicDynamicRequest.getMerchantId());
    Map<String, Customer> existPhonesMap = null;

    //过滤手机号
    List<String> existPhonesList = existPhones.stream().map(Customer::getCustomerPhone)
        .collect(Collectors.toList());

    if (!CollectionUtils.isEmpty(existPhones)) {
      existPhonesMap = existPhones.stream()
          .collect(Collectors.toMap(Customer::getCustomerPhone, identity()));
    }

    // 构建数据返回
    List<String> addPhones = phones.stream().filter(index -> !existPhonesList.contains(index))
        .collect(Collectors.toList());
    List<String> updatePhones = phones.stream().filter(index -> existPhonesList.contains(index))
        .collect(Collectors.toList());
    List<CustomerMagicRequest> addList = getCustomerInfoMap(addPhones, customer_phone);
    List<CustomerMagicRequest> updateList = getCustomerInfoMap(updatePhones, customer_phone);
    // 构建数据返回
    buildUpdateMagicCusomerRes(updateList, existPhonesMap, resList);
    addMagicCustomer(magicDynamicRequest.getMerchantId(), addList, resList);

    // 异步更新数据,并同步数据到大叔据
    if (magicDynamicRequest.getDataType() == null) {
      customerDetailMagicAsyncComponent.asyncUpdateCustomerDetailForMagic(addList, updateList,
          existPhonesMap, magicDynamicRequest);
    } else if (magicDynamicRequest.getDataType().intValue() == 2) {
      customerDetailMagicAsyncComponent.updateCustomerDetailForMagic(addList, updateList,
          existPhonesMap, magicDynamicRequest);
    }
    return resList;
  }

  /**
   * 数据组装
   *
   * @param updatePhones
   * @return
   */
  private List<CustomerMagicRequest> getCustomerInfoMap(List<String> updatePhones,
      Map<String, MagicDynamicInfoRequest> stringListMap) {
    //List<CarbrandModel> carBrand = merchantService.findCarBrand();
    List<CustomerMagicRequest> collect = updatePhones.stream().map(index -> {
      CustomerMagicRequest customerMagicRequest = new CustomerMagicRequest();
      MagicDynamicInfoRequest magicDynamicInfoRequest = stringListMap.get(index);
      Map<String, Object> custAttr = magicDynamicInfoRequest.getCustAttr();
      customerMagicRequest.setAddWay(magicDynamicInfoRequest.getAddWay());
      customerMagicRequest.setCustomerPhone(custAttr.get("customer_phone") + "");
      if (custAttr.get("customer_name") != null) {
        customerMagicRequest.setCustomerName(custAttr.get("customer_name") + "");
      }
      customerMagicRequest.setCustomerSex(
          custAttr.get("customer_sex") != null ? Integer.parseInt(custAttr.get("customer_sex") + "")
              : null);
      Map<String, Object> baseAttr = magicDynamicInfoRequest.getBaseAttr();
      if (custAttr.get("customer_idcard_no") != null) {
        customerMagicRequest.setIdCard(custAttr.get("customer_idcard_no") + "");
        if (Integer.parseInt(customerMagicRequest.getIdCard().substring(16).substring(0, 1)) % 2
            == 0) {
          customerMagicRequest.setCustomerSex(1);
        } else {
          customerMagicRequest.setCustomerSex(2);
        }
      }

      customerMagicRequest.setBuyDate(baseAttr.get("car_buying_date") != null ? DateUtil.parse(
          baseAttr.get("car_buying_date") + "") : null);
      customerMagicRequest.setArrivalDate(
          baseAttr.get("recent_arrival_date") != null ? DateUtil.parse(
              baseAttr.get("recent_arrival_date") + "") : null);
      customerMagicRequest.setAudi(
          baseAttr.get("car_series") != null ? baseAttr.get("car_series") + "" : null);
      customerMagicRequest.setCarType(
          baseAttr.get("car_model") != null ? baseAttr.get("car_model") + "" : null);
      customerMagicRequest.setCarBrand(
          baseAttr.get("car_brand") != null ? baseAttr.get("car_brand") + "" : null);
      customerMagicRequest.setCarVin(
          baseAttr.get("car_vin") != null ? baseAttr.get("car_vin") + "" : null);
      customerMagicRequest.setCarNumber(
          baseAttr.get("car_number") != null ? baseAttr.get("car_number") + "" : null);
      customerMagicRequest.setComInsuranceStarttime(
          baseAttr.get("effective_date_of_commercial_insurance") != null ? DateUtil.parse(
              baseAttr.get("effective_date_of_commercial_insurance") + "") : null);
      customerMagicRequest.setComInsuranceEndtime(
          baseAttr.get("commercial_insurance_expiration_date") != null ? DateUtil.parse(
              baseAttr.get("commercial_insurance_expiration_date") + "") : null);
      customerMagicRequest.setMaintenanceDate(
          baseAttr.get("recent_maintenance_date") != null ? DateUtil.parse(
              baseAttr.get("recent_maintenance_date") + "") : null);
           /* if (baseAttr.get("car_brand") != null) {
                List<CarbrandModel> car_brand = carBrand.stream().filter(ind -> ind.getLabel().equals(baseAttr.get("car_brand") + "")).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(car_brand)) {
                    int size = car_brand.size();
                    if (size == 1) {
                        customerMagicRequest.setCarBrandIds(car_brand.get(0).getId() + "");
                    }
                }
            }*/
      return customerMagicRequest;
    }).collect(Collectors.toList());
    return collect;
  }

  /**
   * tools - 构建添加返回数据
   *
   * @param merchantId
   * @param addList
   * @param resList
   */
  private void addMagicCustomer(Integer merchantId, List<CustomerMagicRequest> addList,
      List<CustomerMagicResponse> resList) {
    if (CollectionUtils.isEmpty(addList)) {
      return;
    }

    // 整理插入数据
    List<CustomerMagicResponse> saveSyncList = addList.stream()
        .filter(req -> !StringUtils.isEmpty(req.getCustomerPhone())).map(req -> {
          Customer customer = MagicImportCustomerConvert.buildCustomerByMagic(merchantId, req, true,
              addwayMagic, req.getAddWay());
          CustomerMagicResponse response = MagicImportCustomerConvert.buildCustomerResByMagic(
              customer, true);
          return response;
        }).collect(Collectors.toList());

    if (CollectionUtils.isEmpty(saveSyncList)) {
      return;
    }
    resList.addAll(saveSyncList);
  }

  /**
   * tools - 构建更新返回数据
   *
   * @param updateList
   * @param existPhonesMap
   * @param resList
   */
  private void buildUpdateMagicCusomerRes(List<CustomerMagicRequest> updateList,
      Map<String, Customer> existPhonesMap, List<CustomerMagicResponse> resList) {
    if (CollectionUtils.isEmpty(updateList)) {
      return;
    }

    List<CustomerMagicResponse> updateAddList = updateList.stream()
        .filter(req -> existPhonesMap.get(req.getCustomerPhone()) != null).map(req -> {
          CustomerMagicResponse response = MagicImportCustomerConvert.buildCustomerResByMagic(
              existPhonesMap.get(req.getCustomerPhone()), false);
          return response;
        }).collect(Collectors.toList());

    if (CollectionUtils.isEmpty(updateAddList)) {
      return;
    }
    resList.addAll(updateAddList);
  }

  /**
   * 没有跟进人的客户入群
   */
  public Customer customerAddBase(CustomerAddBaseRequest customerAddBaseRequest) {
    //本地入库
    Customer customer = new Customer();
    BeanUtils.copyProperties(customerAddBaseRequest, customer);
    customer.setDelFlag(Constants.NORMAL_FLAG);
    customer.setUserid(customerAddBaseRequest.getUserId());
    customerMapper.insertUseGeneratedKeys(customer);
    return customer;
  }

  /**
   * 同步客户数据到大数据
   *
   * @param staff_id   员工id
   * @param type       类型
   * @param merchantId 商户号
   */
//    @Async("taskExecutor")
  public void syncCustomerToBigData(Integer staff_id, String type, Integer merchantId) {
    // 查询当前员工下的客户
    List<CustomerInfoResponse> customerByStaffId = findCustomerByStaffId(staff_id, null);
    customerByStaffId.forEach(index -> {
      log.info("同步客户到大数据{},商户号{},类型{}", index.getId(), merchantId, type);
      syncCustomerData(index.getId(), type, merchantId, null, staff_id);
    });
  }

  /**
   * 同步客户数据到数据平台
   *
   * @param customerId scrm_customer主键
   * @param type       类型
   * @param merchantId 门店号
   * @param tags       标签信息
   * @param staffId    员工主键
   */
  public void syncCustomerData(Integer customerId, String type, Integer
      merchantId, List<FollowTagRequest> tags, Integer staffId) {
    //同步客户数据到数据平台    type  0 新增 1 删除 2 更改"
    log.info("同步客户,customerId:{},type:{}", customerId, type);

    //不同merchantId为不同的客户
    //查询本地客户信息
    CustomerInfo customer = customerMapper.getCustomerById(customerId, staffId);
    if (null == customer) {
      log.info("同步客户失败,customerId不存在:{}", customerId);
      return;
    }
    log.info("同步客户信息本地数据:{}", JSONArray.toJSONString(customer));
    CustomerSync cust = BeanConverUtil.conver(customer, CustomerSync.class);
    //获取oneId
    RpcResponse<String> stringRpcResponse = oneIdRemote.oneIdCreated(
        buildOneIdRequest(cust, merchantId));
    if (null == stringRpcResponse || stringRpcResponse.isFailed()) {
      log.info("同步客户失败,customerId:{},type:{},merchantId:{}", customerId, type, merchantId);
      return;
    }
    String oneId = stringRpcResponse.getResult();
    //更新基础客户oneid
    log.info("同步客户数据更新基础表oneId:{}, customerId: {}", oneId, customerId);
    customerMapper.updateOneIdByCust(oneId, customerId);
    //新增或更新业务客户oneId
    CustomerMerge merge = new CustomerMerge(oneId);
    merge.setMerchantId(merchantId);
    //调用数据平台方接口同步标签
    cust.setId(customerId);
    cust.setMerchantid(merchantId);
    cust.setStaffId(staffId);
    cust.setOneId(oneId);
    if (!CollectionUtils.isEmpty(tags)) {
      String jsonStr = JSONObject.toJSONString(tags);
      cust.setTags(jsonStr);
      log.info("同步客户标签customerId:{},tags:{}", customerId, jsonStr);
    }
    ropCommonServie.getOneId(cust, type);

    //构建客户信息
    mergeCustomerInfo(merge, cust, type, oneId);

    //更新或插入合并表
    updateMergeCustomer(merge, oneId, false);
  }

  /**
   * 构建客户oneid识别参数
   *
   * @param cust       客户信息
   * @param merchantId 商户号
   * @return
   */
  private OneIdEevent buildOneIdRequest(CustomerSync cust, Integer merchantId) {
    OneIdEevent oneIdEevent = new OneIdEevent();
    oneIdEevent.setEventType(OneIdEventEnum.EVENTTYPE_BINDING.getType());
    oneIdEevent.setMainstay(OneIdProEnum.ONEIDPRO_CUSTOMER.getType());
    oneIdEevent.setMerchantId(merchantId);
    Map<String, String> map = new HashMap<>();
    map.put("customer_phone", cust.getCustomerPhone());
    map.put("user_id", cust.getUserId());
    map.put("union_id", cust.getUnionid());
    map.put("customer_qw_nickname", cust.getCustomerName());
    oneIdEevent.setJson(JSONObject.toJSONString(map));
    return oneIdEevent;
  }

  /**
   * 构建客户状态
   *
   * @param merge
   * @param cust
   * @param type
   * @param oneId
   */
  private void mergeCustomerInfo(CustomerMerge merge, CustomerSync cust, String type,
      String oneId) {
    log.info("构建客户状态:{}, type: {}", JSONArray.toJSONString(cust), type);
    BeanUtils.copyProperties(cust, merge);
    merge.setOneId(oneId);
    String createdTime = cust.getCreatedTime();
    merge.setCreatedTime(DateUtils.stringToDate(createdTime, DateUtils.NORMAL_DATE_TIME_PATTERN));
    merge.setIsJoin(1);
    merge.setStatus(0);
    merge.setAddWay(cust.getAddWay());
    merge.setUnionId(cust.getUnionid());
    if (type.equals("0")) {
      int customerByOneId = customerMapper.getCustomerByOneId(oneId, merge.getMerchantId());
      if (customerByOneId == 0) {
        merge.setIsJoin(0);
        merge.setStatus(-1);
      }
    }
  }


  /**
   * oneid更新客户数据到数据平台
   *
   * @param merge
   * @param oneId
   * @param addWayFlag true oneId变更  false oneId不变更
   */
  public void updateMergeCustomer(CustomerMerge merge, String oneId, boolean addWayFlag) {
    CustomerInfoResponse customerByOneId = customerMergeMapper.getCustomerByOneId(oneId,
        merge.getMerchantId());
    log.info("oneid更新客户数据到数据平台: {}", JSONArray.toJSONString(customerByOneId));
    if (null == customerByOneId) {
      try {
        // 分布式锁添加
        boolean lock = redisLock.getLock(LOCK_ID + oneId, 10 * 1000);
        if (lock) {
          //不存在,新增
          merge.setOneId(oneId);
          merge.setDelFlag(Constants.NORMAL_FLAG);
          merge.setId(null);
          merge.setUpdatedTime(new Date());
          merge.setDataCreateTime(new Date());
          log.info("oneid:{},新增合并表:{}", oneId, JSONArray.toJSONString(merge));
          //字段合并处理
          setInsertMergeRegex(merge);
          customerMergeMapper.insert(merge);
        }
      } catch (Exception e) {
        log.info("更新客户信息异常{}", e);
      } finally {
        redisLock.releaseLock(LOCK_ID + oneId);
      }
    } else {
      log.info("更新合并表原数据: {}", JSONArray.toJSONString(merge));
      //字段合并处理
      setUpdateMergeRegex(customerByOneId, merge, addWayFlag);
      //存在,更新
      merge.setDelFlag(Constants.NORMAL_FLAG);
      merge.setId(Integer.valueOf(customerByOneId.getId()));
      merge.setUpdatedTime(new Date());
      log.info("oneid:{},更新合并表:{}", oneId, JSONArray.toJSONString(merge));
      customerMergeMapper.updateByPrimaryKeySelective(merge);
    }
  }

  /**
   * 客户新增合并表 名称合并规则
   *
   * @param newData
   */
  private void setInsertMergeRegex(CustomerMerge newData) {
    //读取配置优先级
    JSONObject jsonObject = JSONObject.parseObject(mergeRegex);
    String versionInfoStr = jsonObject.getString("addWayList");
    List<MergeLevelDTO> mergeLevelDTOS = JSONObject.parseArray(versionInfoStr, MergeLevelDTO.class);
    Map<Integer, MergeLevelDTO> collect = mergeLevelDTOS.stream()
        .collect(Collectors.toMap(MergeLevelDTO::getDictValue, identity(), (key1, key2) -> key2));
    int newAddWay = newData.getAddWay() == null ? 0 : newData.getAddWay();
    //如果来源字段不在合并规则里 则名称不新增
    if (!collect.containsKey(newAddWay)) {
      newData.setCustomerName(null);
    }
  }

  /**
   * 客户姓名和性别合并规则
   *
   * @param oldData
   * @param newData
   */
  private void setUpdateMergeRegex(CustomerInfoResponse oldData, CustomerMerge newData,
      boolean addWayFlag) {
    //读取配置优先级
    JSONObject jsonObject = JSONObject.parseObject(mergeRegex);
    String versionInfoStr = jsonObject.getString("addWayList");
    List<MergeLevelDTO> mergeLevelDTOS = JSONObject.parseArray(versionInfoStr, MergeLevelDTO.class);
    Map<Integer, MergeLevelDTO> collect = mergeLevelDTOS.stream()
        .collect(Collectors.toMap(MergeLevelDTO::getDictValue, identity(), (key1, key2) -> key2));
    int newAddWay = newData.getAddWay() == null ? 0 : newData.getAddWay();
    int oldAddWay = oldData.getAddWay() == null ? 0 : oldData.getAddWay();
    MergeLevelDTO newDataDTO = collect.get(newAddWay);
    MergeLevelDTO oldDataDTO = collect.get(oldAddWay);
    //名称性别合并
    //两者都涉及合并来源 比较优先级大
    if (null != newDataDTO && null != oldDataDTO) {
      Integer newKey = newDataDTO.getLevelKey();
      Integer oldKey = oldDataDTO.getLevelKey();
      //新数据来源小于旧数据来源优先级 levelKey越小 优先级越大
      if (newKey > oldKey) {
        log.info("新数据来源小于旧数据来源优先级");
        newData.setCustomerName(null);
        newData.setCustomerSex(null);
      }
    }//老数据涉及合并来源 新数据没有
    else if (null != oldDataDTO && null == newDataDTO) {
      log.info("老数据涉及合并来源 新数据没有");
      newData.setCustomerName(null);
      newData.setCustomerSex(null);
    }

    //企微状态合并
    int oldIsJoin = oldData.getIsJoin() == null ? 0 : oldData.getIsJoin();
    int newIsJoin = newData.getIsJoin() == null ? 0 : newData.getIsJoin();
    newData.setIsJoin(Math.max(oldIsJoin, newIsJoin));

    Integer type = newData.getType();
    if (type != null && type.intValue() == 1) {
      // 如果企微客户不合并企微名称
      if (!StringUtils.isEmpty(newData.getCustomerName())) {
        newData.setCustomerName(null);
      }
    } else {
      if (!StringUtils.isEmpty(oldData.getCustomerSex())) {
        // 如果是微信客户不合并性别
        newData.setCustomerSex(null);
      }
    }
    //取最小时间的oneId 旧oneId的时间小于新oneId则不更新, 反之更新
    if (oldData.getAddTime() != null && newData.getCreatedTime() != null) {
      if (oldData.getAddTime().compareTo(newData.getCreatedTime()) < 0) {
        newData.setCreatedTime(null);
      }
    }
    // oneId不变更不覆盖来源 || oneId变更则允许更新来源 false 变更
    if (oldData.getAddWay() != null && addWayFlag == false) {
      newData.setAddWay(null);
    }
    if (newData.getStatus() != null && newData.getStatus().equals(Constants.DEL_FLAG)) {
      //删除好友不更新名字
      newData.setCustomerName(null);
    }
  }

  /**
   * 构建跟进人参数
   *
   * @param followerStaff
   * @param customerId
   * @return
   */
  private List<EntmicroCustomerFollow> buildFollowParamAdd
  (List<CustomerFollowerStaffRequest> followerStaff, Integer customerId) {
    log.info("员工打印{}", followerStaff);
    //商户号
    Integer merchantId = followerStaff.get(0).getMerchantId();
    //获取子门店
    List<Integer> subordinateMerchantList = entmicroStaffService.findAuthorizeMerchantNo(
        merchantId);

    log.info("buildFollowParam====merchantId:{},subordinateMerchantList:{}", merchantId,
        subordinateMerchantList);

    //<userid,List<CustomerFollowerStaffRequest>>
    Map<String, CustomerFollowerStaffRequest> map = followerStaff.stream().collect(
        Collectors.toMap(CustomerFollowerStaffRequest::getUserId, identity(),
            (item1, item2) -> item1));

    //转为userid
    List<String> userIds = new ArrayList<>(map.keySet());

    //查询跟进人
    List<EntmicroStaffResponse> staffsExist = entmicroStaffService.getListByUserIds(userIds,
        merchantId);
    log.info("buildFollowParam====userIds:{},staffsExist:{}", userIds, staffsExist);

    if (null == staffsExist || staffsExist.isEmpty()) {
      return null;
    }

    //过滤出商户号在门店范围内的
    List<Integer> finalSubordinateMerchantList = subordinateMerchantList;
    List<EntmicroCustomerFollow> staffFollowRelations = staffsExist.stream().filter(staff -> {
      Integer merchantIdStaff = staff.getMerchantId();
      return finalSubordinateMerchantList.contains(merchantIdStaff);
    }).map(staff -> {
      String userId = staff.getUserId();
      Integer staffId = staff.getId();
      //拿出userId相同的跟进人信息
      CustomerFollowerStaffRequest entmicroStaff = map.get(userId);
      EntmicroCustomerFollow customerFollow = BeanConverUtil.conver(entmicroStaff,
          EntmicroCustomerFollow.class);
      customerFollow.setCustomerId(customerId);
      customerFollow.setStaffId(staffId);
      customerFollow.setDelFlag(Constants.NORMAL_FLAG);
      if (customerFollow.getRemark() != null) {
        customerFollow.setRemark(EmojiUtils.parseToHtmlHexadecimal((customerFollow.getRemark())));
      }
      customerFollow.setTagList(entmicroStaff.getTagList());
      return customerFollow;
    }).collect(Collectors.toList());

    log.info("buildFollowParam====staffFollowRelations:{}", staffFollowRelations);
    return staffFollowRelations;
  }

  /**
   * 客户编辑
   */
  public void customerEdit(CustomerStandardRequest customerStandardRequest,
      boolean statics, Integer merchantId) {
    log.info("CustomerService_Invoke_customerEdit_request:{},statics:{},merchantId:{}",
        JSONArray.toJSONString(customerStandardRequest), statics, merchantId);
    CustomerInfoRequest customerInfo = customerStandardRequest.getCustomerInfo();
    Customer customer = customerMapper.getCustomerByUserId(customerInfo.getUserid());
    if (null == customer) {
      log.info("客户{}未找到", customerInfo.getCustomerName());
      return;
    }
    Integer custId = customer.getId();
    Customer newCustomer = BeanConverUtil.conver(customerInfo, Customer.class);
    if (customer.getDelFlag() == -1) {
      customer.setCreatedTime(new Date());
    }

    newCustomer.setId(custId);
    newCustomer.setUpdatedBy(UserLocalUtils.getCreatedId());
    newCustomer.setUpdatedTime(new Date());

    log.info("同步客户,customerEdit:{}", newCustomer);
    //过滤员工跟进人
    List<CustomerFollowerStaffRequest> followerStaff = setAddWayAndPhone(customerStandardRequest,
        newCustomer);

    //更新需用userid和商户号
    newCustomer.setCustomerName(EmojiUtils.parseToHtmlHexadecimal((customer.getCustomerName())));
    newCustomer.setUpdatedBy(merchantId);
    List<StaffFollowResponse> staffFollow = customerMapper.getStaffFollowById(custId);

    customerMapper.updateByPrimaryKeySelective(newCustomer);
    log.info("客户编辑,data:{}", newCustomer);
    log.info("客户跟进人编辑{}", followerStaff);

    //解析备注
    readRemark(followerStaff, customerInfo);
    if (StringUtils.isEmpty(newCustomer.getCustomerPhone())) {
      newCustomer.setRemarkPhone(customerInfo.getCustomerPhone());
    }
    newCustomer.setUserid(customerInfo.getUserid());
    log.info("编辑客户回填手机号: {}", JSONArray.toJSONString(newCustomer));
    //填充手机号
    customerMapper.updatePhoneByUserId(Arrays.asList(newCustomer));
    //修改所有跟进人对这个客户的备注
    entmicroCustomerFollowMapper.updateBatchInfo(Arrays.asList(newCustomer));

    List<CustomerFollowerStaffRequest> oldfollow = staffFollow.stream().map(index -> {
      CustomerFollowerStaffRequest customerFollowerStaffRequest = new CustomerFollowerStaffRequest();
      customerFollowerStaffRequest.setUserId(index.getUserid());
      customerFollowerStaffRequest.setId(index.getId());
      return customerFollowerStaffRequest;
    }).collect(Collectors.toList());
    log.info("客户跟进人编辑库{}", oldfollow);
    List<CustomerFollowerStaffRequest> addlist = followerStaff.stream()
        .filter(index -> !oldfollow.contains(index)).collect(Collectors.toList());
    List<CustomerFollowerStaffRequest> updatelist = followerStaff.stream()
        .filter(index -> oldfollow.contains(index)).collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(addlist)) {
      log.info("新增跟进人list{}", addlist);
      addlist.stream().forEach(staff -> staff.setMerchantId(merchantId));
      List<EntmicroCustomerFollow> insertFollows = buildFollowParamAdd(addlist, custId);
      followService.insert(insertFollows);
      syncCustomerData(insertFollows, "1", customerInfo, newCustomer);
    }
    if (!CollectionUtils.isEmpty(updatelist)) {
      log.info("更新跟进人list{}", updatelist);
      updatelist.stream().forEach(staff -> staff.setMerchantId(merchantId));
      List<EntmicroCustomerFollow> updateFollows = buildFollowParamAdd(updatelist, custId);
      followService.updatelist(updateFollows);
      syncCustomerData(updateFollows, "1", customerInfo, newCustomer);
    }

    //维格表异步更新
    List<String> userIds = followerStaff.stream().map(CustomerFollowerStaffRequest::getUserId)
        .collect(Collectors.toList());
    List<EntmicroStaffResponse> staffsExist = entmicroStaffService.getListByUserIds(userIds,
        merchantId);
    log.info("customerEdit userIds:{},followerEntmicroStaff:{}", userIds, staffsExist);
    Map<String, String> staffIdNameMap = staffsExist.stream().collect(
        Collectors.toMap(EntmicroStaffResponse::getUserId, EntmicroStaffResponse::getStaffName,
            (o1, o2) -> o1));
    log.info("vika.authorize.merchantId:{}", environment.getProperty("vika.authorize.merchantId"));
    asyncUpdate2Vika(merchantId, customerInfo, followerStaff, staffIdNameMap);
  }

  /**
   * 构建读取备注和描述的数据
   *
   * @return
   */
  public CustomerInfoRequest readRemark(List<CustomerFollowerStaffRequest> followerStaff,
      CustomerInfoRequest customerInfo) {
    //获取客户最晚添加的跟进人备注进行识别
    Optional<CustomerFollowerStaffRequest> max = followerStaff.stream()
        .max(Comparator.comparing(CustomerFollowerStaffRequest::getCreatedTime,
            Comparator.nullsLast(Date::compareTo)));
    if (max.isPresent()) {
      CustomerFollowerStaffRequest staffFollowResponse = max.get();
      //解析备注(业务优先以备注内容为主)
      CustomerKafkaDTO customerKafkaDTO = RemarkUtils.distinguishMethod(
          staffFollowResponse.getRemark());
      //解析描述
      CustomerKafkaDTO customerKafkaDTO1 = RemarkUtils.distinguishMethod(
          staffFollowResponse.getDescription());

      //手机号(优先级:备注手机号 > 备注解析 > 描述解析)
      if (StringUtils.isEmpty(customerInfo.getCustomerPhone())) {
        if (!StringUtils.isEmpty(customerKafkaDTO.getCustomerPhone())) {
          customerInfo.setCustomerPhone(customerKafkaDTO.getCustomerPhone());
        } else if (!StringUtils.isEmpty(customerKafkaDTO1.getCustomerPhone())) {
          customerInfo.setCustomerPhone(customerKafkaDTO1.getCustomerPhone());
        }
      }
      //车牌号(优先级:备注解析 > 描述解析)
      if (!StringUtils.isEmpty(customerKafkaDTO.getCarNumber())) {
        customerInfo.setCarNumber(customerKafkaDTO.getCarNumber());
      } else if (!StringUtils.isEmpty(customerKafkaDTO1.getCarNumber())) {
        customerInfo.setCarNumber(customerKafkaDTO1.getCarNumber());
      }
      //车架号(优先级:备注解析 > 描述解析)
      if (!StringUtils.isEmpty(customerKafkaDTO.getCarVin())) {
        customerInfo.setCarVin(customerKafkaDTO.getCarVin());
      } else if (!StringUtils.isEmpty(customerKafkaDTO1.getCarVin())) {
        customerInfo.setCarVin(customerKafkaDTO1.getCarVin());
      }
    }
    return customerInfo;
  }


  private List<CustomerFollowerStaffRequest> setAddWayAndPhone(CustomerStandardRequest
      customerStandardRequest, Customer newCustomer) {

    List<CustomerFollowerStaffRequest> followerStaff = customerStandardRequest.getFollowerStaff();
    log.info("跟进人来源{}", followerStaff);
    //数据过滤 取最早跟进时间
    if (!CollectionUtils.isEmpty(followerStaff)) {
      //如果有跟进人,状态为正常
      newCustomer.setDelFlag(Constants.NORMAL_FLAG);
      Optional<CustomerFollowerStaffRequest> earlyStaff = followerStaff.stream()
          .min(Comparator.comparing(CustomerFollowerStaffRequest::getCreatedTime,
              Comparator.nullsLast(Date::compareTo)));
      if (earlyStaff.isPresent()) {
        log.info("最早添加的员工{}", earlyStaff);
        CustomerFollowerStaffRequest customerFollowerStaffRequest = earlyStaff.get();
        newCustomer.setAddWay(customerFollowerStaffRequest.getAddWay());
        newCustomer.setCreatedTime(customerFollowerStaffRequest.getCreatedTime());
      }
      List<String> collect = followerStaff.stream().filter(
              index -> index.getRemarkMobiles() != null)
          .map(CustomerFollowerStaffRequest::getRemarkMobiles).collect(Collectors.toList());
      if (!CollectionUtils.isEmpty(collect)) {
        log.info("获取备注号码{}", collect);
        newCustomer.setCustomerPhone(collect.get(0));
      }
      String state = customerStandardRequest.getState();
      if (!StringUtils.isEmpty(state)) {
        for (CustomerFollowerStaffRequest request : followerStaff) {
          if (!StringUtils.isEmpty(request.getState())) {
            break;
          }
          request.setState(state);
        }
      }

      //驻店使用企微添加客户时,推送企微消息提醒
      noticeStaff(followerStaff, customerStandardRequest.getMerchantId(),
          customerStandardRequest.getCustomerInfo());
    }
    return followerStaff;
  }

  /**
   * 根据跟进类型通知加好友的员工
   *
   * @param followerStaff
   */
  public void noticeStaff(List<CustomerFollowerStaffRequest> followerStaff, Integer merchantId,
      CustomerInfoRequest customerInfo) {
    long start = System.currentTimeMillis();
    String noticeMerchantId = environment.getProperty("enmicro.notice.merchantId");
    List<String> merchantIdList = Arrays.asList(noticeMerchantId.split(","));
    log.info("加好友发送企微消息,noticeMerchantId:{},merchantId:{},customerName:{}",
        noticeMerchantId, merchantId, customerInfo.getCustomerName());

    if (!merchantIdList.contains(String.valueOf(merchantId))) {
      return;
    }
    //过滤最晚时间添加的员工
    Optional<CustomerFollowerStaffRequest> lastStaff = followerStaff.stream()
        .max(Comparator.comparing(CustomerFollowerStaffRequest::getCreatedTime,
            Comparator.nullsLast(Date::compareTo)));
    String followTypeName = environment.getProperty("enmicro.notice.followTypeName");

    List<String> followTypeNameList = Arrays.asList(followTypeName.split(","));

    if (!lastStaff.isPresent()) {
      return;
    }
    log.info("最晚添加的员工{}", lastStaff);
    CustomerFollowerStaffRequest customerFollowerStaffRequest = lastStaff.get();
    //查询员工跟进类型
    EntmicroFollowerStaffRequest entmicroFollowerStaffRequest = new EntmicroFollowerStaffRequest();
    entmicroFollowerStaffRequest.setMerchantId(customerFollowerStaffRequest.getMerchantId());
    entmicroFollowerStaffRequest.setUserId(customerFollowerStaffRequest.getUserId());
    List<EntmicroFollowerStaffResponse> followerStaffResponseList = entmicroStaffService.listEntmicroFollowerStaff(
        entmicroFollowerStaffRequest);
    if (CollectionUtils.isEmpty(followerStaffResponseList)) {
      return;
    }
    EntmicroFollowerStaffResponse staffResponse = followerStaffResponseList.get(0);
    if (com.glsx.plat.common.utils.StringUtils.isBlank(staffResponse.getFollowerTypeName())
        || !followTypeNameList.contains(staffResponse.getFollowerTypeName())) {
      return;
    }

    //判断该手机号在系统中是否有待跟进订单记录,若存在,则推送资料完善提醒通知;若不存在,则推送客户建档提醒
    sendNoticeStaffMessage(customerInfo, customerFollowerStaffRequest);
    log.info("加好友推送员工消息完毕,耗时:{}", System.currentTimeMillis() - start);
  }

  public void sendNoticeStaffMessage(CustomerInfoRequest customerInfo,
      CustomerFollowerStaffRequest customerFollowerStaffRequest) {
    RpcResponse<GoodsOrderDTO> rpcRes = goodsOrderRemote.getCustomerLastWaitInputOrder(
        customerInfo.getCustomerPhone());
    log.info("客户:{} 待跟进订单信息rpc返回:{}", customerInfo.getCustomerPhone(), rpcRes);
    GoodsOrderDTO todoOrder = rpcRes.getResult();

    String customerName = Optional.ofNullable(customerInfo.getCustomerName())
        .map(EmojiUtils::parseToUnicode)
        .orElse("");

    WechatMessageModel wechatMessage = Objects.isNull(todoOrder) ?
        buildStartWechatMessageModel(customerFollowerStaffRequest, customerName)
        : buildReplenishWechatMessageModel(customerFollowerStaffRequest,
            getOrderCustomerName(customerInfo, todoOrder), todoOrder);

    commonService.sendCardWechatMessage(wechatMessage);
  }

  private static String getOrderCustomerName(CustomerInfoRequest customerInfo,
      GoodsOrderDTO todoOrder) {
    return Optional.ofNullable(todoOrder.getCustomer())
        .map(GoodsOrderCustomer::getCustomerName)
        .map(EmojiUtils::parseToUnicode)
        .orElse(customerInfo.getCustomerName());
  }

  /**
   * 客户建档提醒推送
   *
   * @param customerFollowerStaffRequest
   * @param customerName
   * @return
   */
  private WechatMessageModel buildStartWechatMessageModel(
      CustomerFollowerStaffRequest customerFollowerStaffRequest, String customerName) {
    WechatMessageModel wechatMessageModel = new WechatMessageModel();
    wechatMessageModel.setMerchantId(customerFollowerStaffRequest.getMerchantId());
    wechatMessageModel.setTitle(CustomerConstants.CUSTOMER_START_MESSAGE_TITLE);
    wechatMessageModel.setUserId(customerFollowerStaffRequest.getUserId());
    wechatMessageModel.setContent(getMessageContent(customerFollowerStaffRequest, customerName));
    String url = environment.getProperty("wechat.miniprogram.url.link.noticeUrl")
        + "?customerName=" + customerName
        + "&page=createArchives";
    wechatMessageModel.setUrl(url);
    return wechatMessageModel;
  }

  private static String getMessageContent(CustomerFollowerStaffRequest customerFollowerStaffRequest,
      String customerName) {

    return String.format(NOTICE_CONTENT, customerName,
        DateUtils.formatNormal(customerFollowerStaffRequest.getCreatedTime()));
  }


  /**
   * 客户完善资料提醒推送构建
   */
  private WechatMessageModel buildReplenishWechatMessageModel(
      CustomerFollowerStaffRequest customerFollowerStaffRequest, String customerName,
      GoodsOrderDTO todoOrder) {
    WechatMessageModel wechatMessageModel = new WechatMessageModel();
    wechatMessageModel.setMerchantId(customerFollowerStaffRequest.getMerchantId());
    wechatMessageModel.setTitle(CustomerConstants.CUSTOMER_COMPLETE_MESSAGE_TITLE);
    wechatMessageModel.setUserId(customerFollowerStaffRequest.getUserId());
    wechatMessageModel.setContent(getMessageContent(customerFollowerStaffRequest, customerName));
    String url = environment.getProperty("wechat.miniprogram.url.link.noticeUrl")
        + "?orderCode=" + todoOrder.getOrderCode()
        + "&customerName=" + customerName
        + "&merchantId=" + todoOrder.getSellerMerchantId()
        + "&page=createOrder";
    wechatMessageModel.setUrl(url);
    return wechatMessageModel;
  }

  /**
   * 推送营销产品说明书
   *
   * @param customerFollowerStaffRequest
   * @param fileConfig
   * @return
   */
  private WechatMessageModel buildDracFile(
      CustomerFollowerStaffRequest customerFollowerStaffRequest, DracFileConfig fileConfig) {
    WechatMessageModel messageModel = new WechatMessageModel();
    messageModel.setMerchantId(customerFollowerStaffRequest.getMerchantId());
    messageModel.setTitle("营销产品说明书");
    messageModel.setUserId(customerFollowerStaffRequest.getUserId());
    messageModel.setContent(
        "您已新增一位客户,参考公司的营销产品说明书,开启跟客户沟通的第一步吧~\n\n点击了解>>");
    messageModel.setUrl(fileConfig.getFileUrl());
    return messageModel;
  }


  /**
   * 跟进人删除客户
   *
   * @param userId         员工userid
   * @param externalUserId 客户userid
   */
  public void customerDelete(String userId, String externalUserId, boolean statics,
      Integer merchantId) {
    boolean delete = followService.delete(userId, externalUserId, merchantId);
    log.info("跟进人删除客户,userId:{},externalUserId:{},是否同步{}", userId, externalUserId,
        delete);
    if (delete) {
      syncCustomerDataDelete(externalUserId);
    }
  }

  private void syncCustomerDataDelete(String externalUserId) {
    List<EntmicroCustomerFollow> entmicroCustomerFollowList = followService.findAllFollowByExternalUserId(
        externalUserId);

    if (CollectionUtils.isEmpty(entmicroCustomerFollowList)) {
      return;
    }

    syncCustomerData(entmicroCustomerFollowList, "0", null, null);
  }

  /**
   * 客户删除跟进人
   *
   * @param userId         员工userid
   * @param externalUserId 客户userid
   * @param remind         是否发送提醒
   */
  public void customerFollowDelete(String userId, String externalUserId, boolean statics,
      Integer merchantId, boolean remind) {
    log.info("客户删除跟进人,userId:{},externalUserId:{}", userId, externalUserId);
    boolean delete = followService.delete(userId, externalUserId, merchantId);
    //同步数据中台
    if (delete) {
      syncCustomerDataDelete(externalUserId);
    }
    if (remind) {
      reminderWhenDeleteCustomer(merchantId, userId, externalUserId);
    }
  }

  /**
   * 客户删除好友提醒
   *
   * @param merchantId     商户号
   * @param userId         员工userId
   * @param externalUserId 客户userid
   * @return
   */
  public boolean reminderWhenDeleteCustomer(Integer merchantId, String userId,
      String externalUserId) {
    log.info("客户删除提醒触发 merchantId:{},userId:{},externalUserId:{}", merchantId, userId,
        externalUserId);
    String title = "客户删除好友提醒";
    Customer customer = customerMapper.getCustomerByUserId(externalUserId);
    log.info("客户删除提醒客户信息:{}", customer);
    if (customer == null) {
      return false;
    }
    String nickName = "";
    String customerName = customer.getCustomerName();
    if (!StringUtils.isEmpty(customerName)) {
      nickName = EmojiUtils.parseToUnicode(customerName);
      if (customer.getType() == Constants.USER_TYPE_WECHAT) {
        nickName = nickName + "@微信";
      } else if (customer.getType() == Constants.USER_TYPE_ENTERPRISE) {
        nickName =
            nickName + "@" + (customer.getCorpName() == null ? "企微" : customer.getCorpName());
      }
    }
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateTime = format.format(new Date());
    String content =
        "\n客户名称:" + nickName + "\n删除时间:" + dateTime + "\n\n客户已将你删除好友,快去跟进吧!";
    Integer merchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
    String entmicroId = entmicroAuthorizeMapper.findEntmicroId(merchantNo);
    String url = String.format(customerDeleteUrl, entmicroId, externalUserId);
    return pushReminder(merchantId, title, content, url, userId);
  }

  /**
   * 企微员工推送提醒
   *
   * @param merchantId 商户号
   * @param title      标题
   * @param content    描述
   * @param url        跳转链接
   * @param userId     发送的员工id
   * @return
   */
  public boolean pushReminder(Integer merchantId, String title, String content, String url,
      String userId) {
    WechatMessageModel wechatMessage = new WechatMessageModel();
    wechatMessage.setUserId(userId);
    wechatMessage.setMerchantId(merchantId);
    wechatMessage.setType("");
    wechatMessage.setTitle(title);
    wechatMessage.setContent(content);
    wechatMessage.setUrl(url);
    wechatMessage.setBtnTxt("立即前往");
    log.info("staff week report component request:{}", JSONObject.toJSONString(wechatMessage));
    return commonService.sendCardWechatMessage(wechatMessage);
  }

  /**
   * 组装需要同步的跟进人所属的多个门店下的数据
   *
   * @param list
   * @param type
   */
  public void syncCustomerData(List<EntmicroCustomerFollow> list, String type,
      CustomerInfoRequest customerInfo, Customer newCustomer) {
    List<EntmicroCustomerFollow> newArraylist = new ArrayList<>();
    //merChangeStatus  门店(商户)变更状态 0-正常 1-门店已变更
    log.info("===type:{},EntmicroCustomerFollow:{}", type, list);
    if (CollectionUtils.isEmpty(list)) {
      return;
    }
    //type  0 新增 1 更改 2 删除
    //获取该员工的多个门店号
    list.forEach(index -> {
      Integer staffId = index.getStaffId();
      List<Integer> staffIds = Arrays.asList(staffId);
      if (!CollectionUtils.isEmpty(staffIds)) {
        List<String> merchantIds = entmicroStaffService.findMerchantIdsByStaffIds(staffIds);
        for (String merchantId : merchantIds) {
          EntmicroCustomerFollow entmicroCustomerFo = new EntmicroCustomerFollow();
          BeanUtils.copyProperties(index, entmicroCustomerFo);
          entmicroCustomerFo.setMerchantId(Integer.parseInt(merchantId));
          newArraylist.add(entmicroCustomerFo);
        }
      }
    });

    //客户id
    Integer customerId = list.get(0).getCustomerId();
    log.info("客户多部门同步信息: {}", newArraylist);
    //同步客户到该员工所属的每个门店
    newArraylist.forEach(index -> {
      syncCustomerData(customerId, type, Integer.valueOf(index.getMerchantId()), index.getTagList(),
          index.getStaffId());

      //异步推送解析的数据到kafka oneId 车牌号 车架号 手机号
      if (null != customerInfo) {
        //若入库手机号为空 则使用解析的手机号
        if (StringUtils.isEmpty(newCustomer.getCustomerPhone())) {
          customerInfo.setCustomerPhone(newCustomer.getRemarkPhone());
        }
        producerComponent.sendKafkaMessageCustomerInfo(customerInfo,
            Integer.valueOf(index.getMerchantId()), newCustomer.getAddWay());
      }
    });
  }

  public void changeOneId(String oldOneId, String newOneId, Integer merchantId) {
    try {

      List<Integer> customerByOneId = customerMapper.findCustomerByOneId(oldOneId, merchantId);
      if (!CollectionUtils.isEmpty(customerByOneId)) {
        customerMapper.changeOneId(newOneId, customerByOneId);
      }
    } catch (Exception e) {
      log.info("OneId变更异常,:oldOneId:{},newOneId:{},", oldOneId, newOneId);
    }
  }

  /**
   * 获取企微的客户详情
   *
   * @param merchantId      商户号
   * @param external_userid 外部联系人id
   * @return
   */
  public CustomerStandardRequest getEntmicroCustomer(Integer merchantId, String external_userid) {
    GetWorkWechatExternalContactRequestDTO getWorkWechatExternalContactRequestDTO = new GetWorkWechatExternalContactRequestDTO();
    getWorkWechatExternalContactRequestDTO.setMerchantId(merchantId);
    getWorkWechatExternalContactRequestDTO.setExternalUserId(external_userid);
    log.info("获取企微客户详情入参:{}",
        JSONArray.toJSONString(getWorkWechatExternalContactRequestDTO));
    RpcResponse<WorkWechatExternalContactResponseDTO> externalContact = contactRemote.getExternalContact(
        getWorkWechatExternalContactRequestDTO);
    log.info("获取企微客户详情:{}", JSONArray.toJSONString(externalContact));
    if (!externalContact.isSuccess()) {
      throw new RpcServiceException(externalContact.getError(), externalContact.getMessage());
    }
    WorkWechatExternalContactResponseDTO result = externalContact.getResult();
    if (result.getErrCode() != null && result.getErrCode() != 0) {
      throw new RpcServiceException(String.valueOf(result.getErrCode()), result.getErrMsg());
    }
    return buildCustomerParam(result, merchantId);
  }


  /**
   * 构建客户参数
   *
   * @param workWechatExternalContactResponseDTO 企微客户
   * @param merchantId
   * @return
   */
  public CustomerStandardRequest buildCustomerParam(WorkWechatExternalContactResponseDTO
      workWechatExternalContactResponseDTO, Integer merchantId) {
    WorkWechatExternalContactDTO externalContact = workWechatExternalContactResponseDTO.getExternalContact();
    //客户数据
    CustomerInfoRequest customerInfoRequest = new CustomerInfoRequest();
    customerInfoRequest.setCustomerName(
        EmojiUtils.parseToHtmlHexadecimal(externalContact.getName()));
    customerInfoRequest.setCustomerOriginalName(externalContact.getName());
    customerInfoRequest.setAvatar(externalContact.getAvatar());
    customerInfoRequest.setType(externalContact.getType());
    customerInfoRequest.setCorpFullName(externalContact.getCorpFullName());
    customerInfoRequest.setPosition(externalContact.getPosition());
    customerInfoRequest.setCorpName(externalContact.getCorpName());
    customerInfoRequest.setCustomerSex(externalContact.getGender());
    customerInfoRequest.setUserid(externalContact.getExternalUserId());
    customerInfoRequest.setUnionId(externalContact.getUnionid());
    //提取企微跟进员工数据
    List<WorkWechatExternalContactFollowUserDTO> followUser = workWechatExternalContactResponseDTO.getFollowUser();
    List<CustomerFollowerStaffRequest> collect = followUser.stream().map(index -> {
      CustomerFollowerStaffRequest customerFollowerStaffRequest = new CustomerFollowerStaffRequest();
      BeanUtils.copyProperties(index, customerFollowerStaffRequest);
      if (!CollectionUtils.isEmpty(index.getRemarkMobiles())) {
        //备注手机号
        customerFollowerStaffRequest.setRemarkMobiles(index.getRemarkMobiles().get(0));
        customerInfoRequest.setCustomerPhone(index.getRemarkMobiles().get(0));
      }
      customerFollowerStaffRequest.setCreatedTime(new Date(index.getCreateTime() * 1000));
      customerFollowerStaffRequest.setMerchantId(merchantId);
      customerFollowerStaffRequest.setState(index.getState());
      List<WorkWechatExternalContactFollowUserTagDTO> tagList = index.getTagList();
      log.info("buildCustomerParam===tagList:{}", tagList);
      List<FollowTagRequest> tagListReq = BeanConverUtil.converList(tagList,
          FollowTagRequest.class);
      log.info("buildCustomerParam===tagListReq:{}", tagListReq);
      log.info("buildCustomerParam==customerFollowerStaffRequest: {}",
          customerFollowerStaffRequest);
      customerFollowerStaffRequest.setTagList(tagListReq);
      return customerFollowerStaffRequest;
    }).collect(Collectors.toList());
    //取出最早添加时间
    Optional<WorkWechatExternalContactFollowUserDTO> min = followUser.stream()
        .min(Comparator.comparing(WorkWechatExternalContactFollowUserDTO::getCreateTime));
    Date createTime = new Date(min.get().getCreateTime() * 1000);
    customerInfoRequest.setCreatedTime(createTime);
    //放入客户请求体数据和跟进员工数据
    CustomerStandardRequest customerStandardRequest = new CustomerStandardRequest(
        customerInfoRequest, collect);
    customerStandardRequest.setExternalUserId(externalContact.getExternalUserId());
    customerStandardRequest.setUserId(collect.get(0).getUserId());
    return customerStandardRequest;
  }

  /**
   * oneId变更
   *
   * @param request
   */
  public void changeOneID(ChangeOneIDRopRequest request) {
    log.info("oneId变更: {}", JSONArray.toJSONString(request));
    String oldOneId = request.getOldOneId();
    String newOneId = request.getNewOneId();
    //更新基础客户oneid
    changeOneId(oldOneId, newOneId, request.getMerchantId());

    CustomerMerge merge = BeanConverUtil.conver(request, CustomerMerge.class);
    //提取原业务数据合并到新的oneId
    CustomerInfoResponse customerByOneId = customerMergeMapper.getCustomerByOneId(oldOneId,
        merge.getMerchantId());
    log.info("oneId变更: {}, 旧数据: {}", JSONArray.toJSONString(request),
        JSONArray.toJSONString(customerByOneId));
    if (customerByOneId != null) {
      merge.setAddWay(customerByOneId.getAddWay());
      merge.setCreatedTime(customerByOneId.getAddTime());
      merge.setCustomerSex(customerByOneId.getCustomerSex());
      merge.setCustomerName(customerByOneId.getCustomerName());
      merge.setCustomerPhone(customerByOneId.getCustomerPhone());
      merge.setType(customerByOneId.getType());
      merge.setIsJoin(customerByOneId.getIsJoin());
      merge.setStatus(customerByOneId.getStatus());
      merge.setCreatedTime(customerByOneId.getAddTime());
      merge.setUnionId(customerByOneId.getUnionId());
      updateMergeCustomer(merge, newOneId, true);
    }

    //逻辑删除旧的oneid
    customerMergeMapper.logicDelete(oldOneId, merge.getMerchantId());
  }

  /**
   * 通过企微 外部联系人ID获取客户基础信息
   *
   * @param externalUserId
   * @return
   */
  public CustomerInfoResponse getCustomerInfoByExternalUserId(String externalUserId) {
    //客户信息
    Customer customerInfo = customerMapper.getCustomerByUserId(externalUserId);
    if (customerInfo == null) {
      return null;
    }
    //名称emoji转化
    customerInfo.setCustomerName(customerInfo.getCustomerName() != null ? EmojiUtils.parseToUnicode(
        customerInfo.getCustomerName()) : null);
    return CustomerInfoConvert.convertCustomerInfo(customerInfo);
  }

  /**
   * 通过条件查询员工下面的客户
   *
   * @param req
   * @return
   */
  public List<CustomerInfoResponse> findCustomerByCondition(QyWechatStaffDefaultRequest req) {
    EntmicroStaffResponse staffDetail = entmicroStaffService.findStaffDetail(
        new StaffRequestDTO(req.getUuid()));
    RpcAssert.assertNotNull(staffDetail, DefaultErrorEnum.DATA_NOT_EXIST, "员工不存在");
    List<CustomerInfoResponse> customerByStaffId = findCustomerByStaffId(staffDetail.getId(),
        req.getKeyWord(), req.getIsMiniPro());
    if (CollectionUtils.isEmpty(customerByStaffId)) {
      return null;
    } else {
      customerByStaffId.forEach(index -> {
        index.setCustomerName(EmojiUtils.parseToUnicode(index.getCustomerName()));
      });
    }

    if (!req.getTaggingInfo()) {
      return customerByStaffId;
    }

    Integer merchantId = UserLocalUtils.getMerchantId();
    List<Integer> datalist = UserLocalUtils.getDatalist();
    String merchantIds = com.glsx.plat.common.utils.StringUtils.join(datalist, ",");
    // 如果需要,补充标签数据
    List<String> oneIds = customerByStaffId.stream().map(CustomerInfoResponse::getOneId)
        .collect(Collectors.toList());
    LabelBatchRopRes labels = ropCommonServie.getLabels(oneIds, merchantId, staffDetail.getId());
    if (labels != null && !CollectionUtils.isEmpty(labels.getUserLabelUnitList())) {
      List<LabelBatchDetailRopRes> userLabelUnitList = labels.getUserLabelUnitList();
      Map<String, List<LabelBatchDetailRopRes>> collect = userLabelUnitList.stream()
          .collect(Collectors.groupingBy(item -> item.getOneId()));
      for (CustomerInfoResponse customer : customerByStaffId) {
        List<LabelBatchDetailRopRes> labelBatchDetailRopRes = collect.get(customer.getOneId());
        List<LabelListRopRes> labellists = new ArrayList<>();
        if (!CollectionUtils.isEmpty(labelBatchDetailRopRes)) {
          labelBatchDetailRopRes.forEach(index -> {
            List<CustomerLabelInfo> labelUnitList = index.getLabelUnitList();
            if (!CollectionUtils.isEmpty(labelUnitList)) {
              List<LabelListRopRes> labelListRopResList = new ArrayList<>();
              labelUnitList.forEach(ind -> {
                String labelGroupType = ind.getLabelGroupInfo() == null ? ""
                    : ind.getLabelGroupInfo().getLabelGroupType();
                List<LabelInfo> labelInfoList = ind.getLabelInfoList();
                if (!CollectionUtils.isEmpty(labelInfoList)) {
                  labelInfoList.forEach(in -> {
                    LabelListRopRes listRopRes = new LabelListRopRes();
                    listRopRes.setLabelGroupType(labelGroupType);
                    listRopRes.setLabelId(in.getLabelId());
                    listRopRes.setLabelValue(in.getLabelName());
                    labelListRopResList.add(listRopRes);
                  });
                }
              });
              labellists.addAll(labelListRopResList);
            }
          });
        }
        if (req.getIsMiniPro() != null && req.getIsMiniPro()) {
          labellists.sort((s1, s2) -> s1.getLabelId() > s2.getLabelId() ? -1 : 1);
        }
        customer.setLabels(labellists);
      }
    }

    // 过滤标签
    if (!CollectionUtils.isEmpty(req.getLabelIds())) {
      customerByStaffId = customerByStaffId.stream()
          .filter(p -> !CollectionUtils.isEmpty(p.getLabels()) &&
              p.getLabels().stream().anyMatch(l -> req.getLabelIds().contains(l.getLabelId())))
          .collect(Collectors.toList());
    }
    // 过滤系统标签
    if (req.getIsMiniPro() != null && req.getIsMiniPro()) {
      customerByStaffId.stream()
          .filter(p -> !CollectionUtils.isEmpty(p.getLabels()))
          .forEach(p -> p.setLabels(
              p.getLabels().stream().filter(l -> "系统标签".equals(l.getLabelGroupType()))
                  .collect(Collectors.toList())));
    }
    return customerByStaffId;
  }

  /**
   * 根据条件查询客户
   *
   * @param custSearchRequest
   * @return
   */
  public List<CustomerInfoResponse> findCustomerByCondition(
      CustListSearchRequest custSearchRequest) {
    return customerMapper.findCustomerBychantIds(custSearchRequest);
  }

  /**
   * 跟进员工id查询客户
   *
   * @param integer 员工id
   * @return
   */
  public List<CustomerInfoResponse> findCustomerByStaffId(Integer integer, String keywork) {
    return findCustomerByStaffId(integer, keywork, null);
  }

  public List<CustomerInfoResponse> findCustomerByStaffId(Integer integer, String keywork,
      Boolean isMiniPro) {
    if (!StringUtils.isEmpty(keywork)) {
      keywork = keywork.replaceAll("_", "/_").replaceAll("%", "/%");
    }
    return customerMapper.findCustomerByStaffId(integer, keywork, isMiniPro);
  }


  /**
   * 查询商户中未加企微的客户
   */
  public List<CustomerInfoResponse> findNoAddEntmocroCustByMerchant(Integer merchantId) {
    return customerMapper.findNoAddEntmocroCustByMerchant(merchantId);
  }

  /**
   * 查询商户中未完善信息的客户
   */
  public List<CustomerInfoResponse> findNoPhoneCustByMerchant(Integer merchantId) {
    return customerMapper.findNoPhoneCustByMerchant(merchantId);
  }

  public CustomerDetailResponse getCustomerDetailByUserId(String userId, List<Integer> datalist,
      Integer
          merchantId, Integer staffId) {
    CustomerInfoResponse customerInfoByExternalUserId = getCustomerInfoByExternalUserId(userId);
    if (customerInfoByExternalUserId == null) {
      // 模拟员工重新添加用户
      CustomerModel customerModel = new CustomerModel();
      Integer supMerchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
      if (supMerchantNo != null) {
        customerModel.setMerchantId(supMerchantNo);
        customerModel.setExternalUserId(userId);
        customerAdd(bussinessModelConvertService.converCustomer(customerModel), true, merchantId);
        customerInfoByExternalUserId = getCustomerInfoByExternalUserId(userId);
        log.info("根据userId查询客户详情为空,模拟添加后结果 customerInfo:{}",
            customerInfoByExternalUserId);
      }
      if (customerInfoByExternalUserId == null) {
        throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
      }
    }
    if (CollectionUtils.isEmpty(datalist)) {
      datalist = Arrays.asList(merchantId);
    }
    return getCustomerDetail(customerInfoByExternalUserId.getOneId(), datalist, merchantId,
        staffId);
  }

  /**
   * 客户编辑功能
   *
   * @param customerMagicRequest 入参
   */
  public void editCustomer(CustomerMagicRequest customerMagicRequest) {
    log.info("CustomerService_Invoke_editCustomer_request:{}",
        JSONArray.toJSONString(customerMagicRequest));
    String userId = customerMagicRequest.getUserId();
    Map<String, Customer> customersByUserId = customerMapper.getCustomersByUserId(
        Arrays.asList(userId));
    Customer customer = customersByUserId.get(userId);
    if (customer != null) {
      Customer customerUpdate = MagicImportCustomerConvert.buildCustomerByMagic(
          customerMagicRequest.getMerchantId(), customerMagicRequest, false, addwayMagic,
          customerMagicRequest.getAddWay());
      customerUpdate.setId(customer.getId());
      customerUpdate.setAddWay(null);
      customerMapper.updateByPrimaryKeySelective(customerUpdate);
    }
    // 给客户打备注
    commonService.remarkExternalContact(new CustomerReceiptModel(customerMagicRequest.getUserId(),
        customerMagicRequest.getCustomerPhone(), customerMagicRequest.getMerchantId(),
        Arrays.asList(customerMagicRequest.getStaffUserId())));
    Integer merchantNo = entmicroStaffService.findSupMerchantNo(
        customerMagicRequest.getMerchantId());
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    customerComsumerEdit(customerMagicRequest.getStaffUserId(), customerMagicRequest.getUserId(),
        merchantNo);
  }

  /**
   * 客户数据编辑
   *
   * @param request 入参
   */
  public Boolean editCustomerData(CustomerMagicRequest request) {
    log.info("客户数据编辑 request:{}", request);
    //1、这条正则可以校验 普通汽车的车牌、新能源客(货)车车牌
    String carNoReg =
        "/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}(([A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)"
            +
            "|([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/";
    Pattern pattern = Pattern.compile(carNoReg);
    Integer merchantId = request.getMerchantId();
    Integer addWay = request.getAddWay();
    String userId = request.getUserId();
    String staffUserId = request.getStaffUserId();
    String customerPhone = request.getCustomerPhone();
    String carNumber = request.getCarNumber();
    RpcAssert.assertNotNull(merchantId, DefaultErrorEnum.PARAMETER_NULL,
        "merchantId must not be null!");
    RpcAssert.assertNotNull(addWay, DefaultErrorEnum.PARAMETER_NULL, "addWay must not be null!");
    if (carNumber != null && pattern.matcher(carNumber).find()) {
      throw new RpcServiceException("车牌号格式错误");
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("merchant_id", merchantId);
    jsonObject.put("add_way", addWay);
    jsonObject.put("user_id", request.getUserId());
    jsonObject.put("customer_phone", customerPhone);
    jsonObject.put("customer_sex", request.getCustomerSex());
    jsonObject.put("car_number", carNumber);
    producerComponent.sendCustomerToKafka(jsonObject.toJSONString());
    return true;
  }

  /**
   * 备注客户手机号
   *
   * @param merchantId  商户号
   * @param userId      客户userId
   * @param staffUserId 员工userId
   */
  public void remarkCustomerPhone(Integer merchantId, String userId, String staffUserId) {
    try {
      Customer customer = customerMapper.getCustomerByUserId(userId);
      log.info("备注客户手机号 customer:{}", customer);
      if (customer != null && !StringUtils.isEmpty(customer.getCustomerPhone())) {
        commonService.remarkExternalContact(
            new CustomerReceiptModel(userId, customer.getCustomerPhone(),
                merchantId, Collections.singletonList(staffUserId)));
      }
    } catch (Exception e) {
      log.error("客户备注手机号异常", e);
      e.printStackTrace();
    }
  }

  /**
   * 修改手机号
   *
   * @param oneId
   * @param merchantId
   */
  public void updateCustPhone(String oneId, Integer merchantId, String remarkMobiles) {
    customerMergeMapper.updateCustPhone(oneId, merchantId, remarkMobiles);
  }

  /**
   * 回调修改客户信息
   *
   * @param userId     员工userId
   * @param cusUserId  客户userId
   * @param merchantId 商户号
   */
  public void customerComsumerEdit(String userId, String cusUserId, Integer merchantId) {
    CustomerModel customerMode = new CustomerModel();
    customerMode.setUserId(userId);
    customerMode.setExternalUserId(cusUserId);
    customerMode.setMerchantId(merchantId);
    customerEdit(bussinessModelConvertService.converCustomer(customerMode), true, merchantId);
  }

  /**
   * 分页获取渠道客户列表
   *
   * @param request
   * @return
   */
  public RpcPagination<CustomerListResponse> getCodeCustomerByPage(
      RpcPagination<CodeCustomerSearchRpcRequest> request) {
    int pageSize = request.getPageSize();
    int pageNum = request.getPageNum();
    PageHelper.startPage(pageNum, pageSize);
    CodeCustomerSearchRpcRequest requestCondition = request.getCondition();
    log.info("分页获取渠道客户列表{}", request.getCondition());
    Date endTimeIn = requestCondition.getEndTime();
    if (null != endTimeIn) {
      requestCondition.setEndTime(DateUtils.addDays(endTimeIn, 1));
    }
    log.info("分页获取渠道客户列表{}" + request.getCondition().getDatalist());
    log.info("分页获取渠道客户列表当前员工UserId{}", request.getCondition().getEntmicroId());
    Page<CustomerListResponse> customerByPage = customerMergeMapper.getCodeCustomerByPage(
        requestCondition);
    //数据组装
    setCustomerInfo(customerByPage, request.getCondition().getMerchantId(), null);
    log.info("分页获取渠道客户列表: {}", JSONObject.toJSONString(customerByPage));
    return RpcPagination.copyPage(customerByPage);
  }

  private List<CustomerListExportModel> customerListExportModel(
      List<CustomerListResponse> customerListResponses, Integer merchantId,
      Map<String, List<ScrmVehicleBasicInfoDTO>> vehicleMapByOneId) {
    return customerListExportModel(customerListResponses, merchantId, vehicleMapByOneId, null);
  }

  /**
   * 分群列表导出数据组装
   *
   * @param customerListResponses
   * @return
   */
  private List<CustomerListExportModel> customerListExportModel(
      List<CustomerListResponse> customerListResponses, Integer merchantId,
      Map<String, List<ScrmVehicleBasicInfoDTO>> vehicleMapByOneId, Boolean isExport) {
    if (CollectionUtils.isEmpty(customerListResponses)) {
      return new ArrayList<>();
    }
    List<String> oneIdList = customerListResponses.stream().map(CustomerListResponse::getOneId)
        .collect(Collectors.toList());

    // 获取线索时间和来源
    Map<String, PotentialBasicResponse> potentialBasicResponseMap = getClueByOneIds(oneIdList,
        merchantId);
    log.info("线索来源和时间:{},", potentialBasicResponseMap);
    List<CustomerListExportModel> customerListExportModels = customerListResponses.stream()
        .map(index -> {
          CustomerListExportModel customerListExportModel = new CustomerListExportModel();
          BeanUtils.copyProperties(index, customerListExportModel);
          if (index.getCustomerSex() != null) {
            customerListExportModel.setCustomerSex(sexConvert(index.getCustomerSex()));
          }
          if (index.getIsJoin() != null) {
            customerListExportModel.setIsJoinName(index.getIsJoin() == 1 ? "是" : "否");
          }
          if (index.getStatus() != null) {
            customerListExportModel.setStatusName(
                index.getStatus().byteValue() == 0 ? "正常" : "删除好友");
          }
          if (index.getAddTime() != null) {
            customerListExportModel.setAddTime(
                index.getAddTime() != null ? DateUtils.format(index.getAddTime()) : null);
          }
          if (index.getSubscribe() != null) {
            customerListExportModel.setSubscribeName(index.getSubscribe() == 1 ? "是" : "否");
          }
          if (!CollectionUtils.isEmpty(potentialBasicResponseMap)) {
            PotentialBasicResponse potentialBasicInfo = potentialBasicResponseMap.get(
                index.getOneId());
            if (!ObjectUtils.isEmpty(potentialBasicInfo)) {
              customerListExportModel.setClueSource(potentialBasicInfo.getClueSource());
              customerListExportModel.setClueTime(potentialBasicInfo.getClueTime() == null ? ""
                  : DateUtils.format(potentialBasicInfo.getClueTime()));
              customerListExportModel.setIntentSeries(potentialBasicInfo.getIntentSeries());
            }
          }
          List<ScrmVehicleBasicInfoDTO> vehicleList = vehicleMapByOneId.get(index.getOneId());
          if (!CollectionUtils.isEmpty(vehicleList)) {
            ScrmVehicleBasicInfoDTO vehicle = vehicleList.get(0);
            customerListExportModel.setBuyDate(
                vehicle.getBuyTime() != null ? DateUtils.format(vehicle.getBuyTime()) : null);
            customerListExportModel.setArrivalDate(
                vehicle.getLastEnteredTime() != null ? DateUtils.format(
                    vehicle.getLastEnteredTime()) : null);
            customerListExportModel.setComInsuranceStarttime(
                vehicle.getMainInsureStartTime() != null ? DateUtils.format(
                    vehicle.getMainInsureStartTime()) : null);
            customerListExportModel.setComInsuranceEndtime(
                vehicle.getMainInsureEndTime() != null ? DateUtils.format(
                    vehicle.getMainInsureEndTime()) : null);
            customerListExportModel.setMaintenanceDate(
                vehicle.getLastMaintainTime() != null ? DateUtils.format(
                    vehicle.getLastMaintainTime()) : null);
            customerListExportModel.setCarVin(vehicle.getStandNo());
            customerListExportModel.setCarNumber(vehicle.getPlateNumber());
            customerListExportModel.setAudi(vehicle.getVehicleSeries());
            Double vehiclePrice = vehicle.getVehiclePrice();
            customerListExportModel.setCarPrice(vehiclePrice == null ? null : vehiclePrice + "");
            customerListExportModel.setCarBrand(vehicle.getVehicleBrand());
            customerListExportModel.setCarType(vehicle.getVehicleType());
          }
          //设置企微名称
          customerListExportModel.setNickName(setNickNameInfo(index.getNickNameList()));
          customerListExportModel.setNickNameList(index.getNickNameList());
          //手机号脱敏(针对广汇导出)
          String customerPhone = index.getCustomerPhone();
          if (PROVIDER_GUANG_HUI.getValue().equals(serviceProviderConfig) && !StringUtils.isEmpty(
              customerPhone) && customerPhone.length() > 4
              && isExport != null && isExport) {
            customerListExportModel.setCustomerPhone(
                DataMaskingUtil.encryptionPhone(customerPhone));
          }
          return customerListExportModel;
        }).collect(Collectors.toList());
    return customerListExportModels;
  }

  // 获取线索来源和时间 K:oneId,V:PotentialBasicResponse
  private Map<String, PotentialBasicResponse> getClueByOneIds(List<String> oneIdList,
      Integer merchantId) {
    HashMap<String, PotentialBasicResponse> map = new HashMap<>(oneIdList.size());
    PotentialBasicInfoRequest potentialBasicInfoRequest = new PotentialBasicInfoRequest();
    potentialBasicInfoRequest.setOneIds(oneIdList);
    potentialBasicInfoRequest.setMerchantId(merchantId);
    RpcResponse<List<PotentialBasicResponse>> response = potentialBasicInfoRemote.getClueByOneIds(
        potentialBasicInfoRequest);
    if (response.isFailed()) {
      throw new RpcServiceException(response.getException().getErrId(), response.getMessage());
    }
    List<PotentialBasicResponse> result = response.getResult();
    for (PotentialBasicResponse basicResponse : result) {
      map.put(basicResponse.getOneId(), basicResponse);
    }
    return map;
  }

  /**
   * 分页获取客户分群列表
   *
   * @param request
   * @return
   */
  public RpcPagination<CustomerClusterListResponse> getCustomerClusterListByPage(
      RpcPagination<CustomerSearchRequest> request) {
    CustomerSearchRequest condition = request.getCondition();
    condition.setMerchantIds(condition.getDatalist());
    if (condition.getFollowStaff() != null) {
      condition.setFollowStaff(EmojiUtils.parseToHtmlHexadecimal(condition.getFollowStaff()));
    }
    request.setCondition(condition);
    // 验证是否携带查询条件,判断数据分页是否由数据平台处理
    Page<Object> page = null;
    if (!verifyCondition(request.getCondition())) {
      page = new Page<>(request.getPageNum(), request.getPageSize());
      request.setPageNum(1);
      request.setPageSize(1000000);
    }
    //客户分群查询客户oneIds
    Page<String> oneIds = ropCommonServie.getOneIdsByGroupId(request);

    log.info("客户分群oneId列表:{}", oneIds);
    if (CollectionUtils.isEmpty(oneIds)) {
      return RpcPagination.copyPage(oneIds);
    }
    Page<CustomerClusterListResponse> customerListByOneId = getCustomerListByOneId(condition,
        oneIds, page);
    return RpcPagination.copyPage(customerListByOneId);
  }

  /**
   * 自定义人群管理客户列表
   *
   * @param request
   * @return
   */
  public RpcPagination<CustomerClusterListResponse> getCrowdManagementCustomerList(
      RpcPagination<CustomerSearchRequest> request) {
    CustomerSearchRequest condition = request.getCondition();
    condition.setMerchantIds(condition.getDatalist());
    if (condition.getFollowStaff() != null) {
      condition.setFollowStaff(EmojiUtils.parseToHtmlHexadecimal(condition.getFollowStaff()));
    }
    request.setCondition(condition);
    // 验证是否携带查询条件,判断数据分页是否由数据平台处理
    Page<Object> page = null;
    if (!verifyCondition(request.getCondition())) {
      page = new Page<>(request.getPageNum(), request.getPageSize());
      request.setPageNum(1);
      request.setPageSize(1000000);
    }
    //客户分群查询客户oneIds
    Page<String> oneIds = ropCommonServie.queryCrowdCustomersById(request);

    log.info("客户分群oneId列表:{}", oneIds);
    if (CollectionUtils.isEmpty(oneIds)) {
      return RpcPagination.copyPage(oneIds);
    }
    Page<CustomerClusterListResponse> customerListByOneId = getCustomerListByOneId(condition,
        oneIds, page);
    return RpcPagination.copyPage(customerListByOneId);
  }

  /**
   * 根据oneId查询客户明细
   *
   * @param condition 查询条件
   * @param oneIds    oneId
   * @param page      是否使用pageHelper
   * @return
   */
  public Page<CustomerClusterListResponse> getCustomerListByOneId(CustomerSearchRequest condition,
      Page<String> oneIds, Page page) {
    if (condition == null) {
      condition = new CustomerSearchRequest();
      condition.setEndTime(new Date());
    }
    log.info("获取客户分群列表分页条件{}", condition);
    Date endTimeIn = condition.getEndTime();
    if (null != endTimeIn) {
      condition.setEndTime(DateUtils.addDays(endTimeIn, 1));
    }
    log.info("获取客户分群列表分页数据,dataList:{}", condition.getDatalist());
    log.info("当前员工UserId{}", condition.getEntmicroId());

    //查询客户列表
    log.info("datahub客户分群oneId列表:{}", oneIds);
    condition.setOneIds(oneIds);

    //车辆条件
    Map<String, List<ScrmVehicleBasicInfoDTO>> vehicleMapByOneId = getVehicleMapByOneId(condition);
    if (vehicleMapByOneId == null) {
      return new Page<>();
    }

    if (page != null) {
      PageHelper.startPage(page.getPageNum(), page.getPageSize());
    }
    Page<CustomerListResponse> customerAll = customerList(condition);
    log.info("scrm客户列表:{}", customerAll);

    //过滤oneId匹配的列表数据
    List<String> oneIdList = condition.getOneIds();
    List<CustomerListResponse> customerListByOneIds = customerAll.stream()
        .filter(cust -> oneIdList.contains(cust.getOneId())).collect(Collectors.toList());

    //数据组装
    List<CustomerListExportModel> customerList = customerListExportModel(customerListByOneIds,
        condition.getMerchantId(), vehicleMapByOneId);
    Map<String, List<CustomerListResponse>> customerListMap = customerListByOneIds.stream()
        .collect(Collectors.groupingBy(index ->
            Optional.ofNullable(index.getOneId()).orElse("")));
    Page<CustomerClusterListResponse> customerClusterList;
    if (page != null) {
      customerClusterList = BeanConverUtil.conver(customerAll, Page.class);
    } else {
      customerClusterList = BeanConverUtil.conver(oneIds, Page.class);
    }
    customerList.forEach(index -> {
      CustomerClusterListResponse response = BeanConverUtil.conver(index,
          CustomerClusterListResponse.class);
      response.setInsStartDate(index.getComInsuranceStarttime());
      response.setInsEndDate(index.getComInsuranceEndtime());
      List<CustomerListResponse> customerListByOneId = customerListMap.get(index.getOneId());
      if (!CollectionUtils.isEmpty(customerListByOneId)) {
        response.setCustomerNickName(customerListByOneId.get(0).getCustomerNickName());
        response.setType(customerListByOneId.get(0).getType());
      }
      response.setCarVin(response.getCarVin());
      //设置企微名称
      response.setNickNameList(index.getNickNameList());
      customerClusterList.add(response);
    });
    log.info("客户分群列表:{}", customerClusterList);
    return customerClusterList;
  }

  /**
   * 客户分群列表导出
   *
   * @param request
   * @return
   */
  public String customerClusterListExport(CustomerSearchRequest request) {
    log.info("客户分群列表导出参数:{}", request);
    RpcPagination<CustomerSearchRequest> rpcPagination = new RpcPagination<>();
    rpcPagination.setPageNum(1);
    rpcPagination.setPageSize(1000000);
    request.setMerchantIds(request.getDatalist());
    rpcPagination.setCondition(request);
    //客户分群查询客户oneIds
    Page<String> oneIds;
    if (request.getCustomCrowd() != null && request.getCustomCrowd()) {
      oneIds = ropCommonServie.queryCrowdCustomersById(rpcPagination);
    } else {
      oneIds = ropCommonServie.getOneIdsByGroupId(rpcPagination);
    }

    log.info("datahub客户分群oneId列表:{}", oneIds);
    List<CustomerListExportModel> customerList = new ArrayList<>();
    if (!CollectionUtils.isEmpty(oneIds)) {
      //获取客户列表信息
      request.setOneIds(oneIds);
      //车辆条件
      Map<String, List<ScrmVehicleBasicInfoDTO>> vehicleMapByOneId = getVehicleMapByOneId(request);
      if (vehicleMapByOneId == null) {
        return ExcelExportUtils.excelExport("客户列表" + System.currentTimeMillis(), customerList,
            CustomerListExportModel.class, serviceProviderConfig);
      }
      List<CustomerListResponse> customerAll = customerList(request);
      log.info("scrm客户列表:{}", customerAll);
      //过滤oneId匹配信息
      List<CustomerListResponse> customerListByOneIds = customerAll.stream()
          .filter(cust -> oneIds.contains(cust.getOneId())).collect(Collectors.toList());
      //导出数据组装
      customerList = customerListExportModel(customerListByOneIds, request.getMerchantId(),
          vehicleMapByOneId, true);
    }

    String fileUrl = ExcelExportUtils.excelExport("客户列表" + System.currentTimeMillis(),
        customerList, CustomerListExportModel.class, serviceProviderConfig);
    log.info("客户分群列表导出ExcelURL:{}", fileUrl);
    return fileUrl;
  }

  /**
   * 标签客户导出
   *
   * @param customerSearchRequest 入参
   * @return
   */
  public String customerPageByTagExport(CustomerSearchRequest customerSearchRequest) {
    RpcPagination<CustomerSearchRequest> customerSearchRequestRpcPagination = new RpcPagination<>();
    customerSearchRequestRpcPagination.setPageNum(1);
    customerSearchRequestRpcPagination.setPageSize(1000000);
    customerSearchRequestRpcPagination.setCondition(customerSearchRequest);
    Page<String> oneIdsByTag = ropCommonServie.getOneIdsByTag(customerSearchRequestRpcPagination);
    List<String> result = oneIdsByTag.getResult();
    customerSearchRequest.setOneIds(result);
    if (CollectionUtils.isEmpty(result)) {
      return ExcelExportUtils.excelExport("客户列表" + System.currentTimeMillis(), null,
          CustomerListExportModel.class, serviceProviderConfig);
    }
    return customerListExport(customerSearchRequest);
  }

  /**
   * 根据标签查询客户列表
   *
   * @param pagination 入参
   * @return
   */
  public RpcPagination<CustomerListResponse> getCustomerPageByTag(
      RpcPagination<CustomerSearchRequest> pagination) {
    RpcPagination<CustomerListResponse> customerListResponseRpcPagination = new RpcPagination<>();
    Page page = null;
    if (!verifyCondition(pagination.getCondition())) {
      page = new Page<>(pagination.getPageNum(), pagination.getPageSize());
      PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
      pagination.setPageNum(1);
      pagination.setPageSize(1000000);
    }
    CustomerSearchRequest condition = pagination.getCondition();
    if (condition.getFollowStaff() != null) {
      condition.setFollowStaff(EmojiUtils.parseToHtmlHexadecimal(condition.getFollowStaff()));
    }
    long sta = System.currentTimeMillis();
    Page<String> oneIdsByTag = ropCommonServie.getOneIdsByTag(pagination);
    long end = System.currentTimeMillis();
    log.info("标签查询耗时:{}", (end - sta));
    List<String> result = oneIdsByTag.getResult();
    if (!CollectionUtils.isEmpty(result)) {
      CustomerSearchRequest customerSearchRequest = new CustomerSearchRequest(result);
      customerSearchRequest.setDatalist(pagination.getCondition().getDatalist());
      customerSearchRequest.setUserType(pagination.getCondition().getUserType());
      customerSearchRequest.setMerchantId(pagination.getCondition().getMerchantId());
      customerSearchRequest.setUuid(pagination.getCondition().getUuid());
      customerSearchRequest.setCustomerPhone(pagination.getCondition().getCustomerPhone());
      customerSearchRequest.setCustomerName(pagination.getCondition().getCustomerName());
      customerSearchRequest.setFollowStaff(pagination.getCondition().getFollowStaff());
      customerSearchRequest.setIsJoin(pagination.getCondition().getIsJoin());
      customerSearchRequest.setNickName(pagination.getCondition().getNickName());
      customerSearchRequest.setCarNumber(pagination.getCondition().getCarNumber());
      customerSearchRequest.setCarVin(pagination.getCondition().getCarVin());
      customerSearchRequest.setBeginCarBuyDate(pagination.getCondition().getBeginCarBuyDate());
      customerSearchRequest.setEndCarBuyDate(pagination.getCondition().getEndCarBuyDate());
      log.info("客户分群oneId列表:{}", result);
      Page<CustomerClusterListResponse> customerListByOneId = getCustomerListByOneId(
          customerSearchRequest, oneIdsByTag, page);
      if (customerListByOneId == null) {
        return customerListResponseRpcPagination;
      }
      customerListResponseRpcPagination.setPageNum(customerListByOneId.getPageNum());
      customerListResponseRpcPagination.setPageSize(customerListByOneId.getPageSize());
      customerListResponseRpcPagination.setTotal(customerListByOneId.getTotal());
      List<CustomerListResponse> list = customerListByOneId.stream().map(s -> {
        CustomerListResponse conver = BeanConverUtil.conver(s, CustomerListResponse.class);
        if (s.getAddTime() != null) {
          conver.setAddTime(DateUtils.parse(s.getAddTime()));
        }
        return conver;
      }).collect(Collectors.toList());
      customerListResponseRpcPagination.setList(list);
      return customerListResponseRpcPagination;
    }
    return customerListResponseRpcPagination;
  }

  /**
   * 设置车辆信息
   *
   * @param customerListResponses
   */
  public void setVehicel(List<CustomerListResponse> customerListResponses, Integer merchantId) {
    List<String> collect = customerListResponses.stream().map(CustomerListResponse::getOneId)
        .collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(collect)) {
      //获取车辆信息
      ScrmCustomerBatchDTO scrmCustomerDTO = new ScrmCustomerBatchDTO();
      scrmCustomerDTO.setListOneId(collect);
      scrmCustomerDTO.setMerchantId(merchantId);
      scrmCustomerDTO.setConsumer("rpc-scrm-entmicro-container");
      scrmCustomerDTO.setVersion("v1.0.0.1");
      RpcResponse<List<ScrmVehicleBasicInfoDTO>> listVehicle = scrmBigdataUtilRemote.getListVehicleBatch(
          scrmCustomerDTO);
      log.info("车辆信息:{}", listVehicle);
      if (listVehicle != null && !CollectionUtils.isEmpty(listVehicle.getResult())) {
        Map<String, List<ScrmVehicleBasicInfoDTO>> oneIdMap = listVehicle.getResult().stream()
            .collect(Collectors.groupingBy(s -> s.getOneid() + ""));
        customerListResponses.forEach(index -> {
          List<ScrmVehicleBasicInfoDTO> vehicleList = oneIdMap.get(index.getOneId());
          if (!CollectionUtils.isEmpty(vehicleList)) {
            ScrmVehicleBasicInfoDTO vehicle = vehicleList.stream()
                .sorted(Comparator.comparing(ScrmVehicleBasicInfoDTO::getBuyTime,
                    Comparator.nullsLast(Date::compareTo)).reversed())
                .collect(Collectors.toList()).get(0);
            index.setAudi(vehicle.getVehicleSeries());
            index.setCarVin(vehicle.getStandNo());
            index.setCarNumber(vehicle.getPlateNumber());
            index.setBuyDate(
                vehicle.getBuyTime() != null ? DateUtils.format(vehicle.getBuyTime()) : null);
          }
        });
      }
    }
  }


  /**
   * 查询手机号是否是企微客户
   *
   * @param phone 手机号
   * @return
   */
  public boolean isEntmicroCustomer(String phone, Integer merchantId) {
    List<Customer> entmicroCustomer = customerMapper.isEntmicroCustomer(phone, merchantId);
    if (!CollectionUtils.isEmpty(entmicroCustomer)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 员工id查客户
   *
   * @return
   */
  public List<EntmicroCustomerFollow> findByStaffId(Integer staffId) {
    return followService.findByStaffId(staffId);
  }


  public void CustomerRemarkDataExport(CustomerRemarkRequest customerRemarkRequest) {
    String exportUrl = customerRemarkRequest.getExportUrl();
    CustomerRemarkDataListener customerRemarkDataListener = new CustomerRemarkDataListener();
    EasyExcel.read(FileUtils.getInputStreamFromUrl(exportUrl), CustomerRemarkExportModel.class,
        customerRemarkDataListener).sheet().doRead();
    List<CustomerMagicRequest> customerMagicRequestList = customerRemarkDataListener.getCustomerMagicRequestList();
    if (!CollectionUtils.isEmpty(customerMagicRequestList)) {
      customerMagicRequestList.forEach(index -> {
        index.setMerchantId(customerRemarkRequest.getMerchantId());
        try {
          editCustomer(index);
        } catch (Exception e) {
          log.info("变更客户手机号失败,客户信息如下{},异常信息{}", index, e);
        }
      });
    }
  }

  /**
   * 设置导出模板的企微名称
   *
   * @param nickNameList
   * @return
   */
  public String setNickNameInfo(List<CustomerNickNameRpcResponse> nickNameList) {
    StringBuffer buffer = new StringBuffer();
    if (!CollectionUtils.isEmpty(nickNameList)) {
      for (CustomerNickNameRpcResponse nickNameRpcResponse : nickNameList) {
        //emoji转化
        if (!StringUtils.isEmpty(nickNameRpcResponse.getNickName())) {
          nickNameRpcResponse.setNickName(
              EmojiUtils.parseToUnicode(nickNameRpcResponse.getNickName()));
        }
        if (nickNameRpcResponse.getType() == null) {
          continue;
        } else if (nickNameRpcResponse.getType().equals(Constants.USER_TYPE_WECHAT)) {
          String nickName = nickNameRpcResponse.getNickName() + "@微信;";
          buffer.append(nickName);
        } else if (nickNameRpcResponse.getType().equals(Constants.USER_TYPE_ENTERPRISE)) {
          String nickName =
              nickNameRpcResponse.getNickName() + "@" + nickNameRpcResponse.getCorpName() + ";";
          buffer.append(nickName);
        }
      }
    }
    return buffer.toString();
  }

  /**
   * 根据标签查询客户
   *
   * @param merchantId 商户号
   * @param userType   用户类型
   * @param tagJson    标签json字符串
   * @return
   */
  public List<CustomerListResponse> findCustomerByTags(Integer merchantId, Integer userType,
      String tagJson, Integer combineType) {
    List<String> oneIds = new ArrayList<>();
    List<CustomerListResponse> customerListResponses = new ArrayList<>();
    try {
      // 根据标签查询客户
      List<TagSearchRequest> tagSearchRequests = JSONArray.parseArray(tagJson,
          TagSearchRequest.class);
      CustomerSearchRequest customerSearchRequest = new CustomerSearchRequest();
      customerSearchRequest.setTagLists(tagSearchRequests);
      customerSearchRequest.setMerchantId(merchantId);
      customerSearchRequest.setCombineType(combineType);
      RpcPagination<CustomerSearchRequest> customerSearchRequestRpcPagination = new RpcPagination<>();
      customerSearchRequestRpcPagination.setPageNum(1);
      customerSearchRequestRpcPagination.setPageSize(100000);
      customerSearchRequestRpcPagination.setCondition(customerSearchRequest);
      Page<String> oneIdsByTag = ropCommonServie.getOneIdsByTag(customerSearchRequestRpcPagination);
      oneIds = oneIdsByTag.getResult();
    } catch (RpcServiceException e) {
      throw new RpcServiceException(DefaultErrorEnum.DATA_INVALID);
    }
    // 查询客户详细信息
    if (!CollectionUtils.isEmpty(oneIds)) {
      CustomerSearchRequest customerSearchRequest = new CustomerSearchRequest();
      customerSearchRequest.setOneIds(oneIds);
      customerSearchRequest.setMerchantId(merchantId);
      customerSearchRequest.setDatalist(Arrays.asList(merchantId));
      customerSearchRequest.setUserType(userType);
      customerListResponses = customerList(customerSearchRequest);
    }
    return customerListResponses;
  }

  /**
   * 根据标签查询客户
   *
   * @param merchantId 商户号
   * @param userType   用户类型
   * @param crowIds    人群id
   * @return
   */
  public List<CustomerListResponse> findCustomerByCrowIds(Integer merchantId, Integer userType,
      List<Integer> crowIds, Integer combineType) {
    List<String> oneIds = new ArrayList<>();
    List<CustomerListResponse> customerListResponses = new ArrayList<>();
    try {
      oneIds = commonService.findCrowGroupCustomer(crowIds, merchantId);
    } catch (RpcServiceException e) {
      throw new RpcServiceException(DefaultErrorEnum.DATA_INVALID);
    }
    // 查询客户详细信息
    if (!CollectionUtils.isEmpty(oneIds)) {
      CustomerSearchRequest customerSearchRequest = new CustomerSearchRequest();
      customerSearchRequest.setOneIds(oneIds);
      customerSearchRequest.setMerchantId(merchantId);
      customerSearchRequest.setDatalist(Arrays.asList(merchantId));
      customerSearchRequest.setUserType(userType);
      customerListResponses = customerList(customerSearchRequest);
    }
    return customerListResponses;
  }

  /**
   * 根据客户合并id查询客户
   *
   * @param mergeIds     合并id
   * @param customerName 客户名称
   * @return
   */
  public List<CustomerInfoResponse> findCustomerBymergeIds(List<Integer> mergeIds,
      String customerName, Integer merchantId) {
    List<CustomerInfoResponse> customerBymergeIds = customerMapper.findCustomerBymergeIds(mergeIds,
        null, merchantId, customerName);
    if (!CollectionUtils.isEmpty(customerBymergeIds)) {
      List<String> collect = customerBymergeIds.stream().map(CustomerInfoResponse::getOneId)
          .collect(Collectors.toList());
      List<CustomerNickNameRpcResponse> byBatchOneId = customerMapper.findByBatchOneId(collect,
          customerBymergeIds.get(0).getMerchantId());
      Map<String, List<CustomerNickNameRpcResponse>> userIdMaps = byBatchOneId.stream()
          .filter(index -> index.getUserId() != null)
          .collect(Collectors.groupingBy(CustomerNickNameRpcResponse::getOneId));
      customerBymergeIds.forEach(index -> {
        List<CustomerNickNameRpcResponse> customerNickNameRpcResponses = userIdMaps.get(
            index.getOneId());
        if (!CollectionUtils.isEmpty(customerNickNameRpcResponses)) {
          List<String> userIds = customerNickNameRpcResponses.stream()
              .map(CustomerNickNameRpcResponse::getUserId).collect(Collectors.toList());
          index.setUserIds(userIds);
        }
      });
    }
    return customerBymergeIds;
  }

  /**
   * 根据客户合并id查询员工
   *
   * @param mergeId    合并id
   * @param merchantId 商户号
   * @return
   */
  public List<EntmicroStaffResponse> findStaffIdByCustomerIds(Integer mergeId, Integer merchantId) {
    List<EntmicroStaffResponse> staffIdByCustomerIds = entmicroStaffService.findStaffIdByCustomerIds(
        Arrays.asList(mergeId));
    if (!CollectionUtils.isEmpty(staffIdByCustomerIds)) {
      List<EntmicroStaffResponse> collect = staffIdByCustomerIds.stream()
          .filter(index -> index.getMerchantId() == merchantId.intValue())
          .collect(Collectors.toList());
      return collect;
    }
    throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
  }

  /**
   * 根据客户合并id查询员工
   *
   * @param mergeIds   合并id
   * @param merchantId 商户号
   * @return
   */
  public Map<Integer, List<EntmicroStaffResponse>> findStaffIdByCustomerIdList(
      List<Integer> mergeIds, Integer merchantId) {
    List<EntmicroStaffResponse> staffIdByCustomerIds = entmicroStaffService.findStaffIdByCustomerIds(
        mergeIds);
    if (!CollectionUtils.isEmpty(staffIdByCustomerIds)) {
      List<EntmicroStaffResponse> collect = staffIdByCustomerIds.stream()
          .filter(index -> index.getMerchantId() == merchantId.intValue())
          .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(collect)) {
        throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
      }
      return collect.stream().collect(Collectors.groupingBy(EntmicroStaffResponse::getCustomerId));
    }
    throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
  }

  /**
   * 根据客户手机号查询客户
   *
   * @param phone      手机号
   * @param merchantId 商户号
   * @return
   */
  public CustomerInfoResponse findCustomerByPhone(String phone, Integer merchantId) {
    List<CustomerInfoResponse> customerBymergeIds = customerMapper.findCustomerBymergeIds(null,
        phone, merchantId, null);
    if (CollectionUtils.isEmpty(customerBymergeIds)) {
      throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
    }
    CustomerInfoResponse customerInfoResponse = customerBymergeIds.get(0);
    ScrmCustomerDTO scrmCustomerDTO = new ScrmCustomerDTO();
    scrmCustomerDTO.setOneId(customerInfoResponse.getOneId());
    scrmCustomerDTO.setMerchantId(merchantId);
    RpcResponse<List<ScrmVehicleBasicInfoDTO>> listVehicle = scrmBigdataUtilRemote.getListVehicle(
        scrmCustomerDTO);
    if (listVehicle.isSuccess()) {
      List<ScrmVehicleBasicInfoDTO> result = listVehicle.getResult();
      if (!CollectionUtils.isEmpty(result)) {
        List<ScrmVehicleBasicInfoResponse> collect = result.stream().map(index -> {
          ScrmVehicleBasicInfoResponse scrmVehicleBasicInfoResponse = new ScrmVehicleBasicInfoResponse();
          BeanUtils.copyProperties(index, scrmVehicleBasicInfoResponse);
          return scrmVehicleBasicInfoResponse;
        }).collect(Collectors.toList());
        customerInfoResponse.setScrmVehicleBasicInfoResponses(collect);
      }
    }
    return customerInfoResponse;
  }

  public List<CustomerResponseDTO> findCustomersByExternalUserid(List<String> userIdList) {
    Example example = new Example(Customer.class);
    example.createCriteria().andIn("userid", userIdList);
    List<Customer> customers = customerMapper.selectByExample(example);
    if (customers != null && !customers.isEmpty()) {
      return BeanConverUtil.converList(customers, CustomerResponseDTO.class);
    }
    return null;
  }

  public List<String> findPhonesByUseridBefEncryption(List<String> useridBefEncryptionList) {
    Example example = new Example(Customer.class);
    example.createCriteria().andIn("useridBefEncryption", useridBefEncryptionList)
        .andEqualTo("delFlag", 0);
    List<Customer> customers = customerMapper.selectByExample(example);
    return customers.stream().map(Customer::getCustomerPhone).collect(Collectors.toList());
  }

  /**
   * 脚本 - 批量添加客户数据性能测试用
   */
  public void addBatchMagicCustomerScript(List<Integer> merchantIdList) {
    int batchCount = 20000; // 商户新增数据量
    // 10001001
    Set<String> nameSet = new HashSet<>();
    Set<String> phoneSet = new HashSet<>();
    String name = "";
    String phone = "";
    for (Integer merchantId : merchantIdList) {
      MagicDynamicRequest magicDynamicRequest = new MagicDynamicRequest();
      magicDynamicRequest.setTableName("scrm_magic_cube_customer_" + merchantId);
      magicDynamicRequest.setMerchantId(merchantId);
      List<MagicDynamicInfoRequest> dynamicInfoRequests = new ArrayList<>();
      for (int i = 0; i < batchCount; i++) {
        MagicDynamicInfoRequest magicDynamicInfoRequest = new MagicDynamicInfoRequest();
        Map<String, Object> custAttrMap = new HashMap<>();
        while (org.apache.commons.lang3.StringUtils.isEmpty(name) || nameSet.contains(name)) {
          int len = (int) (Math.random() * 3 + 1);
          name = getRandomName(len);
        }
        nameSet.add(name);
        while (org.apache.commons.lang3.StringUtils.isEmpty(phone) || phoneSet.contains(phone)) {
          phone = getTel();
        }
        phoneSet.add(phone);
        custAttrMap.put("customer_name", name);
        custAttrMap.put("customer_phone", phone);
        custAttrMap.put("customer_idcard_no", "000000000000000000");
        magicDynamicInfoRequest.setCustomerPhone(phone);
        magicDynamicInfoRequest.setCustAttr(custAttrMap);
        Map<String, Object> baseAttrMap = new HashMap<>();
        baseAttrMap.put("car_number", null);
        baseAttrMap.put("car_vin", "00000000000000000");
        baseAttrMap.put("car_buying_date", null);
        baseAttrMap.put("car_series", null);
        baseAttrMap.put("car_model", null);
        baseAttrMap.put("trustee_phone", null);
        baseAttrMap.put("customer_level", null);
        baseAttrMap.put("test_drive", null);
        baseAttrMap.put("intended_vehicle_series", null);
        baseAttrMap.put("amounts", null);
        baseAttrMap.put("settlement_time", null);
        baseAttrMap.put("power_of_attorney_repair_type", null);
        baseAttrMap.put("commencement_date", null);
        magicDynamicInfoRequest.setBaseAttr(baseAttrMap);
        dynamicInfoRequests.add(magicDynamicInfoRequest);
        if (i % 2000 == 0) {
          magicDynamicRequest.setCustomers(dynamicInfoRequests);
          this.customerAddMagic(magicDynamicRequest);
          dynamicInfoRequests = new ArrayList<>();
        }
      }
      magicDynamicRequest.setCustomers(dynamicInfoRequests);
      this.customerAddMagic(magicDynamicRequest);
    }
  }

  /**
   * 获取随机手机号码
   */
  private String[] telFirst = "234,235,236,237,238,239,250,251,252,257,258,259,230,231,232,255,256,233,253".split(
      ",");

  private String getTel() {
    int index = getNum(0, telFirst.length - 1);
    String first = telFirst[index];
    String second = String.valueOf(getNum(1, 888) + 10000).substring(1);
    String third = String.valueOf(getNum(1, 9100) + 10000).substring(1);
    return first + second + third;
  }

  public static int getNum(int start, int end) {
    return (int) (Math.random() * (end - start + 1) + start);
  }

  /**
   * 获取随机中文姓名
   */
  public String getRandomName(int len) {
    String randomName = "";
//        int index = (int) (Math.random() * surname.length);
    for (int i = 0; i < len; i++) {
      String str = null;
      int hightPos, lowPos; // 定义高低位
      Random random = new Random();
      hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值
      lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值
      byte[] b = new byte[2];
      b[0] = (new Integer(hightPos).byteValue());
      b[1] = (new Integer(lowPos).byteValue());
      try {
        str = new String(b, "GBK"); // 转成中文
      } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
      }
      randomName += str;
    }
    return randomName;
  }

  /**
   * 查询客户信息
   *
   * @param customerMergeRequest 客户信息
   */
  public String findCustomer(CustomerMergeRequest customerMergeRequest) {
    Integer merchantId = customerMergeRequest.getMerchantId();
    String oneId = customerMergeRequest.getOneId();
    // 1.变更基础表的信息
    List<CustomerMerge> customer = customerMergeMapper.findByOneIdAndMerchant(oneId, merchantId);
    if (!CollectionUtils.isEmpty(customer)) {
      List<CustomerMergeRequest> collect = customer.stream().map(index -> {
        CustomerMergeRequest cust = new CustomerMergeRequest();
        BeanUtils.copyProperties(index, cust);
        return cust;
      }).collect(Collectors.toList());
      return JSONObject.toJSONString(collect, SerializerFeature.WriteMapNullValue);
    }
    return null;
  }

  /**
   * 新增客户信息
   *
   * @param customerMergeRequest 客户信息
   */
  public void addCustomer(CustomerMergeRequest customerMergeRequest) {
    String oneId = customerMergeRequest.getOneId();
    // 1.变更基础表的信息
    Date createdTime = customerMergeRequest.getCreatedTime();
    insertCustomer(customerMergeRequest, createdTime);
    // 2.变更合并表的信息
    CustomerMerge customerMerge = new CustomerMerge();
    BeanUtils.copyProperties(customerMergeRequest, customerMerge);
    if (createdTime == null) {
      customerMerge.setCreatedTime(new Date());
    }
    customerMerge.setIsJoin(0);
    customerMerge.setStatus(0);
    customerMerge.setUpdatedTime(new Date());
    updateMergeCustomer(customerMerge, oneId, false);
  }

  private void insertCustomer(CustomerMergeRequest customerMergeRequest, Date createdTime) {
    Customer customer = new Customer();
    BeanUtils.copyProperties(customerMergeRequest, customer);
    customer.setDelFlag(Constants.NORMAL_FLAG);
    customer.setMerchantid(customerMergeRequest.getMerchantId());
    if (createdTime == null) {
      customer.setCreatedTime(new Date());
    }
    // 保单和魔方不保存企微名称
    Integer addWay = customer.getAddWay();
    if ((addWay != null && (addWay == 101 || addWay == 103)) || StringUtils.isEmpty(
        customer.getCustomerName())) {
      customer.setCustomerName(null);
    }
    customerMapper.insert(customer);
  }

  /**
   * 更新客户信息
   *
   * @param customerMergeRequest 客户信息
   */
  public void updateCustomer(CustomerMergeRequest customerMergeRequest) {
    String oneId = customerMergeRequest.getOneId();
    // 1.变更基础表的信息
    Customer customer = customerMapper.getNotEntmicroCustomerByOneId(customerMergeRequest);
    if (customer != null) {
      CopyUtils.copyProperties(customerMergeRequest, customer);
      // 保单和魔方不保存企微名称
      Integer addWay = customer.getAddWay();
      if ((addWay != null && (addWay == 101 || addWay == 103)) || StringUtils.isEmpty(
          customer.getCustomerName())) {
        customer.setCustomerName(null);
      }
      customerMapper.updateByPrimaryKeySelective(customer);
    } else {
      insertCustomer(customerMergeRequest, customerMergeRequest.getCreatedTime());
    }
    // 2.变更合并表的信息
    CustomerMerge customerMerge = new CustomerMerge();
    BeanUtils.copyProperties(customerMergeRequest, customerMerge);
    customerMerge.setType(null);
    updateMergeCustomer(customerMerge, oneId, false);
  }

  /**
   * 完善客户手机号
   *
   * @param userIdList 企微客户userId
   * @param phone      备注手机号
   * @param merchantId 商户号(可空)
   * @return
   */
  public String perfectCustomerPhone(List<String> userIdList, String phone, Integer merchantId) {
    log.info("完善客户手机号参数userId:{},手机号:{},merchantId:{}", userIdList, phone, merchantId);
    if (CollectionUtils.isEmpty(userIdList)) {
      throw new RpcServiceException("1", "该用户没有加入企微!");
    }
    if (StringUtils.isEmpty(phone) || !Pattern.matches(
        "^1(3[0-9]|4[0-1,4-9]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\\d{8}$", phone)) {
      throw new RpcServiceException("2", "联系电话不符合要求,请重新输入!");
    }
    List<String> phoneList = customerMergeMapper.selectCustomerExistPhoneByUserId(userIdList,
        merchantId);
    if (!CollectionUtils.isEmpty(phoneList)) {
      throw new RpcServiceException("3", "该用户手机号已存在!");
    }
    for (String userId : userIdList) {
      try {
        //查询客户跟进人
        CustomerMagicRequest customerMagicRequest = messageConvertService.convertRemarkPhoneParam(
            userId, phone);
        Integer merchantNo = entmicroStaffService.findSupMerchantNo(
            customerMagicRequest.getMerchantId());

        //客户信息 手机号 userId
        CustomerInfoRequest customerInfoRequest = new CustomerInfoRequest();
        customerInfoRequest.setUserid(userId);
        customerInfoRequest.setCustomerPhone(phone);

        CustomerStandardRequest customerStandardRequest = new CustomerStandardRequest();
        customerStandardRequest.setCustomerInfo(customerInfoRequest);
        //客户跟进人
        customerStandardRequest.setFollowerStaff(customerMagicRequest.getFollowerStaff());
        customerEdit(customerStandardRequest, true, merchantNo);
      } catch (Exception e) {
        log.info("完善客户手机号异常,userId:{},手机号:{},异常信息: {}", userIdList, phone, e);
        e.printStackTrace();
      }
    }
    String oneId = customerMergeMapper.selectOneIdByCustomerPhone(phone, merchantId);
    if (oneId == null) {
      throw new RpcServiceException("4", "手机号修改失败");
    }
    return oneId;
  }

  /**
   * 验证查询条件 无条件返回true,有条件返回false
   *
   * @return
   */
  public Boolean verifyCondition(CustomerSearchRequest condition) {
    if (condition == null) {
      return true;
    }
    if (!StringUtils.isEmpty(condition.getFollowStaff()) || !StringUtils.isEmpty(
        condition.getCustomerPhone())
        || !StringUtils.isEmpty(condition.getCustomerName()) || !StringUtils.isEmpty(
        condition.getNickName())
        || condition.getIsJoin() != null || !StringUtils.isEmpty(condition.getCarNumber())
        || !StringUtils.isEmpty(condition.getCarVin()) || !StringUtils.isEmpty(
        condition.getCarSeries())
        || condition.getBeginCInsEndDate() != null || condition.getEndInsEndDate() != null
        || condition.getBeginCarBuyDate() != null || condition.getEndCarBuyDate() != null) {
      return false;
    }
    return true;
  }

  public List<CustGroupResponse> filterCustomerChatIdsByStaffIds(Integer merchantId,
      List<Integer> staffIds) {
    if (staffIds == null || staffIds.isEmpty()) {
      return null;
    }
    return customerMapper.filterCustomerChatIdsByStaffIds(merchantId, staffIds);
  }

  public List<CustomerListResponse> findCustomerByOpenCondition(
      CustomerOpenRequest customerOpenRequest) {
    List<CustomerListResponse> customerByOpenCondition = customerMergeMapper.findCustomerByOpenCondition(
        customerOpenRequest);
    if (!CollectionUtils.isEmpty(customerByOpenCondition)) {
      List<String> collect = customerByOpenCondition.stream().map(CustomerListResponse::getOneId)
          .collect(Collectors.toList());
      List<CustomerNickNameRpcResponse> byBatchOneId = customerMapper.findByBatchOneId(collect,
          customerOpenRequest.getMerchantId());
      Map<String, List<CustomerNickNameRpcResponse>> userIdMaps = byBatchOneId.stream()
          .filter(index -> index.getUserId() != null)
          .collect(Collectors.groupingBy(CustomerNickNameRpcResponse::getOneId));
      customerByOpenCondition.forEach(index -> {
        List<CustomerNickNameRpcResponse> customerNickNameRpcResponses = userIdMaps.get(
            index.getOneId());
        if (!CollectionUtils.isEmpty(customerNickNameRpcResponses)) {
          List<String> userIds = customerNickNameRpcResponses.stream()
              .map(CustomerNickNameRpcResponse::getUserId).collect(Collectors.toList());
          index.setUserIds(userIds);
          setNickName(byBatchOneId, index.getOneId());
          index.setNickNameList(customerNickNameRpcResponses);
        }
      });
    }
    return customerByOpenCondition;
  }

  public Map<Integer, List<CustomerInfoResponse>> findCusetomerListByMergeIds(
      List<Integer> mergeIds, Integer merchantId, Integer staffId) {
    List<CustomerInfoResponse> cusetomerListByMergeIds = customerMapper.findCusetomerListByMergeIds(
        mergeIds, merchantId, staffId);
    if (!CollectionUtils.isEmpty(cusetomerListByMergeIds)) {
      Map<Integer, List<CustomerInfoResponse>> collect = cusetomerListByMergeIds.stream()
          .collect(Collectors.groupingBy(CustomerInfoResponse::getMergeId));
      return collect;
    }
    return null;
  }

  public Map<String, CustomerInfoResponse> findCusetomerListByOneIds(List<String> oneIds,
      Integer merchantId) {
    return customerMergeMapper.getCustomerByOneIds(oneIds, merchantId);
  }

  public List<Integer> getMergeIdList(List<Integer> customerIds, Integer merchantId) {
    return customerMapper.getMergeIdList(customerIds, merchantId);
  }

  public CrowdGroupDetailRopResponse queryCrowdListByCrowdGroupId(Integer groupId) {
    return ropCommonServie.queryCrowdListByCrowdGroupId(groupId);
  }

  /**
   * 查询门店下的企微客户
   *
   * @param merchantId
   * @return
   */
  public List<Customer> selectCustomerByMerchant(Integer merchantId) {
    return customerMapper.selectCustomerByMerchant(merchantId);
  }

  public CustomerOneIdDto queryOneIdByPhoneNumber(SearchCustomerOneIdDto dto) {
    RpcAssert.assertNotNull(dto, DefaultErrorEnum.PARAMETER_NULL);
    RpcAssert.assertNotNull(dto.getMerchantId(), DefaultErrorEnum.PARAMETER_NULL,
        "门店号不能为空!");
    RpcAssert.assertNotNull(dto.getPhone(), DefaultErrorEnum.PARAMETER_NULL, "手机号不能为空!");
    List<String> list = customerMapper.queryOneIdByPhoneNumber(dto.getPhone(), dto.getMerchantId());
    CustomerOneIdDto resp = new CustomerOneIdDto();
    resp.setMerchantId(dto.getMerchantId());
    resp.setPhone(dto.getPhone());
    resp.setOneIdList(list);
    return resp;
  }

  /**
   * 查询目前已关注公众号用户信息
   *
   * @param appId 公众号appId
   * @return 映射表列表
   */
  public List<WechatSubscriberMappingDO> findWechatSubscriberListByAppId(String appId) {
    RpcAssert.assertNotEmpty(appId, DefaultErrorEnum.PARAMETER_NULL, "appId is not be null");
    Example example = new Example(WechatSubscriberMappingDO.class);
    example.createCriteria().andEqualTo("delFlag", 0).andEqualTo("appId", appId);
    List<WechatSubscriberMappingDO> mappingDOList = wechatSubscriberMappingMapper.selectByExample(
        example);
    log.info("查询目前已关注公众号用户信息 mappingDOList:{}", mappingDOList);
    return mappingDOList;
  }

  /**
   * 新增公众号关注用户openId和unionId映射表
   *
   * @param mappingDOList 映射表实例
   * @return 新增行数
   */
  public int insertWechatSubscriberMapping(List<WechatSubscriberMappingDO> mappingDOList) {
    log.info("新增公众号关注用户映射表 mappingDOList:{}", mappingDOList);
    if (CollectionUtils.isEmpty(mappingDOList)) {
      return 0;
    }
    return wechatSubscriberMappingMapper.insertList(mappingDOList);
  }

  /**
   * 更改公众号关注用户openId和unionId映射表
   *
   * @param openIdList 映射表openIdList
   * @param appId      公众号appId
   * @param subscribe  关注状态
   * @return 更改行数
   */
  public int updateWechatSubscriberMapping(List<String> openIdList, String appId,
      Integer subscribe) {
    if (StringUtils.isEmpty(appId) || subscribe == null || CollectionUtils.isEmpty(openIdList)) {
      return 0;
    }
    Example example = new Example(WechatSubscriberMappingDO.class);
    example.createCriteria().andEqualTo("delFlag", 0).andEqualTo("appId", appId)
        .andIn("openId", openIdList);
    WechatSubscriberMappingDO record = new WechatSubscriberMappingDO();
    record.setSubscribe(subscribe);
    record.setUpdatedTime(new Date());
    return wechatSubscriberMappingMapper.updateByExampleSelective(record, example);
  }

  /**
   * 更新用户是否关注公众号状态
   *
   * @param appId      公众号开发者凭据 AppId
   * @param merchantId 商户号
   */
  public void updateCustomerMergeSubscribe(String appId, Integer merchantId) {
    RpcAssert.assertNotEmpty(appId, DefaultErrorEnum.PARAMETER_NULL, "appId is not be null");
    customerMapper.updateCustomerMergeSubscribe(appId, merchantId);
  }

  /**
   * 更新用户unionId
   *
   * @param userId  用户userId
   * @param unionId 用户unionId
   * @return 更新行数
   */
  public int updateCustomerUnionIdByUserId(String userId, String unionId) {
    if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(unionId)) {
      return 0;
    }
    Example example = new Example(Customer.class);
    example.createCriteria().andEqualTo("delFlag", 0).andEqualTo("userid", userId);
    Customer record = new Customer();
    record.setUnionId(unionId);
    return customerMapper.updateByExampleSelective(record, example);
  }

  /**
   * 查询不存在unionId的用户
   *
   * @param merchantId 商户号
   * @return userId
   */
  public List<String> findUseridByUnionIdIsNull(Integer merchantId) {
    return customerMapper.selectUseridByUnionIdIsNull(merchantId);
  }

  /**
   * 更新用户登录小程序状态
   *
   * @param merchantId 商户号
   * @param unionId    unionId
   * @return 更新结果
   */
  public Boolean recordIsLoginApplet(Integer merchantId, String unionId) {
    RpcAssert.assertNotEmpty(merchantId + "", DefaultErrorEnum.PARAMETER_NULL,
        "merchantId is not be null");
    RpcAssert.assertNotEmpty(unionId, DefaultErrorEnum.PARAMETER_NULL, "unionId is not be null");
    CustomerSearchRequest request = new CustomerSearchRequest();
    request.setUserType(1);
//        request.setIsLoginApplet(0);
    request.setMerchantId(merchantId);
    request.setDatalist(Collections.singletonList(merchantId));
    request.setUnionId(unionId);
    Example example = new Example(CustomerMerge.class);
    example.createCriteria().andEqualTo("delFlag", 0).andEqualTo("unionId", unionId)
        .andEqualTo("merchantId", merchantId);
    List<CustomerMerge> mergeList = customerMergeMapper.selectByExample(example);
    log.info("用户是否登录过小程序 merchantId:{},unionId:{},mergeList:{}", merchantId, unionId,
        mergeList);
    if (mergeList == null) {
      return false;
    }
    List<CustomerMerge> notLoginAppletList = mergeList.stream()
        .filter(s -> s.getIsLoginApplet() == null || s.getIsLoginApplet() != 1)
        .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(notLoginAppletList)) {
      return false;
    }
    String oneId = notLoginAppletList.get(0).getOneId();
    if (StringUtils.isEmpty(oneId)) {
      return false;
    }
    CustomerMerge record = new CustomerMerge();
    record.setIsLoginApplet(1);
    int i = updateCustomerMergeByOneId(record, oneId, merchantId);
    return i >= 1;
  }

  /**
   * 根据oneId更新客户合并表
   *
   * @param record     更新参数
   * @param oneId      客户oneid
   * @param merchantId 商户号
   * @return 更改行数
   */
  public int updateCustomerMergeByOneId(CustomerMerge record, String oneId, Integer merchantId) {
    RpcAssert.assertNotEmpty(merchantId + "", DefaultErrorEnum.PARAMETER_NULL,
        "merchantId is not be null");
    RpcAssert.assertNotEmpty(oneId, DefaultErrorEnum.PARAMETER_NULL, "oneId is not be null");
    Example example = new Example(CustomerMerge.class);
    example.createCriteria().andEqualTo("delFlag", 0).andEqualTo("oneId", oneId)
        .andEqualTo("merchantId", merchantId);
    return customerMergeMapper.updateByExampleSelective(record, example);
  }

  /**
   * @param userIdList,
   * @return
   */
  public Map<String, CustomerFollowStaffResponse> getCustomerStaffByUserId(
      List<String> userIdList) {
    return customerMapper.getCustomerStaffByUserId(userIdList);
  }

  /**
   * oneId查跟进员工
   *
   * @return
   */
  public Map<String, CustomerFollowStaffResponse> getCustomerStaffByOneId(List<String> oneIds,
      Integer merchantId) {
    return customerMapper.getCustomerStaffByOneId(oneIds, merchantId);
  }

  public List<StaffFollowResponse> selectFollowStaffByCustomerPhone(Integer merchantId,
      String customerPhone,
      List<Integer> staffIdList, List<String> userIdList) {
    RpcAssert.assertNotEmpty(merchantId + "", DefaultErrorEnum.PARAMETER_NULL,
        "merchantId is not be null");
    return customerMapper.selectFollowStaffByCustomerPhone(merchantId, customerPhone, staffIdList,
        userIdList);
  }

  /**
   * userId查客户
   *
   * @param userid
   * @return
   */
  public Map<String, Customer> getCustomersByUserId(List<String> userid) {
    if (CollectionUtils.isEmpty(userid)) {
      return null;
    }
    return customerMapper.getCustomersByUserId(userid);
  }

  /**
   * oneId查跟进人
   *
   * @param oneIdList
   * @param merchantIdList
   * @return
   */
  public List<CustomerFollowStaffResponse> getListCustomerStaffByOneId(List<Integer> merchantIdList,
      List<String> oneIdList, List<Integer> staffIdList) {
    if (CollectionUtils.isEmpty(merchantIdList) && CollectionUtils.isEmpty(oneIdList)
        && CollectionUtils.isEmpty(staffIdList)) {
      return null;
    }
    return customerMapper.getListCustomerStaffByOneId(merchantIdList, oneIdList, staffIdList);
  }

  /**
   * 客户主键查跟进人id
   *
   * @param id
   * @return
   */
  public List<Integer> getStaffByCustomerId(Integer id) {
    if (null == id) {
      return null;
    }
    return customerMapper.getStaffByCustomerId(id);
  }

  /**
   * 客户适配
   *
   * @param loginCallBackModel 客户回调信息
   */
  public void matchCustomer(CustomerListCallBackModel loginCallBackModel) {
    List<CustomerCallBackModel> contactList = loginCallBackModel.getContactList();
    if (CollectionUtils.isEmpty(contactList)) {
      return;
    }
    // 2.查询员工账号
    EntmicroStaff staffByPhoneAndMerchantNo = entmicroStaffService.findStaffByPhoneAndMerchantNo(
        new LoginCallBackModel(loginCallBackModel.getUserId() + ""));
    if (staffByPhoneAndMerchantNo == null || staffByPhoneAndMerchantNo.getEntmicroId() != null) {
      log.info("当前员工系统未查到或者是托管的企微不匹配客户");
      return;
    }
    // 3.匹配授权账号下的客户,更新加密前的客户id
    List<CustomerInfoResponse> customerByStaffId = findCustomerByStaffId(
        staffByPhoneAndMerchantNo.getId(), null);
    List<Customer> customerList = new ArrayList<>();
    for (CustomerCallBackModel index : contactList) {
      Customer customer = new Customer();
      String avatar = index.getAvatar();
      String nickname = index.getNickname();
      List<CustomerInfoResponse> collect = customerByStaffId.stream()
          .filter(ind -> ind.getAvatar().equals(avatar) || ind.getCustomerName().equals(nickname))
          .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(collect)) {
        continue;
      }
      CustomerInfoResponse customerInfoResponse = collect.get(0);
      customer.setId(customerInfoResponse.getId());
      customer.setUseridBefEncryption(index.getUserId() + "");
      customerList.add(customer);
    }
    if (!CollectionUtils.isEmpty(customerList)) {
      customerMapper.batchUpdate(customerList);
    }
  }

  public void addCustomer(CustomerModel customerModel, Boolean flag, Integer merchantId) {
    customerAdd(bussinessModelConvertService.converCustomer(customerModel), true, merchantId);
  }

  /**
   * 根据条件查询客户
   *
   * @param merchantId 商户号
   * @param phoneList  手机号集合
   * @return
   */
  public List<CustomerInfoResponse> findAddEntmicroCustomerByPhones(Integer merchantId,
      List<String> phoneList) {
    return customerMapper.findAddEntmicroCustomerByPhones(merchantId, phoneList);
  }


  /**
   * 1.更新客户标签 2.更新客户群标签 3.通知用户
   *
   * @param reportCustomerRequest 上报信息
   */
  public void reportCustomerList(ReportCustomerRequest reportCustomerRequest) {
    // 更新客户标签
    log.info("客户上报参数{},", JSONObject.toJSONString(reportCustomerRequest));
    List<String> userIds = reportCustomerRequest.getUserIds();
    Integer merchantId = reportCustomerRequest.getMerchantId();
    List<String> phones = reportCustomerRequest.getPhones();
    if (CollectionUtils.isEmpty(userIds)) {
      if (!CollectionUtils.isEmpty(phones)) {
        reportCustomerList(phones, merchantId, reportCustomerRequest.getReportType(), true);
      }
    } else {
      reportCustomerList(userIds, merchantId, reportCustomerRequest.getReportType(), false);
    }
  }

  private void reportCustomerList(List<String> userIds, Integer merchantId, Integer reportType,
      boolean b) {
    List<String> collect = userIds.stream().map(index -> {
      Map<String, Object> map = new HashMap<>();
      if (b) {
        map.put("customer_phone", index);
      } else {
        map.put("user_id", index);
      }
      map.put("add_way", "101");
      if (reportType.intValue() == ReportTypeEnum.INTENTION.getAttType()) {
        map.put("latent_customer_flag", 1);
      } else if (reportType.intValue() == ReportTypeEnum.ORDER.getAttType()) {
        map.put("order_customer_flag", 1);
      }
      map.put("merchant_id", merchantId);
      return JSONObject.toJSONString(map);
    }).collect(Collectors.toList());
    RpcResponse<Boolean> booleanRpcResponse = customerCollectRemote.reportCustomerList(collect);
    if (booleanRpcResponse.isSuccess()) {
      log.info("客户上报成功{}", JSONObject.toJSONString(collect));
    }
  }

  /**
   * 根据userid和商户号查询客户信息
   *
   * @param userId     用户id
   * @param merchantId 商户号
   * @return
   */
  public CustomerInfoResponse findCustomerByUserId(String userId, Integer merchantId) {
    return customerMergeMapper.findCustomerByUserId(userId, merchantId);
  }

  /**
   * 根据id查询意向和下单客户
   *
   * @param customerIds 客户id
   * @param merchantId  商户号
   * @return
   */
  public Map<Integer, List<Integer>> getCustomerByLabel(List<Integer> customerIds,
      Integer merchantId) {
    Integer intentionGroupId = environment.getProperty("intention.groupId", Integer.class);
    Integer intentionLabelId = environment.getProperty("intention.labelId", Integer.class);
    Integer orderGroupId = environment.getProperty("order.groupId", Integer.class);
    Integer orderLabelId = environment.getProperty("order.labelId", Integer.class);
    Map<Integer, List<Integer>> map = new HashMap<>();
    Example example = new Example(Customer.class);
    example.createCriteria().andIn("id", customerIds);
    List<Customer> customers = customerMapper.selectByExample(example);

    UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo labelInfo = new UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo();
    labelInfo.setGroupId(intentionGroupId);
    labelInfo.setLabelId(intentionLabelId);
    labelInfo.setGroupType("系统标签");
    List<String> oneid = searchCustomerByLabel(merchantId, labelInfo);
    if (!StringUtils.isEmpty(oneid)) {
      List<Integer> collect = customers.stream().filter(index -> oneid.contains(index.getOneId()))
          .map(Customer::getId).collect(Collectors.toList());
      map.put(1, collect);
    }
    UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo orderLabelInfo = new UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo();
    orderLabelInfo.setGroupId(orderGroupId);
    orderLabelInfo.setLabelId(orderLabelId);
    orderLabelInfo.setGroupType("系统标签");
    List<String> orderOneid = searchCustomerByLabel(merchantId, orderLabelInfo);
    if (!StringUtils.isEmpty(orderOneid)) {
      List<Integer> collect = customers.stream()
          .filter(index -> orderOneid.contains(index.getOneId())).map(Customer::getId)
          .collect(Collectors.toList());
      map.put(2, collect);
    }
    return map;
  }

  /**
   * 根据id查询意向和下单客户
   *
   * @param customerIds 客户id
   * @param merchantId  商户号
   * @return
   */
  public Map<Integer, List<Integer>> getCustomerByMegerIdLabel(List<Integer> customerIds,
      Integer merchantId) {
    Integer intentionGroupId = environment.getProperty("intention.groupId", Integer.class);
    Integer intentionLabelId = environment.getProperty("intention.labelId", Integer.class);
    Integer orderGroupId = environment.getProperty("order.groupId", Integer.class);
    Integer orderLabelId = environment.getProperty("order.labelId", Integer.class);
    Map<Integer, List<Integer>> map = new HashMap<>();
    Example example = new Example(Customer.class);
    example.createCriteria().andIn("id", customerIds);
    List<CustomerMerge> customerMerges = customerMergeMapper.selectByExample(example);
    if (!CollectionUtils.isEmpty(customerMerges)) {
      OneIdSearch oneIdSearch = new OneIdSearch();
      oneIdSearch.setMerchantId(merchantId);
      List<String> oneIdList = customerMerges.stream().map(CustomerMerge::getOneId)
          .collect(Collectors.toList());
      oneIdSearch.setOneIdList(oneIdList);
      RpcResponse<Map<String, String>> oneIdByOneIdList = oneIdRemote.findOneIdByOneIdList(
          oneIdSearch);
      if (oneIdByOneIdList.isSuccess()) {
        Map<String, String> result = oneIdByOneIdList.getResult();
        customerMerges.forEach(index -> {
          index.setOneId(result.get(index.getOneId()));
        });
      }
      UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo labelInfo = new UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo();
      labelInfo.setGroupId(intentionGroupId);
      labelInfo.setLabelId(intentionLabelId);
      labelInfo.setGroupType("系统标签");
      List<String> oneid = searchCustomerByLabel(merchantId, labelInfo);
      if (!StringUtils.isEmpty(oneid)) {
        List<Integer> collect = customerMerges.stream()
            .filter(index -> oneid.contains(index.getOneId())).map(CustomerMerge::getId)
            .collect(Collectors.toList());
        map.put(1, collect);
      }
      UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo orderLabelInfo = new UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo();
      orderLabelInfo.setGroupId(orderGroupId);
      orderLabelInfo.setLabelId(orderLabelId);
      orderLabelInfo.setGroupType("系统标签");
      List<String> orderOneid = searchCustomerByLabel(merchantId, orderLabelInfo);
      if (!StringUtils.isEmpty(orderOneid)) {
        List<Integer> collect = customerMerges.stream()
            .filter(index -> orderOneid.contains(index.getOneId())).map(CustomerMerge::getId)
            .collect(Collectors.toList());
        map.put(2, collect);
      }
    }
    return map;
  }

  private List<String> searchCustomerByLabel(Integer merchantId,
      UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo labelInfo) {
    UserQueryByLabelDTO.UserQueryByLabelReq userQueryByLabelReq = new UserQueryByLabelDTO.UserQueryByLabelReq();
    userQueryByLabelReq.setMerchantId(merchantId);
    userQueryByLabelReq.setPageNum(1);
    userQueryByLabelReq.setPageSize(100000);
    userQueryByLabelReq.setLabelInfoList(Arrays.asList(labelInfo));
    UserQueryByLabelDTO.UserQueryByLabelRet userQueryByLabelRet = userProfileRemote.queryOneIdListByLabel(
        userQueryByLabelReq);
    if (userQueryByLabelRet.getCode() == 0) {
      return userQueryByLabelRet.getOneIdList();
    }
    throw new RpcServiceException("查询标签客户异常{}", userQueryByLabelRet.getMessage());
  }

  /**
   * 获取客户跟进记录
   */
  public List<CustomerRecordResponse> getCustomerRecords(CustRecordRequest request) {
    List<CustomerRecordResponse> result = new ArrayList<>();
    String id = StringUtils.isEmpty(request.getUserId()) ? request.getOneId() : request.getUserId();
    CustomerInfoResponse customer = customerMapper.findCustomerByUserIdOrOneId(id,
        request.getMerchantId());
    if (null == customer) {
      throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST);
    }

    // 获取员工记录
    List<CustomerFollowStaffResponse> custFollows = followService.findRelationByUserId(id);
    if (!CollectionUtils.isEmpty(custFollows)) {
      List<CustomerRecordResponse> custRecords = custFollows.stream()
          .map(p -> new CustomerRecordResponse("成为好友", "关联员工: " + p.getStaffName(),
              p.getCreatedTime()))
          .collect(Collectors.toList());
      custRecords.get(custFollows.size() - 1).setTitle("首次添加");
      result.addAll(custRecords);
    }
    // 获取领取卡券记录
    RpcPagination<UserDirectionalGiftListDTO> giftRequest = new RpcPagination<>();
    giftRequest.setPageSize(Integer.MAX_VALUE);
    giftRequest.setNeedCount(false);
    UserDirectionalGiftListDTO condition = new UserDirectionalGiftListDTO();
    condition.setNickName(customer.getCustomerPhone());
    giftRequest.setCondition(condition);
    RpcResponse<RpcPagination<BackstageUserDirectionalGiftResponse>> giftResponse = userDirectionalGiftRemote.getUserDirectionalGiftSaasList(
        giftRequest);
    if (giftResponse.hasResult()) {
      List<CustomerRecordResponse> giftRecords = giftResponse.getResult().getList().stream()
          .map(p -> {
            String coupons =
                CollectionUtils.isEmpty(p.getCouponList()) ? "" : p.getCouponList().stream()
                    .filter(c -> !StringUtils.isEmpty(c.getCouponName()))
                    .map(c -> c.getCouponName())
                    .collect(Collectors.joining("、"));
            return new CustomerRecordResponse("领取卡券", "优惠券: " + coupons, p.getCreatedDate());
          })
          .collect(Collectors.toList());
      result.addAll(giftRecords);
    }

    // 获取参加且支付成功的活动记录
    RpcResponse<List<CustomerActivityRecordDTO>> activityRecordRes = activityRemote.listByCustomerPhoneAndPaidOrder(
        customer.getCustomerPhone());
    if (activityRecordRes.hasResult()) {
      List<CustomerRecordResponse> activityRecords = activityRecordRes.getResult().stream()
          .map(p -> new CustomerRecordResponse("参加活动", "活动名称: " + p.getActivityName(),
              p.getOrderPaidDate()))
          .collect(Collectors.toList());
      result.addAll(activityRecords);
    }

    // 排序
    result.sort((s1, s2) -> s1.getTime().equals(s2.getTime()) ? 0
        : s1.getTime().after(s2.getTime()) ? -1 : 1);
    return result;
  }

  /**
   * 获取用户物业信息
   */
  public CustomerPropertyInfoDTO getUserPropertyMessageByOneId(String oneId) {
    RpcAssert.assertNotNull(oneId, DefaultErrorEnum.PARAMETER_NULL, "oneId must not be null");
    Example example = new Example(CustomerMerge.class);
    example.createCriteria().andEqualTo("oneId", oneId).andEqualTo("delFlag", 0);
    List<CustomerPropertyInfoDTO> list = customerMergeMapper.getUserPropertyMessageByOneId(oneId);
    if (!CollectionUtils.isEmpty(list)) {
      return list.get(0);
    }
    return null;
  }

  /**
   * 更新用户物业信息
   */
  public Boolean updateUserPropertyMessageByOneId(CustomerPropertyInfoDTO request) {
    RpcAssert.assertNotNull(request.getOneId(), DefaultErrorEnum.PARAMETER_NULL,
        "oneId must not be null");
    Example example = new Example(CustomerMerge.class);
    Example.Criteria criteria = example.createCriteria();
    criteria.andEqualTo("oneId", request.getOneId()).andEqualTo("delFlag", 0);
    CustomerMerge record = new CustomerMerge();
    BeanUtils.copyProperties(request, record);
    customerMergeMapper.updateByExampleSelective(record, example);

    criteria.andEqualTo("merchantId", request.getMerchantId());
    List<CustomerMerge> list = customerMergeMapper.selectByExample(example);
    if (!CollectionUtils.isEmpty(list)) {
      CustomerMerge customerMerge = list.get(0);
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("merchant_id", customerMerge.getMerchantId());
      jsonObject.put("add_way", "109");
      jsonObject.put("community", customerMerge.getCommunity());
      jsonObject.put("building", customerMerge.getBuilding());
      jsonObject.put("room", customerMerge.getRoom());
      jsonObject.put("customer_phone", customerMerge.getCustomerPhone());
      if (!ObjectUtils.isEmpty(customerMerge.getUnionId())) {
        jsonObject.put("union_id", customerMerge.getUnionId());
      }

      List<DictDataResponse> homeownerTypeList = merchantService.findAllByDictType(
          "homeowner_type");
      if (!CollectionUtils.isEmpty(homeownerTypeList) && !ObjectUtils.isEmpty(
          customerMerge.getHomeownerType())) {
        for (DictDataResponse dictDataResponse : homeownerTypeList) {
          if (customerMerge.getHomeownerType().equals(dictDataResponse.getDictValue().toString())) {
            jsonObject.put("homeowner_name", dictDataResponse.getDictLabel());
          }
        }
      }
      producerComponent.sendCustomerToKafka(jsonObject.toJSONString());
    }
    return true;
  }

  /**
   * 推送企微客户到sop
   *
   * @param sopCusSendRequest 请求信息
   */
  public void sendCustomerToSop(SopCusSendRequest sopCusSendRequest) {
    // 1.查询门店下面的企微客户 分批次处理
    List<EntmiroCustomerInfo> entmiroCustomerInfoList = customerMergeMapper.findEntmicroCusByMerchantId(
        sopCusSendRequest.getMerchantId());
    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(entmiroCustomerInfoList)) {
      // 2.查询客户的车牌号,客户标签
      // 3.推送到sop的mq队列中
      List<List<EntmiroCustomerInfo>> partition = Lists.partition(entmiroCustomerInfoList,
          org.apache.commons.lang3.StringUtils.isNotEmpty(
              environment.getProperty("sop.customer.size")) ? Integer.parseInt(
              environment.getProperty("sop.customer.size")) : 500);
      for (List<EntmiroCustomerInfo> entmiroCustomerInfos : partition) {
        List<String> collect = entmiroCustomerInfos.stream().map(EntmiroCustomerInfo::getOneId)
            .collect(Collectors.toList());
        ScrmCustomerBatchDTO scrmCustomerDTO = new ScrmCustomerBatchDTO();
        scrmCustomerDTO.setListOneId(collect);
        scrmCustomerDTO.setMerchantId(sopCusSendRequest.getMerchantId());
        scrmCustomerDTO.setConsumer("rpc-scrm-entmicro-container");
        scrmCustomerDTO.setVersion("v1.0.0.1");
        RpcResponse<List<ScrmVehicleBasicInfoDTO>> listVehicle = scrmBigdataUtilRemote.getListVehicleBatch(
            scrmCustomerDTO);
        if (listVehicle.isSuccess()) {
          List<ScrmVehicleBasicInfoDTO> result = listVehicle.getResult();
          setCarNumber(result, entmiroCustomerInfos);
          rabbitProducer.topicSend(RabbitConfig.DATA_REPORT_EXCHANGE_NAME,
              RabbitConfig.DATA_REPORT_TOPIC,
              JSONObject.toJSONString(buildSopCus(entmiroCustomerInfos, sopCusSendRequest)));
        }
      }
    }

  }

  /**
   * 设置车牌号信息
   *
   * @param result
   * @param entmiroCustomerInfos
   */
  private void setCarNumber(List<ScrmVehicleBasicInfoDTO> result,
      List<EntmiroCustomerInfo> entmiroCustomerInfos) {
    entmiroCustomerInfos.forEach(index -> {
      List<ScrmVehicleBasicInfoDTO> collect = result.stream()
          .filter(ind -> ind.getOneid().equals(index.getOneId())).collect(Collectors.toList());
      if (!CollectionUtils.isEmpty(collect)) {
        index.setCarNumber(collect.get(0).getPlateNumber());
      }
    });
  }

  /**
   * 构建推送到sop的参数
   *
   * @param entmiroCustomerInfos 客户信息
   * @return sopCusSendRequest sop信息
   */
  private List<JSONObject> buildSopCus(List<EntmiroCustomerInfo> entmiroCustomerInfos,
      SopCusSendRequest sopCusSendRequest) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return entmiroCustomerInfos.stream().map(index -> {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("customer_name", index.getCustomerName());
      if(StringUtils.isEmpty(index.getCustomerPhone())){
        jsonObject.put("customer_phone", null);
      }else {
        jsonObject.put("customer_phone", index.getCustomerPhone());
      }
      jsonObject.put("wechat_avatar_url", index.getAvatar());
      jsonObject.put("car_number", index.getCarNumber());
      jsonObject.put("scrm_one_id", index.getOneId());
      jsonObject.put("org_user_id", index.getExternalUserId());
      jsonObject.put("user_id", index.getUserId());
      jsonObject.put("id_join", index.getIsJoin());
      jsonObject.put("org_id", sopCusSendRequest.getMerchantId()+"");
      jsonObject.put("sop_journey_id", sopCusSendRequest.getInstId());
      jsonObject.put("sop_journey_stage", sopCusSendRequest.getInstDefalutName());
      jsonObject.put("sop_journey_enter_time", format.format(new Date()));
      jsonObject.put("sop_journey_stage_enter_time", format.format(new Date()));
      jsonObject.put("sop_follow_up_person_name", index.getUserName());
      jsonObject.put("add_way", "scrm");
      return jsonObject;
    }).collect(Collectors.toList());
  }
}