ResultCheckServiceImpl 97.2 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
package com.funde.gras.allot.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.funde.gras.api.utils.*;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.funde.gras.api.common.MyConstant;
import com.funde.gras.api.common.PaasHttpRequest;
import com.funde.gras.api.common.PageInfo;
import com.funde.gras.api.domain.*;
import com.funde.gras.api.service.*;

/**
 * ClassName:  ResultCheckServiceImpl
 * Description:  []
 * Date:  2018年8月3日 下午4:46:39
 *
 * @author ASUS
 */
@Service(version = "1.0.0", timeout = 15000000, interfaceName = "com.funde.gras.api.service.ResultCheckService")
public class ResultCheckServiceImpl implements ResultCheckService {

    private Integer failedCount = 0;

    private final String SUCCESSFUL_FLAG = "1";

    private final String FAILED_FLAG = "2";

    private Integer succesCount = 0;

    @Reference(version = "1.0.0")
    private OracleGrasSysTempService sysTempService;

    @Reference(version = "1.0.0")
    private OracleBranchInfoService branchInfoService;

    @Reference(version = "1.0.0")
    private OracleRuleDealService ruleDealService;

    @Reference(version = "1.0.0")
    private OraclePolicyPremInfoService premInfoService;

    @Reference(version = "1.0.0")
    private OracleGrasAssignBatchRecordService batchRecordService;

    @Reference(version = "1.0.0")
    private OraclePolicyService policyService;

    @Reference(version = "1.0.0")
    private OracleGrasAssignFailedRecordService failedRecordService;

    //@Reference(version = "1.0.0")
    //private FallingMapService mapService;

    @Reference(version = "1.0.0")
    private OracleStaffInfoService staffInfoService;

    @Reference(version = "1.0.0")
    private OracleEmpStatusService oracleEmpStatusService;

    @Reference(version = "1.0.0")
    private OracleGrasSysTempService tempService;

    @Reference(version = "1.0.0")
    private OracleGrasSysDataTransService transService;

    @Reference(version = "1.0.0")
    private OracleRenewalStaffInfoOtherService otherService;

    @Reference(version = "1.0.0")
    private OracleRnServicerInfoService servicerInfoService;

    @Reference(version = "1.0.0")
    private OracleRNPolicyServicerChgRecordService changeService;

    @Reference(version = "1.0.0")
    private OracleLapsePolicy lapsePolicyService;

    @Reference(version = "1.0.0")
    private OraclePolicyProductService policyProductService;

    @Reference(version = "1.0.0")
    private OraclePolicyPremInfoService policyPremInfoService;
    
    @Reference(version = "1.0.0")
    private ElasticSearchService elasticSearchService;
    

    @Autowired
    private PaasHttpRequest paasHttpRequest;

    private LogUtils logUtils = new LogUtils(getClass());



    @Override
    public List<GrasSysTemp> selectByBranchCode(String branchCode) {
        return sysTempService.selectByBranchCode(branchCode);
    }

    /***
     * MethodName:  [queryStaffs]
     * Description:  [分单结果检查查询查询保单服务人员]
     * @param: [branchCode, flag]
     * @return: java.util.List<com.funde.gras.api.domain.StaffInfo>
     */
    @Override
    public PageInfo<StaffInfo> queryStaffs(String branchCode, String channelType, String flag, Integer pageNum, Integer pageSize,String month) {
        Integer total = 0;
        List<StaffInfo> staffs = new ArrayList<>();
        String nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        String nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        //recordList 符合条件的全部的流水号
        List<String> recordList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        List<String> channelTypeList = Arrays.asList(channelType.split(","));
        if (recordList!=null && recordList.size()>0) {
            //已分单业务员 1为前端传输的标记 意为已分单
            if (flag != null && !flag.equals("") && flag.equals(SUCCESSFUL_FLAG)) {
                staffs = sysTempService.queryHavePolicyStaffs(branchCode, channelTypeList, pageNum, pageSize, recordList);
                total = sysTempService.countServicersForPageInfoSuccess(branchCode, channelTypeList, recordList);
                //未分单业务员 2为前端传输的标记 意为未分单
            } else if (flag != null && !flag.equals("") && flag.equals(FAILED_FLAG)) {
                staffs = sysTempService.queryHaveNoPolicyStaffs(branchCode, channelTypeList, pageNum, pageSize, recordList);
                total = sysTempService.countServicersForPageInfoFailed(branchCode, channelTypeList, recordList);
            }
        }
        return new PageInfo<StaffInfo>(pageNum, pageSize, total, staffs);
    }

    /***
     * MethodName:  [queryPolicy]
     * Description:  [方法注释] 
     * @param: [flag, branchCode, channelType, month]
     * @return: java.util.List<com.alibaba.fastjson.JSONObject>
     */
    @Override
    public PageInfo<Map<String,String>> queryPolicy(String flag, String branchCode, String month, Integer pageNum, Integer pageSize, List channelType) {
        String nowMonth = null;
        String nextMonth = null;
        Integer total = 0;
        List<Map<String,String>> resultList = new ArrayList<>();
        if (month != null && !"".equals(month)) {
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);

            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        //recordList 符合条件的全部的流水号
        List<String> recordList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        //查询不到机构对应的分单记录流水号
        if (recordList == null || recordList.size() == 0) {
//            JSONObject noresultJSON = new JSONObject();
            Map<String,String> noresultMap = new HashMap<>();
            noresultMap.put("result", "没有该机构的分单记录");
            resultList.add(noresultMap);
            return new PageInfo<Map<String,String>>(0, pageSize, 0, resultList);
        } else {
            if (flag.equals(SUCCESSFUL_FLAG)) {
                resultList = sysTempService.querySuccesPolicy(recordList,branchCode, pageNum, pageSize, channelType);
                total = sysTempService.countPolicyForPageInfoSuccess(recordList, branchCode,channelType);
            } else if (flag.equals(FAILED_FLAG)) {
                resultList = sysTempService.queryFailedPolicy(recordList, branchCode, pageNum, pageSize, channelType);
                total = sysTempService.countPolicyForPageInfoFailed(recordList, branchCode, channelType);
            }
        }
        return new PageInfo<Map<String,String>>(pageNum, pageSize, total, resultList);
    }

    /***
     * MethodName:  [getCount]
     * Description:  [方法注释]
     * @param: [branchCode, channelType, month]
     * @return: java.util.Map<java.lang.String,java.lang.Integer>
     */
    @Override
    public Map<String, Integer> getCount(String branchCode, String month, List channelType) {
        Map<String, Integer> resultMap = new HashMap<>();
        String nowMonth = null;
        String nextMonth = null;
        if (month != null && !"".equals(month)) {
//            Map<String, String> allotMonth = DateUtil.allotMonth(month);
            //起始日
//            nowMonth = allotMonth.get("nowMonth");
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
            //截止日
//            nextMonth = allotMonth.get("nextMonth");
            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        //分单批次编号组
        List<String> batchRecordsList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        if (batchRecordsList != null && batchRecordsList.size() != 0) {
            failedCount = sysTempService.getCountForFailed(batchRecordsList, channelType);
            succesCount = sysTempService.getCountForSuccess(batchRecordsList, channelType);
        }
        resultMap.put("success", succesCount);
        resultMap.put("failed", failedCount);
        resultMap.put("count", succesCount + failedCount);
        succesCount = 0;
        failedCount = 0;
        return resultMap;
    }

    @Override
    public Map<String, Integer> getCountForManu(String batchSeq) {
        Map<String, Integer> resultMap = new HashMap<>();
        String channelType = null;
        //成功分单总数
        Integer succesCount = sysTempService.getSuccesCount(batchSeq, channelType, null);
        if (succesCount == null) {
            succesCount = 0;
        }
        //失败分单总数
        Integer failedCount = sysTempService.getFailedCount(batchSeq, channelType, null);
        if (succesCount == null) {
            succesCount = 0;
        }
        resultMap.put("success", succesCount);
        resultMap.put("failed", failedCount);
        resultMap.put("count", succesCount + failedCount);
        return resultMap;
    }

    /**
     * 校验保单和服务人员
     * @param condition
     * @param branchCode
     * @param policyList
     * @return
     */
    @Override
    public JSONObject checkPolicAndServicer(String condition,String branchCode, List<JSONObject> policyList){
        List<Map<String,String>> policyFailedList = new ArrayList<>();
        Map<String,String> policyFailedMap = null;
        List<Map<String,String>> policySuccessList = new ArrayList<>();
        Map<String,String> policySuccessMap = null;
        JSONObject resultJson = new JSONObject();
        List<String> policyNoList = new ArrayList<>();
        try {
            //所有能进行分单的保单号
            //传入的EXCEL中错误的保单的信息
            Set<String> failedList = new HashSet<>();
//            List<String> policies = checkPolicyNo(branchCode);

            //以下这个是符合条件的能进行分单的保单号的数组

            //对保单号与续收人员逐一进行核对
            for (JSONObject policyJson : policyList) {
                //保单号
                String policyNo = policyJson.getString("policyNo");
                //服务人员编号
                String servicerNo = policyJson.getString("servicerNo");
                //判断文件不为空
                if (policyList == null || policyList.size() == 0) {
                    resultJson.put("文件不能为空", failedList);
                    return resultJson;
                }
                //产品层的保单信息
                List<PolicyProduct> policyProducts = policyProductService.selectByPolicyNo(policyNo);
                if(policyProducts == null || policyProducts.size() == 0){
                    policyFailedMap = new HashMap<>();
                    policyFailedMap.put("policyNo",policyNo);
                    policyFailedMap.put("servicerNo",servicerNo);
                    policyFailedMap.put("cause","无效的保单号");
                    policyFailedList.add(policyFailedMap);
//                    policyFailedList.add(policyNo+"无效的保单号");
                    failedList.add(policyNo);
                }else {
                    boolean flag = true;
                    //应缴件判定
                    if("1".equals(condition)){
                        //失效件
                    }else if("2".equals(condition)){
                        //失效条件:POS_lapse_policy表中 的lapse_date 到当天不超过两年
                        PosLapsePolicy posLapsePolicy = null;
                        for (PolicyProduct policyProduct : policyProducts) {
                            //保单产品编号
                            Short prodSeq = policyProduct.getProdSeq();
                            posLapsePolicy = lapsePolicyService.selectByPolicyNoAndProSeq(policyNo, prodSeq);
                            if(posLapsePolicy != null){
                                //失效日期
                                Date lapseDate = posLapsePolicy.getLapseDate();
                                //失效原因
                                String lapseReason = policyProduct.getLapseReason();
                                //如果不是符合规则的失效原因,就不予操作
                                boolean contains = MyConstant.LAPSE_POLICIES.contains(lapseReason);
                                if(contains==true){
                                    //日期要在当天到两年内
                                    Date twoYearsLater = DateUtil.getTwoYearsAgo();
                                    //int fromCompare = lapseDate.compareTo(new Date());
                                    int endCompare = lapseDate.compareTo(twoYearsLater);
                                    if(endCompare == -1){
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo",policyNo);
                                        policyFailedMap.put("servicerNo",servicerNo);
                                        policyFailedMap.put("cause","保单失效日期不合要求");
                                        policyFailedList.add(policyFailedMap);
//                                        policyFailedList.add(policyNo + "保单失效日期不合要求");
                                        failedList.add(policyNo);

                                        flag = false;
                                    }
                                }else {
                                    failedList.add(policyNo);
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo",policyNo);
                                    policyFailedMap.put("servicerNo",servicerNo);
                                    policyFailedMap.put("cause","保单渠道不合要求");
                                    policyFailedList.add(policyFailedMap);
//                                    policyFailedList.add(policyNo + "保单渠道不合要求");

                                    flag = false;
                                }
                                break;
                            }
                        }
                        if(posLapsePolicy == null) {
                            failedList.add(policyNo);
                            policyFailedMap = new HashMap<>();
                            policyFailedMap.put("policyNo",policyNo);
                            policyFailedMap.put("servicerNo",servicerNo);
                            policyFailedMap.put("cause","保单不是规定的失效件");
                            policyFailedList.add(policyFailedMap);
//                                policyFailedList.add(policyNo + "保单不是规定的失效件");

                            flag = false;
                        }
                        //缓交件
                    }else if("3".equals(condition)){
                        for (PolicyProduct policyProduct : policyProducts) {
                            //缓交件除了人员信息外的条件是有效状态的长险
                            String productCode = policyProduct.getProductCode();
                            boolean contains = MyConstant.ALL_KIND_PROD.contains(productCode);
                            if(contains == false){
                                failedList.add(policyNo);
                                policyFailedMap = new HashMap<>();
                                policyFailedMap.put("policyNo",policyNo);
                                policyFailedMap.put("servicerNo",servicerNo);
                                policyFailedMap.put("cause","保单不是规定的缓交件");
                                policyFailedList.add(policyFailedMap);
//                                policyFailedList.add(policyNo + "保单不是规定的缓交件");

                                flag = false;
                            }
                        }
                    }
                    //如果保单校验没有问题,执行人员校验
                    if (flag) {
                        //服务人员资质确认
                        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(servicerNo);
                        //人员不存在
                        if (staffInfo == null || "".equals(staffInfo)) {
                            failedList.add(policyNo);
//                    servicerFailedList.add(servicerNo + "人员不存在");
                            policyFailedMap = new HashMap<>();
                            policyFailedMap.put("policyNo", policyNo);
                            policyFailedMap.put("servicerNo", servicerNo);
                            policyFailedMap.put("cause", "人员不存在");
                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                            continue;
                        } else {
                            String empStatusCode = staffInfo.getEmpStatusCode();
                            boolean ifInPosition = empStatusCode.endsWith("01");
                            //人员资质不是在职
                            if (!ifInPosition == true) {
                                failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo + "人员已离职");
                                policyFailedMap = new HashMap<>();
                                policyFailedMap.put("policyNo", policyNo);
                                policyFailedMap.put("servicerNo", servicerNo);
                                policyFailedMap.put("cause", "人员已离职");
                                policyFailedList.add(policyFailedMap);
                                failedCount += 1;
                                continue;
                            }
                        }
                        //保单的渠道
                        String policyChannel = policyService.selectChannelTypeByPolicyNo(policyNo);
                        //人员的渠道
                        String empChannelType = staffInfoService.selectChannelTypeByEmpNp(servicerNo);
                        //保单对应渠道缺失,错误
                        if (policyChannel == null || "".equals(policyChannel)) {
                            failedList.add(policyNo);
//                    policyFailedList.add(policyNo + "无效保单");
                            policyFailedMap = new HashMap<>();
                            policyFailedMap.put("policyNo", policyNo);
                            policyFailedMap.put("servicerNo", servicerNo);
                            policyFailedMap.put("cause", "无效保单");
                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                            continue;
                            //保单为个险渠道
                        } else if (MyConstant.CHANNEL_01.equals(policyChannel)) {
                            //在当前机构不为总共的情况下,个险保单必须与续收人员在同一三级机构下。
                            if (!branchCode.equals("86")) {
                                //员工机构
                                String branchCodeByEmpNo = staffInfoService.getBranchCodeByEmpNo(servicerNo);
                                //保单对应机构
                                String branchCodeByPolicyNo = policyService.selectBranchCodeByPolicyNo(policyNo);
                                BranchInfo empBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByEmpNo);
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByPolicyNo);
                                String empBranchInfoBranchLevel = empBranchInfo.getBranchLevel();
                                String policyBranchInfoBranchLevel = policyBranchInfo.getBranchLevel();
                                //四级机构的处理
                                //员工机构不是三级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(empBranchInfoBranchLevel)) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByEmpNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByEmpNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //保单所属机构不是三级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfoBranchLevel)) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByPolicyNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByPolicyNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //两者不是一个三级机构 不通过
                                if (branchCodeByEmpNo == null || branchCodeByPolicyNo == null || !branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
//                            servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo", policyNo);
                                    policyFailedMap.put("servicerNo", servicerNo);
                                    policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                    policyFailedList.add(policyFailedMap);
                                    failedList.add(policyNo);
                                    continue;
                                } else {
                                    //个险分几种种情况  1.人员也为个险  2.人员不为个险但是 MARKET_FLAG 为Y 取反例即可 3 人员的职务为续收专员、续收主任、个险兼收、银代兼收 这四种
                             
                                        RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
                                        //人员的职务
                                        String position = staffInfo.getPosition();
                                        //是否个险兼收人员标示
//                                assignAbility(servicerFailedList,failedList, policyNo, staffInfoOther, position, servicerNo);
                                        assignAbility(policyFailedList, failedList, policyNo, staffInfoOther, position, servicerNo);
                                    
                                }
                                //总公司
                            } else {
                                //个险分几种种情况  1.人员也为个险  2.人员不为个险但是 MARKET_FLAG 为Y 取反例即可 3 人员的职务为续收专员、续收主任、个险兼收、银代兼收 这四种
                          
                                    RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
                                    //人员的职务
                                    String position = staffInfo.getPosition();
                                    //是否个险兼收人员标示
//                            assignAbility(servicerFailedList,failedList, policyNo, staffInfoOther, position, servicerNo);
                                    assignAbility(policyFailedList, failedList, policyNo, staffInfoOther, position, servicerNo);
                                
                            }
                            //银代
                        } else if (MyConstant.CHANNEL_02.equals(policyChannel)) {
                            //不是总公司
                            if (!branchCode.equals("86")) {
                                //银代保单必须与续收人员在同一三级机构下。银代(仅指保单机构为二级机构的保单)
                                String branchCodeByEmpNo = staffInfoService.getBranchCodeByEmpNo(servicerNo);
                                //人员所属的上级
                                String parentBranchByEmpNo = policyService.selectParentBranchByEmpNo(servicerNo);
                                //保单所属上级公司
                                String branchCodeByPolicyNo = policyService.selectBranchCodeByPolicyNo(policyNo);
                                //人员所属上级公司
                                String policyParentBranch = policyService.selectParentBranchByPolicyNo(policyNo);

                                //保单所属机构信息
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByPolicyNo);
                                //保单属于四级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByPolicyNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByPolicyNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //人员所属机构信息
                                BranchInfo empBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByEmpNo);
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(empBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByEmpNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByEmpNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //保单上级公司是总公司 本级机构就是二级机构
                                if (policyParentBranch != null && policyParentBranch.length() == 2) {
                                    //人员也是二级机构的人员
                                    if (parentBranchByEmpNo != null && parentBranchByEmpNo.length() == 2) {
                                        //两者不是一样的
                                        if (!branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
                                            failedList.add(policyNo);
//                                    servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                            policyFailedMap = new HashMap<>();
                                            policyFailedMap.put("policyNo", policyNo);
                                            policyFailedMap.put("servicerNo", servicerNo);
                                            policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                            policyFailedList.add(policyFailedMap);
                                            continue;
                                        }
                                        //人员的上级机构就是二级机构
                                    } else if (parentBranchByEmpNo != null && parentBranchByEmpNo.length() == 4) {
                                        if (!branchCodeByEmpNo.equals(parentBranchByEmpNo)) {
                                            failedList.add(policyNo);
//                                    servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                            policyFailedMap = new HashMap<>();
                                            policyFailedMap.put("policyNo", policyNo);
                                            policyFailedMap.put("servicerNo", servicerNo);
                                            policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                            policyFailedList.add(policyFailedMap);
                                            continue;
                                        }
                                    }
                                    //三级机构保单
                                } else {
                                    //两者不是一个机构 不通过
                                    if (branchCodeByEmpNo == null || branchCodeByPolicyNo == null || !branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
                                        failedList.add(policyNo);
//                                servicerFailedList.add(servicerNo+ "人员无权操作此保单(跨机构)");
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo", policyNo);
                                        policyFailedMap.put("servicerNo", servicerNo);
                                        policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                        policyFailedList.add(policyFailedMap);
                                        continue;
                                    } else {
                                        verifyBankChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                                    }
                                }
                                //总公司
                            } else {
                                verifyBankChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                            }
                            //经代
                        } else if (MyConstant.CHANNEL_03.equals(policyChannel)) {
                            //不是总公司
                            if (!branchCode.equals("86")) {
                                //经代必须与续收人员在同一二级机构下。
                                String serviceBranch = policyService.selectParentBranchByEmpNo(servicerNo);
                                //服务人员所属机构信息
                                BranchInfo servicerBranchInfo = branchInfoService.selectByPrimaryKey(serviceBranch);
                                //保单机构
                                String policyBranch = policyService.selectParentBranchByPolicyNo(policyNo);
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(policyBranch);
                                //保单属于四级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", policyBranch);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    policyBranch = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //人员所属机构信息
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(servicerBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", serviceBranch);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    serviceBranch = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //上级公司是总公司 当前公司就是二级公司
                                if (policyBranch.length() == 2) {
                                    policyBranch = policyService.selectBranchCodeByPolicyNo(policyNo);
                                }
                                //两者的二级公司不一样
                                if (serviceBranch == null || policyBranch == null || !serviceBranch.equals(policyBranch)) {
                                    failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo", policyNo);
                                    policyFailedMap.put("servicerNo", servicerNo);
                                    policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                    policyFailedList.add(policyFailedMap);
                                } else {
                                    veryfyEcoChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                                }
                                //总公司无视分公司权限
                            } else {
                                veryfyEcoChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                            }

                            //收展
                        } else if (MyConstant.CHANNEL_07.equals(policyChannel)) {
                            if (!branchCode.equals("86")) {
                                //收展保单必须与续收人员在同一三级机构下。
                                String branchCodeByEmpNo = staffInfoService.getBranchCodeByEmpNo(servicerNo);
                                String branchCodeByPolicyNo = policyService.selectBranchCodeByPolicyNo(policyNo);
                                //人员机构信息
                                BranchInfo empBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByEmpNo);
                                //保单机构信息
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByPolicyNo);
                                //保单属于四级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByPolicyNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByPolicyNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //人员所属机构信息
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(empBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", empBranchInfo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByEmpNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //收展保单如保单业务员在职,则不允许调整给其它人。
                                RNPolicyServiceInfo rnPolicyServiceInfo = servicerInfoService.selectByPolicyNo(policyNo);
                                String agentNo = rnPolicyServiceInfo.getAgentNo();
                                StaffInfo staff = staffInfoService.selectByPrimaryKey(agentNo);
                                //在职
                                if (staff!=null && staff.getEmpStatusCode().endsWith("01")) {
                                    //两者不同
                                    if (!agentNo.equals(servicerNo)) {
                                        failedList.add(policyNo);
//                                servicerFailedList.add(servicerNo+ "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo", policyNo);
                                        policyFailedMap.put("servicerNo", servicerNo);
                                        policyFailedMap.put("cause", "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedList.add(policyFailedMap);
                                    }
                                }
                                //两者不是一个机构 不通过
                                if (branchCodeByEmpNo == null || branchCodeByPolicyNo == null || !branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
                                    failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo+ "人员无权操作此保单(跨机构)");
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo", policyNo);
                                    policyFailedMap.put("servicerNo", servicerNo);
                                    policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                    policyFailedList.add(policyFailedMap);
                                } else {
                                    verifyShouzhanChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                                }
                                //总公司
                            } else {
                                //收展保单如保单业务员在职,则不允许调整给其它人。
                                RNPolicyServiceInfo rnPolicyServiceInfo = servicerInfoService.selectByPolicyNo(policyNo);
                                String agentNo = rnPolicyServiceInfo.getAgentNo();
                                StaffInfo staff = staffInfoService.selectByPrimaryKey(agentNo);
                                //在职
                                if (staff!=null && staff.getEmpStatusCode().endsWith("01")) {
                                    //两者不同
                                    if (!agentNo.equals(servicerNo)) {
                                        failedList.add(policyNo);
//                                servicerFailedList.add(servicerNo+ "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo", policyNo);
                                        policyFailedMap.put("servicerNo", servicerNo);
                                        policyFailedMap.put("cause", "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedList.add(policyFailedMap);
                                    }
                                }
                                verifyShouzhanChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                            }

                        }
                    }
                }
                policyNoList.add(policyNo);
            }
            policyNoList.removeAll(failedList);

            //处理保单人员离职交接
            policySuccessList=quitAssign(policyNoList,policyList,policyFailedList,failedList);
            policyNoList.removeAll(failedList);


            resultJson.put("policyFailed", policyFailedList);
            resultJson.put("policySuccess",policySuccessList);
            resultJson.put("failedPolicyNo",failedList);
            resultJson.put("successPolicyNo",policyNoList);
            resultJson.put("failed", failedList.size());
            resultJson.put("total", policyList.size());
            resultJson.put("success", policyList.size() - failedList.size());

        }catch (Exception e){
            logUtils.error(e);
        }
        return resultJson;
    }

    /***
     * MethodName:  [adjustFailedPolicy]
     * Description:  根据传入的excel进行保单人员指定
     * @param: [policyList]
     * @return: java.util.Map<java.lang.String,java.lang.Integer>
     */
    @Override
    public JSONObject adjustFailedPolicy(String condition,String branchCode, List<JSONObject> policyList,String user) {

        JSONObject resultJson = new JSONObject();
        try {
            //校验保单和人员
            resultJson = checkPolicAndServicer(condition,branchCode,policyList);
            //校验成功的保单将存到gras_sys_temp表中
            if (resultJson.containsKey("successPolicyNo")){
                //获取校验成功保单号
                List<String> policyNoList = (List<String> )resultJson.get("successPolicyNo");
                //往成功表中添加这些数据
                List<GrasSysTemp> sysTempList = new ArrayList<>();
                List<Map<String,String>> successList = new ArrayList<>();
                //在分单失败表中删除调传入的保单号
                if (policyNoList != null && policyNoList.size() != 0) {
//                    String batchSeq = NumberUtil.random10();
//                    String batchCode = NumberUtil.random4();
                    //向批次申请中添加一个信息
//                GrasAssignBatchRecord batchRecord = new GrasAssignBatchRecord(batchSeq,"N",NumberUtil.random10(),MyConstant.SYS_USER,new Date(),MyConstant.SYS_USER,new Date());
                    for (String policyNo : policyNoList) {
                        //封装参数用于数据库操作
                        //传入的值并不会很多(最多1000个)
                        String servicerNo = "";
                        for (JSONObject inJSON : policyList) {
                            String inPolicyNo = inJSON.getString("policyNo");
                            //找到对应的服务人员
                            if (inPolicyNo != null && !"".equals(inPolicyNo) && inPolicyNo.equals(policyNo)) {
                                servicerNo = inJSON.getString("servicerNo");
                                Map<String,String> itemSuccessMap = new HashMap<>();
                                itemSuccessMap.put("policyNo",policyNo);
                                itemSuccessMap.put("servicerNo",servicerNo);
                                successList.add(itemSuccessMap);
                                break;
                            }
                        }
                        //根据保单号查询保单缴费信息,获得应缴月
                        PolicyPremInfo policyPremInfo = policyPremInfoService.selectByPolicyNo(policyNo);
                        if (policyPremInfo != null) {
                            String dateMonth = policyPremInfo.getPremDueDate();
                            dateMonth = dateMonth.substring(0,7);
                            //根据机构号和应缴月查询分单批次申请,获得流水号
                            GrasAssignBatchRecord grasAssignBatchRecord = batchRecordService.selectBatchRecord(branchCode, dateMonth);
                            if (grasAssignBatchRecord != null) {
                                GrasSysTemp temp = new GrasSysTemp(policyNo, branchCode, servicerNo, MyConstant.ASSIGN_RULE_11, grasAssignBatchRecord.getBatchSeq(),user);
                                temp.setServicerNo(servicerNo);
                                sysTempList.add(temp);
                            }
                        }
                    }
                    //往成功表中添加这些数据 并向批次表中添加数据
                    try {
                        if (sysTempList != null && sysTempList.size() != 0) {
//                        batchRecord.setBranchCode(branchCode);
//                        Date dueMonthDate = DateUtil.getDateFormat(DateUtil.getPerFirstDayOfDate(dueMonth,DateUtil.DATE_DEFAULT_FORMAT));
//                        batchRecord.setDueMonth(dueMonthDate);
//                        batchRecord.setBatchCode(NumberUtil.random4());
//                        batchRecordService.insertBatchRecord(batchRecord);
                            for (List mergeSuccessList : subListPolicyList(sysTempList)) {
                                sysTempService.insertOrUpdateBatch(mergeSuccessList);
                            }
                        }
                        //在失败表中删除这些数据
                        if (policyNoList != null && policyNoList.size() != 0) {
                            for (List listForDelete : subListPolicyList(policyNoList)) {
//                            failedRecordService.deleteList(listForDelete);
                                failedRecordService.updateList("N",listForDelete);
                            }
                        }
                    } catch (Exception e) {
                        resultJson.put("内部错误", e.getMessage());
                        return resultJson;
                    }
                }

                failedCount = 0;
                succesCount = 0;
            }

            return resultJson;
        } catch (Exception e) {
            logUtils.error(e);
            resultJson.put("错误信息:", e.getMessage());
            failedCount = 0;
            succesCount = 0;
            return resultJson;
        }

    }



    /**
     * MethodName:  quitAssign
     * Description:  [保单离职交接规则]
     * @param policyNoList
     * @param policyList
     * @return  String
     *
     * @author  Mamba
     * @date  2019年1月8日 下午2:26:28
     */
    private List<Map<String, String>> quitAssign(List<String> policyNoList, List<JSONObject> policyList, List<Map<String,String>> policyFailedList,Set<String> failedList)
    {
        //key:应缴日(1812)年份加月份   value{现服务人员代码,服务人员代码}
        Map<String, Map> map = new HashMap<String, Map>();
        //{现服务人员代码,服务人员代码}
        Map<String, String> policyMap = new HashMap<String, String>();
        //最后符合条件的保单信息
        List<Map<String, String>> policySuccessList = new ArrayList<>();
        Map<String, String> policySuccessMap = null;
        Date nowDate = new Date();
        //获取当前年份
        int nowYear = DateUtil.getYear(nowDate);
        int nowMonth = DateUtil.getMonth(nowDate);
        Map<String,String> paramMap=new HashMap<String,String>();
      //错误信息
        Map<String,String> policyFailedMap = null;

        for (String item : policyNoList)
        {
            for (JSONObject policyJson : policyList)
            {
                String policyNo = policyJson.getString("policyNo");
                String servicerNo = policyJson.getString("servicerNo");
                try
                {
                    if (item.equals(policyNo))
                    {
                        policySuccessMap = new HashMap<>();
                        /**
                         * 处理离职交接规则
                         */
                        //根据保单号从数据库取现服务人员
                        RNPolicyServiceInfo rnPolicyServiceInfo = servicerInfoService.selectByPolicyNo(policyNo);
                        StaffInfo staffInfo = null;
                        if (rnPolicyServiceInfo != null)
                        {
                            staffInfo = staffInfoService.selectByPrimaryKey(rnPolicyServiceInfo.getServiceNo());
                        }
                        int month = 0;
                        int year = 0;
                        if (staffInfo != null && staffInfo.getLeaveDate() != null)
                        {
                            Date leaveDate = DateUtil.formatDate(staffInfo.getLeaveDate(), "yyyy-MM-dd");
                            month = DateUtil.getMonth(leaveDate);
                            year = DateUtil.getYear(leaveDate);
                        }
                        //1:先判断该保单的现服务人员是否在当月或者上月离职    人员离职时间:STAFF_INFO.LEAVE_DATE
                        if (quitTime(nowYear, nowMonth, year, month))
                        {

                            //3.离职人员名下未收件交接遵循“应缴月为同一个月份的保单只能交接给同一个人,不允许分别交接给多个人员”;未收件:保单缴费状态为1的时候为未收件,即POLICY_PREM_INFO.PREM_STATUS=1
                            //例如:A人员当月离职,他12月名下有3笔保单,分别为1,2,3,分别会出现两种情况,1:A人员应缴日在12月的保单从未有过交接记录     2:A人员应缴日在12月的保单存在交接记录
                            //情况1:上传文件中,把1,2,3分别分配给B,C,D,文件格式如下:

                            //数据库获取保单应缴日,得到应缴月
                            PolicyPremInfo policyPremInfo = premInfoService.selectByPolicyNo(policyNo);
                            Date premDueDate = DateUtil.formatDate(policyPremInfo.getPremDueDate(), "yyyy-MM-dd");
                            int premDueMonth = DateUtil.getMonth(premDueDate);
                            int premDueYear = DateUtil.getYear(premDueDate);
                            //校验考核期
                            if(checkAssessmentPeriod(premDueYear,premDueMonth)){
                                //那么这种情况,1先分给了B,那根据规则同一月保单只能分配给同一人,那么2,3保单就只能B
                                //校验如下,校验保单交出服务人员是否和该保单现服务人员相同,若不相同则没有发生保单离职交接记录
                                //注:数据库获取保单服务人员交接记录表,该保单最近一次交接记录,获取交出服务人员字段   RN_POLICY_SERVICER_CHG_RECORD.EARLIER_AGENT
                                String startMonths = DateUtil.getPerFirstDayOfDate(policyPremInfo.getPremDueDate(), DateUtil.DATETIME_DEFAULT_FORMAT);
                                String endMonth = DateUtil.getPerLastDayOfDate(policyPremInfo.getPremDueDate(), DateUtil.DATETIME_DEFAULT_FORMAT);
    
                                paramMap.put("sreceiveNo", rnPolicyServiceInfo.getServiceNo());
                                paramMap.put("startMonths", startMonths);
                                paramMap.put("endMonth", endMonth);
                                RNPolicyServicerChgRecord record = changeService.queryLastTimeServicerChg(paramMap);
                                /**保       原         接收
                                 * p1  H1  H2
                                 * p2  H1  H3
                                 */
    
                                //交出服务人员代码
                                String outSer = null;
                                //接收服务人员代码
                                String receiveSer = null;
    
                                //现服务人员代码
                                String nowServicerNo = rnPolicyServiceInfo.getServiceNo();
    
                                if (record == null
                                        || DateUtil.compareToDate(staffInfo.getLeaveDate(),
                                        DateUtil.getDateFormat(record.getChangeDate())) != -1)
                                {
    
                                    //情况一:没有记录,或者离职时间大于调整时间(离职之前交接的保单)      小于根据应缴月从map中取值(应缴月值应该每次去查保单的应缴日),从值中取该保单号的现服务人员,
    
                                    Map<String, String> m = map.get(String.valueOf(premDueYear)
                                            + String.valueOf(premDueMonth));
                                    //现服务人员代码
                                    String nowServicer = null;
                                    //准备交接的服务人员代码
                                    String servicer = null;
                                    /**
                                     * map  H1:H2
                                     */
                                    if(m!=null){
                                        for (Map.Entry<String, String> s : m.entrySet())
                                        {
                                            if (s.getKey().equals(nowServicerNo))//H1==1
                                            {
                                                nowServicer = s.getKey();
                                                servicer = s.getValue();//H2
                                            }
    
                                        }
                                    }
                                    //情况1:如果没值,那就符合条件
                                    //情况2:如果有值,根据同月只能分配给同一人员原则,比较收服务人员与上个接收服务人员是否相同为同一人
                                    if (nowServicer != null && !servicerNo.equals(servicer))
                                    {
                                            failedList.add(policyNo);
                                            policyFailedMap = new HashMap<>();
                                            policyFailedMap.put("policyNo", policyNo);
                                            policyFailedMap.put("servicerNo", servicerNo);
                                            policyFailedMap.put("cause", "离职人员下同一应缴月下的保单只能分配给一个人");
                                            policyFailedList.add(policyFailedMap);
                                            break;
                                    }
    
                                }
                                else
                                {
                                    
                                      //情况二:若保单交出服务人员和该保单现服务人员相同,则说明之前有发生过保单离职交接,那根据一个月中只能分给同一个服务人员原则,那只能分配给接收服务人员
                                      //处理脏数据 NextAgent离职      --通过,可以调整      NextAgent 未离职   --保持原服务人员,不可以调整
                                      //如果离职后调整的服务人员也处于离职状态的话,则允许此次操作
                                      StaffInfo staffInfo1 = staffInfoService.selectByPrimaryKey(record.getNextAgent());
                                      //若是离职,则不可调整 break
                                      if(staffInfo1 != null && staffInfo1.getLeaveDate() != null){
                                          failedList.add(policyNo);
                                         
                                          policyFailedMap = new HashMap<>();
                                          policyFailedMap.put("policyNo", policyNo);
                                          policyFailedMap.put("servicerNo", servicerNo);
                                          policyFailedMap.put("cause", "离职人员下同一应缴月下的保单只能分配给一个人");
                                          policyFailedList.add(policyFailedMap);
                                          break;
                                      }
                                }
                                policyMap.put(nowServicerNo, servicerNo);
                                map.put(String.valueOf(premDueYear) + String.valueOf(premDueMonth), policyMap);
                            }  
                        }
                            
                            
                        /**
                         * end
                         */

                        policySuccessMap.put("policyNo", policyNo);
                        policySuccessMap.put("servicerNo", servicerNo);
                        policySuccessList.add(policySuccessMap);
                        break;
                    }
                }

                catch (Exception e)
                {
                    e.printStackTrace();
                    policySuccessMap.put("policyNo", policyNo);
                    policySuccessMap.put("servicerNo", servicerNo);
                    policySuccessList.add(policySuccessMap);
                    break;
                }
            }
        }
        return policySuccessList;

    }
    /**
     * 
     * MethodName:  checkAssessmentPeriod
     * Description:  [校验考核期]  
     *@param premDueYear
     *@param premDueMonth
     *@return  boolean
     * 
     * @author  Mamba
     * @date  2019年5月5日 下午5:33:23
     */
    private boolean checkAssessmentPeriod(int premDueYear, int premDueMonth)
    {
        //例如:当前5月份操作离职交接时,只对应缴月在3月、4月、5月的保单进行规则校验
        Date nowDate=DateUtil.getNowDate();
        int nowYear=DateUtil.getYear(nowDate);
        int nowMonth=DateUtil.getMonth(nowDate);
        
        //最小月
        Date earliestDate=DateUtil.getDateMonthFormat(DateUtil.getDateMonthFormat(DateUtil.getFirstMonth(3)));
        int earliestYear=DateUtil.getYear(earliestDate);
        int earliestMonth=DateUtil.getMonth(earliestDate);
        
        //同年 当前:2019-4  最小月:2019-1 应缴月:2019-3
        if(earliestYear==nowYear){
            //同年 : 小于等于当前月   &&  大于最小月 --3月小于5月,大于2月
            if(nowYear==premDueYear && premDueMonth<=nowMonth && premDueMonth>earliestMonth){
                return true;
            }
        }
        //不同年
        if(earliestYear<nowYear){
            //当前:2019-3  最小月:2018-12  应缴月:2019-3
            //应缴月与当前时间同年  && 应缴月小于等于当前月
            if(nowYear==premDueYear && premDueMonth<=nowMonth){
                return true;
            }
            //应缴月与最小月同年  && 应缴月大于最小月
            if(nowYear==earliestYear && premDueMonth>earliestMonth){
                return true;
            }
        }
        return false;
    }

    private boolean quitTime(int nowYear, int nowMonth, int year, int month)
    {
        //同年--当月&上月
        if (nowYear == year && (nowMonth == month || nowMonth == (month - 1)))
        {
            return true;
        }

        //去年  ---上月
        if ((nowYear - year) == 1 && month == 12)
        {
            return true;
        }

        return false;
    }


    private void verifyShouzhanChannel(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, String servicerNo, StaffInfo staffInfo, String empChannelType) {
        //收展分几种种情况  1.人员也为收展  2.人员不为收展但是 shouzhanflag? 为Y 取反例即可 3 人员的职务为个险收展专员、银代收展专员、收展主任、个险兼收、银代兼收 这四种
        if (!MyConstant.CHANNEL_07.equals(empChannelType)) {
            RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
            //人员的职务
            String position = staffInfo.getPosition();
            assignAbility(policyFailedList,failedList, policyNo, staffInfoOther, position, servicerNo);
        }
    }

    private void veryfyEcoChannel(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, String servicerNo, StaffInfo staffInfo, String empChannelType) {
        Map<String,String> policyFailedMap = new HashMap<>();
        policyFailedMap.put("policyNo",policyNo);
        policyFailedMap.put("servicerNo",servicerNo);
        policyFailedMap.put("cause","人员无权操作此保单(不能负责该渠道)");

        //经代分几种种情况  1.人员也为经代  2.人员不为经代但是 agentFlag 为Y 取反例即可 3 人员的职务为银代督导、续收主任、个险兼收、银代兼收 这四种
        if (!MyConstant.CHANNEL_03.equals(empChannelType)) {
            RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
            //人员的职务
            String position = staffInfo.getPosition();
            if (staffInfoOther != null) {
                //个险兼收人员标示
                String marketFlag = staffInfoOther.getMarketFlag();
                //经代兼收标示
                String agentFlag = staffInfoOther.getAgentFlag();
                //银代兼收标示
                String bankFlag = staffInfoOther.getBankFlag();
                //不是兼收人员
                //续收专员、续收主任、个险兼收、银代兼收 这四种都可以分经代的单子
                if ((!"Y".equals(marketFlag)) && (!"Y".equals(bankFlag)) && (!"Y".equals(agentFlag))) {
                    if (position != null && !"".equals(position)) {
                        //续收专员、银代收展专员、续收主任
                        if (!MyConstant.BANK_AGENT_SERVICER.equals(position) && !MyConstant.PERSONAL_INSURANCE_SERVICER.equals(position) && !MyConstant.CD_DIRECTOR.equals(position)) {
                            failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                        }
                    } else {
                        failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                        policyFailedList.add(policyFailedMap);
                        failedCount += 1;
                    }
                }
            } else {
                failedList.add(policyNo);
//                servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                policyFailedList.add(policyFailedMap);
                failedCount += 1;
            }
        }
    }

    private void verifyBankChannel(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, String servicerNo, StaffInfo staffInfo, String empChannelType) {
        Map<String,String> policyFailedMap = new HashMap<>();
        policyFailedMap.put("policyNo",policyNo);
        policyFailedMap.put("servicerNo",servicerNo);
        policyFailedMap.put("cause","人员无权操作此保单(不能负责该渠道)");
        //银代分几种种情况  1.人员也为银代  2.人员不为银代但是 bank——flag 为Y 取反例即可 3 人员的职务为银代督导、续收主任、个险兼收、银代兼收 这四种
        if (!MyConstant.CHANNEL_02.equals(empChannelType)) {
            RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
            //人员的职务
            String position = staffInfo.getPosition();
            //是否银代兼收人员标示
            if (staffInfoOther != null) {
                String marketFlag = staffInfoOther.getMarketFlag();
                //银代兼收标示
                String bankFlag = staffInfoOther.getBankFlag();
                //不是兼收人员
                if ((!"Y".equals(marketFlag)) && (!"Y".equals(bankFlag))) {
                    if (position != null && !"".equals(position)) {
                        //银代督导、续收主任、个险兼收、银代兼收 这四种都可以分银代的单子
                        //续收专员、银代收展专员
                        if (!MyConstant.BANK_AGENT_SERVICER.equals(position) && !MyConstant.CD_DIRECTOR.equals(position)) {
                            failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");

                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                        }
                    } else {
                        failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo + "人员无权操作此保单(不能负责该渠道)");
                        policyFailedList.add(policyFailedMap);
                        failedCount += 1;
                    }
                }
            } else {
                failedList.add(policyNo);
//                servicerFailedList.add(servicerNo);
                policyFailedList.add(policyFailedMap);
                failedCount += 1;
            }
        }
    }

    private void assignAbility(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, RenewalStaffInfoOther staffInfoOther, String position, String servicerNo) {
        Map<String,String> policyFailedMap = new HashMap<>();
        policyFailedMap.put("policyNo",policyNo);
        policyFailedMap.put("servicerNo",servicerNo);
        policyFailedMap.put("cause","人员无权操作此保单(不能负责该渠道)");
        if (staffInfoOther != null) {
            //个险兼收人员标示
            String marketFlag = staffInfoOther.getMarketFlag();
            //银代兼收标示
            String bankFlag = staffInfoOther.getBankFlag();
            //不是兼收人员
            //个险收展专员、收展主任、个险兼收、银代兼收 这四种都可以分收展的单子
            if ((!"Y".equals(marketFlag)) && (!"Y".equals(bankFlag))) {
                if (position != null && !"".equals(position)) {
                    //续收专员、银代收展专员、续收主任
                    if (!MyConstant.PERSONAL_INSURANCE_SERVICER.equals(position) && !MyConstant.CD_DIRECTOR.equals(position)) {
                        failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo + "人员无权操作此保单(不能负责该渠道)");

                        policyFailedList.add(policyFailedMap);
                        failedCount += 1;
                    }
                } else {
                    failedList.add(policyNo);
//                    servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                    policyFailedList.add(policyFailedMap);
                    failedCount += 1;
                }
            }
        } else {
            failedList.add(policyNo);
//            servicerFailedList.add(servicerNo + "人员无权操作此保单(不能负责该渠道)");
            policyFailedList.add(policyFailedMap);
            failedCount += 1;
        }
    }

    /**
     * 根据保单号查询到能服务该保单的人员
     *
     * @param policyNo
     * @return
     */
    @Override
    public List<StaffInfo> getEmpsByBranchCodeAndchannelType(String policyNo) {
        //保单所属机构号
        String branchCode = policyService.selectBranchCodeByPolicyNo(policyNo);
        //保单渠道
        String channelType = policyService.selectChannelTypeByPolicyNo(policyNo);
        //结果集
        List resultList = new ArrayList();
        //机构信息
        BranchInfo branchInfo = branchInfoService.selectByPrimaryKey(branchCode);
        //机构级别
        String branchLevel = branchInfo.getBranchLevel();
        //如果保单是四级机构,那就找他对应的三级机构
        if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(branchLevel)) {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("branchCode", branchCode);
            paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
            branchCode = ruleDealService.queryBranchCodeByLevel(paramMap);
        }
        //保单对应的机构下所有符合条件的人员
        List<StaffInfo> empsByBranchCodeAndchannelType = staffInfoService.getEmpsByBranchCodeAndchannelType(branchCode);
        for (StaffInfo staffInfo : empsByBranchCodeAndchannelType) {
            String empNo = staffInfo.getEmpNo();
            //人员能服务的渠道
            Set<String> checkChannelTypes = checkChannelTypes(empNo);
            //人员服务的渠道包含了保单的渠道
            if (checkChannelTypes.contains(channelType)) {
                resultList.add(staffInfo);
            }
        }
        return resultList;
    }

    /**
     * 回写核心数据库的操作
     * @param user
     * @param policyServicerList
     * @param assginRule
     * @return
     */
    @Override
    public JSONObject resultBackRN(String user,List<Map<String,String>> policyServicerList,String assginRule){
        JSONObject resultJson = new JSONObject();
        String transFlag = "传输异常";
        String reason = "";
        List<RNPolicyServicerChgRecord> RNPSCRList=new ArrayList<RNPolicyServicerChgRecord>();
        try{
            List<String> policys = new ArrayList<>();
            JSONArray paramArray = new JSONArray();
            for (Map<String, String> item : policyServicerList) {
                String policyNo = item.get("policyNo");
                String servicerNo = item.get("servicerNo");
                //用于存放给核心系统传输数据的
                JSONObject dataJSON = new JSONObject(){{
                    put("policyNo", policyNo);
                    put("servicerNo", servicerNo);
                    put("orphanMark", "0");
                    put("assignRule", assginRule);
                    put("lastAssignUser", user);
                    put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                }};
                //保单交接记录
                setPolicyServicerChgRecord(policyNo,servicerNo,assginRule,user,RNPSCRList);
                paramArray.add(dataJSON);
                policys.add(policyNo);
            }
            //向核心系统传数据
            logUtils.info("核心系统回写...时间:" + new Date() + "向核心系统传入的参数为:" + paramArray);
            //此处要求是按3000条进行传输一次
            List<JSONArray> jsonArrays = submit3000Datas(paramArray, 3000);
            //传输失败的保单数组
            List<String> failedPolicyNos = new ArrayList<>();
            //传输记录 用于记录
            List<GrasSysDataTrans> transList = new ArrayList<>();
            //分批传输
            for (JSONArray pageDatas : jsonArrays) {
                //每次传输的结果
                JSONObject everyTimeSyncResult = AllotResultsBack.syncPolicyRule(pageDatas);
                logUtils.info(new Date() + "本次回写结果:" + everyTimeSyncResult);
                //传输成功与否的标示
                String flag = everyTimeSyncResult.getString("flag");
                //接口返回的传输失败的保单
                JSONArray failedPolicys = everyTimeSyncResult.getJSONArray("policyNos");
                if("0".equals(flag)){
                    //失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = failedPolicy.getString(policyNo);
                                failedPolicyNos.add(policyNo);
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                    //传输成功
                    transFlag = "传输成功";
                }else {
                    transFlag = "传输失败";
                    //传输失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = "";
                                failedPolicyNos.add(policyNo);
                                //接口返回的结果 可能长度很长不符合数据库规范
                                if (failedPolicy.getString(policyNo).length() >= 200) {
                                    failedReason = failedPolicy.getString(policyNo).substring(0, 199);
                                } else {
                                    failedReason = failedPolicy.getString(policyNo);
                                }
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                }
            }
            //传输成功的保单的处理 移除失败的就是成功的
            policys.removeAll(failedPolicyNos);
            if (policys != null && policys.size() != 0) {
                for (String policyNo : policys) {
                    GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"Y","Y","传输成功",user,user);
                    transList.add(transData);
                }
            }
            //写入到数据库
            if (transList != null && transList.size() != 0) {
                for (List mergeList : subListPolicyList(transList)) {
                    transService.mergeDataTransList(mergeList);
                }
            }
            //报存保单交接记录
           /* for (RNPolicyServicerChgRecord policyServicer : RNPSCRList)
            {
                if(policys.contains(policyServicer.getPolicyNo())){
                    changeService.insert(policyServicer);
                }
            }*/
            //更新es
            JSONObject jsonObject=new JSONObject();
            List<JSONObject> policyNolist=new ArrayList<JSONObject>();
            for (Object object : paramArray)
            {
                jsonObject=(JSONObject)object;
                for(String policyNo:policys){
                    if(policyNo.equals(jsonObject.get("policyNo"))){
                        String servicerNo=(String) jsonObject.get("servicerNo");
                        StaffInfo staffInfo=staffInfoService.selectByPrimaryKey(servicerNo);
                        if(staffInfo!=null){
                            jsonObject.put("empName", staffInfo.getEmpName());
                            policyNolist.add(jsonObject);
                        }
                       break; 
                    }
                }
            }
            elasticSearchService.updateAssignPolicyInfo(policyNolist);
            
            
        }catch (Exception e){
            logUtils.error(e);
        }
        return resultJson;
    }


    /**
     * MethodName:  setPolicyServicerChgRecord
     * Description:  [设置保单服务人员交接记录信息]  
     *@param policyNo
     *@param servicerNo
     *@param assginRule
     *@param user  void
     * 
     * @author  Mamba
     * @date  2019年2月18日 上午10:58:55
     */
    private void setPolicyServicerChgRecord(String policyNo, String servicerNo, String assginRule, String user,List<RNPolicyServicerChgRecord> RNPSCRList)
    {
        Date nowTime=new Date();
        //交出服务人员--原服务人员
        String earlierAgent=null;
        RNPolicyServiceInfo policyServiceInfo=servicerInfoService.selectByPolicyNo(policyNo);
        if(policyServiceInfo!=null){
            earlierAgent=policyServiceInfo.getServiceNo();
        }
        PolicyPremInfo policyPremInfo=premInfoService.selectByPolicyNo(policyNo);
        Date premDueDate=null; 
        if(policyPremInfo!=null){
            premDueDate= DateUtil.getDateFormat(policyPremInfo.getPremDueDate());
        }
        String branchCode=policyService.selectBranchCodeByPolicyNo(policyNo);
        
        RNPolicyServicerChgRecord policyServicer=new RNPolicyServicerChgRecord();
        policyServicer.setChangeSeq(NumberUtil.random20());
        policyServicer.setPolicyNo(policyNo);
        policyServicer.setBranchCode(branchCode);
        policyServicer.setEarlierAgent(earlierAgent);
        policyServicer.setNextAgent(servicerNo);
        policyServicer.setChangeDate(nowTime);
        //均为业务员
        policyServicer.setChangeMode("0");
        policyServicer.setPremDueDate(premDueDate);
        policyServicer.setCreatedUser(user);
        policyServicer.setCreatedDate(nowTime);
        policyServicer.setUpdatedUser(user);
        policyServicer.setUpdatedDate(nowTime);
        policyServicer.setPkSerial(NumberUtil.random20());
        //policyServicer.setAssignPolicyType(assginRule);
        RNPSCRList.add(policyServicer);
    }

    /**
     * 回写核心数据库的操作
     *
     * @param user    当前用户
     * @param policys 保单号数组
     * @return
     */
    @Override
    public JSONObject resultBack(String user, List<String> policys) {
        JSONObject resultJson = new JSONObject();
        String transFlag = "传输异常";
        String reason = "";
        List<RNPolicyServicerChgRecord> RNPSCRList=new ArrayList<RNPolicyServicerChgRecord>();
        //创建向接口传输数据的数组
        try {
            JSONArray paramArray = new JSONArray();
            //需要传输的参数有,policyNo,servicerNo,orphanMark,assignRule,lastAssignUser,lastAssignDate
            //查询到保单号对应的待分单的保单对应的服务人员等信息
            List<GrasSysTemp> grasSysTempList = new ArrayList<>();
            if (policys != null && policys.size() > 0) {
                List<List> policyLists = subListPolicyList(policys);
                for (List policyList : policyLists) {
                    List policyListResults = tempService.getByPolicyList(policyList);
                    grasSysTempList.addAll(policyListResults);
                }
            }
            //判空 分单成功的这些向数据库传输
            if (grasSysTempList != null && grasSysTempList.size() != 0) {
                for (GrasSysTemp sysTemp : grasSysTempList) {
                    //保单号
                    String policyNo = sysTemp.getPolicyNo();
                    //分单规则
                    String assginRule = sysTemp.getAssignRule();

                    //保单对应服务人员编号
                    String servicerNo = sysTemp.getServicerNo();
                    //保单已经分配了服务人员
                    if (servicerNo != null && !"".equals(servicerNo)) {
                        //用于存放给核心系统传输数据的
                        JSONObject dataJSON = new JSONObject(){{
                            put("policyNo", policyNo);
                            put("servicerNo", servicerNo);
                            put("orphanMark", "0");
                            put("assignRule", assginRule);
                            put("lastAssignUser", user);
                            put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        }};
//                        //保单号
//                        dataJSON.put("policyNo", policyNo);
//                        //对应服务人员
//                        dataJSON.put("servicerNo", servicerNo);
//                        //孤儿单标记
//                        dataJSON.put("orphanMark", "0");
//                        //对应的分单规则
//                        dataJSON.put("assignRule", assginRule);
//                        //分单操作人,就是当前用户
//                        dataJSON.put("lastAssignUser", user);
//                        //操作日期
//                        dataJSON.put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        paramArray.add(dataJSON);
                        //保单没有分配人员
                    } else {
                        JSONObject dataJSON = new JSONObject(){{
                            put("policyNo", policyNo);
                            put("servicerNo", "");
                            put("orphanMark", "1");
                            put("assignRule", assginRule);
                            put("lastAssignUser", user);
                            put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        }};
//                        dataJSON.put("policyNo", policyNo);
//                        dataJSON.put("servicerNo", "");
//                        dataJSON.put("orphanMark", "1");
//                        dataJSON.put("assignRule", assginRule);
//                        dataJSON.put("lastAssignUser", user);
//                        dataJSON.put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        paramArray.add(dataJSON);
                    }
                    setPolicyServicerChgRecord(policyNo, servicerNo, assginRule, user, RNPSCRList);
                }
            }
            //向核心系统传数据
            logUtils.info("核心系统回写...时间:" + new Date() + "向核心系统传入的参数为:" + paramArray);
            //此处要求是按3000条进行传输一次
            List<JSONArray> jsonArrays = submit3000Datas(paramArray, 3000);
            //传输失败的保单数组
            List<String> failedPolicyNos = new ArrayList<>();
            //传输记录 用于记录
            List<GrasSysDataTrans> transList = new ArrayList<>();
            //分批传输
            for (JSONArray pageDatas : jsonArrays) {
                //每次传输的结果
                JSONObject everyTimeSyncResult = AllotResultsBack.syncPolicyRule(pageDatas);
                logUtils.info(new Date() + "本次回写结果:" + everyTimeSyncResult);
                //传输成功与否的标示
                String flag = everyTimeSyncResult.getString("flag");
                //接口返回的传输失败的保单
                JSONArray failedPolicys = everyTimeSyncResult.getJSONArray("policyNos");
                if("0".equals(flag)){
                    //失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = failedPolicy.getString(policyNo);
                                failedPolicyNos.add(policyNo);
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                    //传输成功
                    transFlag = "传输成功";
                }else {
                    transFlag = "传输失败";
                    //传输失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = "";
                                failedPolicyNos.add(policyNo);
                                //接口返回的结果 可能长度很长不符合数据库规范
                                if (failedPolicy.getString(policyNo).length() >= 200) {
                                    failedReason = failedPolicy.getString(policyNo).substring(0, 199);
                                } else {
                                    failedReason = failedPolicy.getString(policyNo);
                                }
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                }
            }
            //传输成功的保单的处理 移除失败的就是成功的
            policys.removeAll(failedPolicyNos);
            if (policys != null && policys.size() != 0) {
                for (String policyNo : policys) {
                    GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"Y","Y","传输成功",user,user);
                    transList.add(transData);
                }
            }
            //临时表中数据的剔除 回写成功了的
            if (policys != null && policys.size() != 0) {
                for (List deleteList : subListPolicyList(policys)) {
                    sysTempService.deleteByPolicyList(deleteList);
                }
            }
            //写入到数据库
            if (transList != null && transList.size() != 0) {
                for (List mergeList : subListPolicyList(transList)) {
                    transService.mergeDataTransList(mergeList);
                }
            }
           //报存保单交接记录
            /*for (RNPolicyServicerChgRecord policyServicer : RNPSCRList)
            {
                if(policys.contains(policyServicer.getPolicyNo())){
                    changeService.insert(policyServicer);
                }
            }*/
            
            //更新es
            JSONObject jsonObject=new JSONObject();
            List<JSONObject> policyNolist=new ArrayList<JSONObject>();
            for (Object object : paramArray)
            {
                jsonObject=(JSONObject)object;
                for(String policyNo:policys){
                    if(policyNo.equals(jsonObject.get("policyNo"))){
                        String servicerNo=(String) jsonObject.get("servicerNo");
                        StaffInfo staffInfo=staffInfoService.selectByPrimaryKey(servicerNo);
                        if(staffInfo!=null){
                            jsonObject.put("empName", staffInfo.getEmpName());
                            policyNolist.add(jsonObject);
                        }
                       break; 
                    }
                }
            }
            elasticSearchService.updateAssignPolicyInfo(policyNolist);
            
        } catch (Exception e) {
            transFlag = "传输失败";
            reason = e.getMessage();
            resultJson.put("result", transFlag);
            resultJson.put("reason", reason);
            //错误输出
            logUtils.error(e.toString());
            e.printStackTrace();
        }
        resultJson.put("result", transFlag);
        resultJson.put("reason", reason);
        return resultJson;
    }

    @Override
    public boolean adjustEmp(String branchCode, String policyNo, String empNo,String userName) {

        String batch = "";
        List<GrasAssignBatchRecord> batchRecords = batchRecordService.assignBatchRecordMonth(branchCode);
        if (batchRecords != null && batchRecords.size() > 0) {
            GrasAssignBatchRecord batchRecord = batchRecords.get(0);
            batch = batchRecord.getBatchSeq();
        }
        GrasSysTemp temp = new GrasSysTemp(policyNo,branchCode,empNo,MyConstant.ASSIGN_RULE_11,batch,userName);
        List<GrasSysTemp> tempList = new ArrayList<>();
        tempList.add(temp);
        int mergeResult = sysTempService.insertOrUpdateBatch(tempList);
        if (mergeResult == 1) {
            //成功后要删除失败表的数据
//            failedRecordService.deleteByPolicy(policyNo);
            failedRecordService.updatePolicy("N",policyNo);
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String,String>> selectForExcel(String flag, String branchCode, String month, List channelType) {
        //月份格式化
        List<JSONObject> resultJson = new ArrayList<>();
        String nowMonth = null;
        String nextMonth = null;
        Integer total = 0;
        List<Map<String,String>> resultList = new ArrayList<>();
        if (month != null && !"".equals(month)) {
            //起始日
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
            //截止日
            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        List<String> batchRecordsList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        if (batchRecordsList != null && batchRecordsList.size() != 0) {
            if (flag.equals(SUCCESSFUL_FLAG)) {
                //总数
                total = sysTempService.countPolicyForPageInfoSuccess(batchRecordsList, branchCode, channelType);
                //总页数
                int totalPages = (total / 10) + 1;
                for (int i = 1; i <= totalPages; i++) {
                    List<Map<String,String>> pageList = sysTempService.querySuccesPolicy(batchRecordsList, branchCode, i, 10, channelType);
                    resultList.addAll(pageList);
                }
            } else if (flag.equals(FAILED_FLAG)) {
                total = sysTempService.countPolicyForPageInfoFailed(batchRecordsList, branchCode, channelType);
                //总页数
                int totalPages = (total / 10) + 1;
                for (int i = 1; i <= totalPages; i++) {
                    List<Map<String,String>> pageList = sysTempService.queryFailedPolicy(batchRecordsList, branchCode, i, 10, channelType);
                    resultList.addAll(pageList);
                }
            }
        }
        return resultList;
    }

    /**
     * 自动提交保单至核心系统
     * 剩下的所有保单都是要提交的
     */
    @Override
    public void autoResultBack() {
        List<String> policies = sysTempService.selectAllPolicies();
        JSONObject resultBack = resultBack(MyConstant.SYS_USER, policies);
        String result = resultBack.getString("result");
        //传输失败
        if (result == null || !result.equals("传输成功")) {
            //再次提交
            autoResultBack();
        }
    }

    //list长度可能过长 进行截取
    private List<List> subListPolicyList(List policyList) {
        List<List> resultList = new ArrayList();
        if (policyList == null || policyList.size() == 0) {
            return null;
        }
        for (int i = 0; i < policyList.size(); i++) {
            if (i % 999 == 0) {
                int count = i / 999;
                List subList = (List) policyList.stream().limit((count + 1) * 999).skip(count * 999).collect(Collectors.toList());
                resultList.add(subList);
            }
        }
        return resultList;
    }


    //查看人员能服务哪些渠道
    private Set<String> checkChannelTypes(String empNo) {
        Set<String> channelList = new LinkedHashSet<>();
        //人员本身的渠道
        String channelTypeByEmpNp = staffInfoService.selectChannelTypeByEmpNp(empNo);
        channelList.add(channelTypeByEmpNp);
        //兼收范围查看
        RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(empNo);
        //个险兼收标示OK  个险兼收     可服务保单渠道:个险,经代,收展,银代 SFP 区拓 创新拓展
        if (staffInfoOther != null && "Y".equals(staffInfoOther.getMarketFlag())) {
            addChannelTypes(channelList, MyConstant.CHANNEL_02, MyConstant.CHANNEL_03, MyConstant.CHANNEL_04, MyConstant.CHANNEL_05, MyConstant.CHANNEL_09, MyConstant.CHANNEL_07);
        }
        //银代兼收标示OK  可服务保单渠道:个险,经代,收展,银代
        if (staffInfoOther != null && "Y".equals(staffInfoOther.getBankFlag())) {
            addChannelTypes(channelList, MyConstant.CHANNEL_05, MyConstant.CHANNEL_02, MyConstant.CHANNEL_03, MyConstant.CHANNEL_04, MyConstant.CHANNEL_09, MyConstant.CHANNEL_07);
        }
        //人员职位
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(empNo);
        if (staffInfo != null) {
            //人员职位
            String position = staffInfo.getPosition();
            //收展主任 可以负责:个险,经代,收展,银代,SFP(属于银代),区拓(属于个险),创新(属于银代)
            if (position != null && !"".equals(position) && MyConstant.CD_DIRECTOR.equals(position)) {
                addChannelTypes(channelList, MyConstant.CHANNEL_02, MyConstant.CHANNEL_03, MyConstant.CHANNEL_04, MyConstant.CHANNEL_05, MyConstant.CHANNEL_07, MyConstant.CHANNEL_09);
            }
            //个险收展专员  个险,经代,收展
            if (position != null && !"".equals(position) && MyConstant.PERSONAL_INSURANCE_SERVICER.equals(position)) {
                channelList.addAll(Arrays.asList(MyConstant.CHANNEL_01,MyConstant.CHANNEL_03,MyConstant.CHANNEL_05,MyConstant.CHANNEL_07));
            }
            //银代收展专员 银代
            if (position != null && !"".equals(position) && MyConstant.BANK_AGENT_SERVICER.equals(position)) {
                channelList.addAll(Arrays.asList(MyConstant.CHANNEL_02,MyConstant.CHANNEL_04,MyConstant.CHANNEL_09));
            }
        }
        return channelList;
    }

    private void addChannelTypes(Set<String> channelList, String e2, String e3, String e4, String e5, String e6, String e7) {
        channelList.add(MyConstant.CHANNEL_01);
        channelList.addAll(Arrays.asList(e2,e3,e4,e5,e6,e7));
    }

    /**
     * MethodName:  queryPoServerInfoExportToExcel 
     * Description:  [根据应缴月查询机构保单服务信息] 
     *@param branchCode
     *@param channelType
     *@param month
     *@return 
     */
    @Override
    public List<JSONObject> queryPoServerInfoExportToExcel(String branchCode, String channelType, String month)
    {
        Map<String, String> paramMap=new HashMap<String,String>();
        String nowMonth = null;
        String nextMonth = null;
        if (month != null && !"".equals(month)) {
//            Map<String, String> allotMonth = DateUtil.allotMonth(month);
            //起始日
//            nowMonth = allotMonth.get("nowMonth");
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
            //截止日
//            nextMonth = allotMonth.get("nextMonth");
            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        paramMap.put("branchCode", branchCode);
        paramMap.put("nowMonth", nowMonth);
        paramMap.put("nextMonth", nextMonth);
        
        List<String> channelTypeList = null;
        if(!StringUtils.isEmpty(channelType)){
            String[] channelTpList=channelType.split(",");
            channelTypeList=Arrays.asList(channelTpList);
            
            //paramMap.put("channelType", channelType);
        }
       //List<JSONObject> list=new ArrayList<JSONObject>();
       List<JSONObject> normalAssignList=null;
       //List<JSONObject> spanBranchList=null;
        try
        {
            normalAssignList=servicerInfoService.queryPoSericeInfoByPremDueDate(branchCode,nowMonth,nextMonth,channelTypeList);
            /*if(normalAssignList!=null){
                list.addAll(normalAssignList);
            }*/
            //获取跨机构分单保单
         /*   spanBranchList=servicerInfoService.querySpanBranchAssignPolicy(paramMap);
            if(spanBranchList!=null){
                list.addAll(spanBranchList);
            }*/
            
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
       
        return normalAssignList;
    }

    /**
     * 数据分3000条一次向RN系统传输
     * @param allDatas 全部数据
     * @param pageData 每次传多少
     * @return
     */
    private List<JSONArray> submit3000Datas(JSONArray allDatas,int pageData){
        List<JSONArray> resultList = new ArrayList();
        if(allDatas == null || allDatas.size() == 0){
            return null;
        }
        int num = 0;
        JSONArray tempArray = new JSONArray();
        for(int i = 0 ; i<allDatas.size();i++){
            JSONObject itemObject = allDatas.getJSONObject(i);
            tempArray.add(itemObject);
            num++;
            if (num == pageData){
                resultList.add(tempArray);
                num = 0;
                tempArray.clear();
            }
//            if(i % pageData == 0){
//                int count = i/pageData;
//                JSONArray subList = JSONArray.parseArray(allDatas.stream().limit((count + 1) * pageData).skip(count * pageData).collect(Collectors.toList()).toString()) ;
//                resultList.add(subList);
//            }
        }
        if (tempArray.size()>0){
            resultList.add(tempArray);
        }
        return resultList;
    }
}