tasks.py 143 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
import json
import os
import cv2
import time
import logging
import traceback
import numpy as np
from datetime import datetime, timedelta
from collections import OrderedDict
from . import app
from settings import conf
from apps.doc.models import (
    AFCOCRResult,
    AFCSEOCRResult,
    HILOCRResult,
    HILSEOCRResult,
    AFCComparisonInfo,
    AFCSEComparisonInfo,
    AFCSECMSInfo,
    HILComparisonInfo,
    HILSEComparisonInfo,
    HILSECMSInfo,
    Configs,
    HILCompareReport,
    AFCCompareReport,
    AFCSECompareResult,
    AFCCACompareResult,
    HILSECompareResult,
    HILCACompareResult,
    HILAutoSettlement,
    AFCAutoSettlement,
)
from apps.doc import consts
from apps.doc.ocr.gcap import gcap
from apps.doc.ocr.cms import cms
from apps.doc.exceptions import GCAPException
from apps.doc.named_enum import RequestTeam, RequestTrigger, ProcessName, ErrorType
from common.tools.comparison import cp
from common.tools.des import decode_des

compare_log = logging.getLogger('compare')
log_base = '[Compare]'
# e_log_base = '[e-contract]'
empty_str = ''
empty_error_type = 1000
des_key = conf.CMS_DES_KEY


def rotate_bound(image, angle):
    # grab the dimensions of the image and then determine the
    # center
    (h, w) = image.shape[:2]
    (cX, cY) = (w // 2, h // 2)

    # grab the rotation matrix (applying the negative of the
    # angle to rotate clockwise), then grab the sine and cosine
    # (i.e., the rotation components of the matrix)
    M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY

    # perform the actual rotation and return the image
    return cv2.warpAffine(image, M, (nW, nH))


def build_coordinates(section_position_dict):
    if isinstance(section_position_dict, dict):
        h_min = section_position_dict.get('top', 0)
        w_min = section_position_dict.get('left', 0)
        h_max = h_min + section_position_dict.get('height', 0)
        w_max = w_min + section_position_dict.get('width', 0)
        if h_max > h_min and w_max > w_min:
            return True, (h_min, h_max, w_min, w_max)
        else:
            return False, ()
    return False, ()


def field_build_coordinates(field_position_info):
    field_position_dict = field_position_info.get(consts.FIELD_POSITION_KEY, {})
    field_quad_list = field_position_info.get(consts.FIELD_QUAD_KEY, [])
    if isinstance(field_quad_list, list) and len(field_quad_list) == 8:
        w_list = [field_quad_list[0], field_quad_list[2], field_quad_list[4], field_quad_list[6]]
        h_list = [field_quad_list[1], field_quad_list[3], field_quad_list[5], field_quad_list[7]]
        h_min = min(h_list)
        h_max = max(h_list)
        w_min = min(w_list)
        w_max = max(w_list)
        if h_max > h_min and w_max > w_min:
            return True, (h_min, h_max, w_min, w_max)
    if isinstance(field_position_dict, dict):
        h_min = field_position_dict.get('top', 0)
        w_min = field_position_dict.get('left', 0)
        h_max = h_min + field_position_dict.get('height', 0)
        w_max = w_min + field_position_dict.get('width', 0)
        if h_max > h_min and w_max > w_min:
            return True, (h_min, h_max, w_min, w_max)
        else:
            return False, ()
    return False, ()


def img_process(section_img_path, section_position, section_angle):
    image = cv2.imread(section_img_path)
    is_valid, coord_tuple = build_coordinates(section_position)
    if is_valid:
        image = image[coord_tuple[0]:coord_tuple[1], coord_tuple[2]:coord_tuple[3], :]
    if isinstance(section_angle, int) or isinstance(section_angle, float):
        if section_angle != 0:
            return rotate_bound(image, section_angle)
    return image


def name_check(ocr_res_dict, second_ocr_field, second_compare_list, second_id_num, name):
    id_field = second_compare_list[1][1]
    name_field = second_compare_list[0][1]
    ocr_res_str = ocr_res_dict.get(second_ocr_field)
    if ocr_res_str is not None:
        ocr_res_list = json.loads(ocr_res_str)
        for ocr_res in ocr_res_list:
            ocr_second_id_num = ocr_res.get(id_field)
            if ocr_second_id_num == second_id_num:
                ocr_name = ocr_res.get(name_field)
                if ocr_name == name:
                    return True
    return False


def get_order_dict(src_dict, order_tuple):
    order_dict = OrderedDict({})
    for field in order_tuple:
        if field in src_dict:
            order_dict[field] = src_dict[field]
    return order_dict


def do_not_compare(info_dict, compare_list):
    for compare_tuple in compare_list:
        info_dict[compare_tuple[4]] = consts.RESULT_NA
        if compare_tuple[0] in info_dict:
            del info_dict[compare_tuple[0]]


def field_compare(info_dict, ocr_res_dict, ocr_field, compare_list, res_set,
                  has_expiry_date=False, sep_name=None, capital_ignore=False):
    is_find = False
    ocr_res_str = ocr_res_dict.get(ocr_field)
    if ocr_res_str is not None:
        ocr_res_list = json.loads(ocr_res_str)
        # length = len(ocr_res_list)

        # sep营业执照根据法人过滤
        if isinstance(sep_name, str):
            tmp_list = []
            for ocr_res in ocr_res_list:
                ocr_sep_name = ocr_res.get(consts.LEGAL_REP_NAME)
                if isinstance(ocr_sep_name, str) and ocr_sep_name == sep_name:
                    tmp_list.append(ocr_res)
        else:
            tmp_list = ocr_res_list

        length = len(tmp_list)

        # 过期期限特殊处理
        if has_expiry_date:
            expiry_dates = []
            key = compare_list[2][1]
            for ocr_res in tmp_list:
            # for ocr_res in ocr_res_list:
                if ocr_res.get(key):
                    expiry_dates.append(ocr_res.get(key))
        else:
            expiry_dates = []

        for res_idx in range(length-1, -1, -1):
        # for ocr_res in ocr_res_list:
            if is_find:
                break
            ocr_res = tmp_list[res_idx]
            for idx, compare_tuple in enumerate(compare_list):
                input_str = info_dict.get(compare_tuple[0])
                ocr_str = ocr_res.get(compare_tuple[1])
                compare_res, ocr_output = getattr(cp, compare_tuple[2])(
                    input_str, ocr_str, idx, **compare_tuple[3])
                # print('type: {0}, idx: {1}, field: {2}, input: {3}, ocr: {4}, res: {5}, out: {6}'.format(ocr_field, idx, compare_tuple[0], input_str, ocr_str, compare_res, ocr_output))
                if idx == 0 and compare_res in [consts.RESULT_N, consts.RESULT_NA] and length > 1:
                    break
                is_find = True

                # 过期期限特殊处理
                if idx == 2 and has_expiry_date and compare_res == consts.RESULT_NA:
                    for expiry_date in expiry_dates:
                        expiry_date_compare_res, expiry_date_ocr_output = getattr(cp, compare_tuple[2])(
                            input_str, expiry_date, idx, **compare_tuple[3]
                        )
                        if expiry_date_compare_res == consts.RESULT_Y:
                            compare_res = consts.RESULT_Y
                            ocr_output = expiry_date_ocr_output
                            ocr_str = expiry_date
                            break

                info_dict[compare_tuple[4]] = compare_res
                if input_str is not None:
                    if ocr_str is None or ocr_output is None:
                        del info_dict[compare_tuple[0]]
                    else:
                        info_dict[compare_tuple[0]] = ocr_output
                if capital_ignore and idx == 1:
                    pass
                elif capital_ignore and idx == 2 and input_str is None:
                    pass
                else:
                    res_set.add(compare_res)
    if not is_find:
        res_set.add(consts.RESULT_N)
        for compare_tuple in compare_list:
            info_dict[compare_tuple[4]] = consts.RESULT_NA
            if compare_tuple[0] in info_dict:
                del info_dict[compare_tuple[0]]


def usedcar_info_compare(info_dict, ocr_res_dict, ocr_field, compare_list, res_set):
    no_match_vino = []
    is_find = False
    key_right = False
    ocr_res_str = ocr_res_dict.get(ocr_field)
    if ocr_res_str is not None:
        ocr_res_list = json.loads(ocr_res_str)

        # 3、4页/副页去除
        # if ocr_field == consts.MVC_OCR_FIELD:
        tmp_list = []
        for res in ocr_res_list:
            if res.get(compare_list[0][1]) is not None:
                tmp_list.append(res)

        length = len(tmp_list)

        for res_idx in range(length-1, -1, -1):
            if is_find:
                break
            ocr_res = tmp_list[res_idx]
            for idx, compare_tuple in enumerate(compare_list):
                input_str = info_dict.get(compare_tuple[0])
                ocr_str = ocr_res.get(compare_tuple[1])
                compare_res, ocr_output = getattr(cp, compare_tuple[2])(
                    input_str, ocr_str, idx, **compare_tuple[3])
                # print('type: {0}, idx: {1}, field: {2}, input: {3}, ocr: {4}, res: {5}, out: {6}'.format(ocr_field, idx, compare_tuple[0], input_str, ocr_str, compare_res, ocr_output))
                if idx == 0 and compare_res in [consts.RESULT_N, consts.RESULT_NA]:
                    if ocr_str is not None:
                        no_match_vino.append(ocr_str)
                    if length > 1:
                        break
                is_find = True
                if idx == 0 and compare_res == consts.RESULT_Y:
                    key_right = True
                info_dict[compare_tuple[4]] = compare_res
                if input_str is not None:
                    if idx != 0:
                        if ocr_str is None or ocr_output is None:
                            del info_dict[compare_tuple[0]]
                        else:
                            info_dict[compare_tuple[0]] = ocr_output
                res_set.add(compare_res)
    if not is_find:
        res_set.add(consts.RESULT_N)
        for idx, compare_tuple in enumerate(compare_list):
            info_dict[compare_tuple[4]] = consts.RESULT_NA
            if idx == 0:
                continue
            if compare_tuple[0] in info_dict:
                del info_dict[compare_tuple[0]]
    return is_find and key_right, no_match_vino


def get_ca_compare_info(last_obj):
    compare_info = {}
    individual_info_dict = {}
    for individual_info in json.loads(last_obj.individual_cus_info):
        license_dict = {}

        if individual_info['idType'] in consts.CA_FIRST_ID_FIELD_MAPPING:
            license_en, field_list = consts.CA_FIRST_ID_FIELD_MAPPING[individual_info['idType']]
            field_input = []
            for field in field_list:
                if field in individual_info:
                    field_input.append((field, individual_info.get(field, '')))
            license_dict[license_en] = field_input

        if individual_info.get('secondIdType') in consts.CA_SECOND_ID_FIELD_MAPPING:
            second_license_en, second_field_list = consts.CA_SECOND_ID_FIELD_MAPPING[individual_info['secondIdType']]
            if second_license_en not in license_dict:
                second_field_input = []
                for second_field, write_field in second_field_list:
                    if second_field in individual_info:
                        second_field_input.append((write_field, individual_info.get(second_field, '')))
                license_dict[second_license_en] = second_field_input

        if individual_info['customerType'] == consts.CUSTOMER_TYPE[5]:
            sep_field_input = []
            for sep_field in consts.CA_SEP_FIELD:
                if sep_field in individual_info:
                    sep_field_input.append((sep_field, individual_info.get(sep_field, '')))
            license_dict[consts.BL_EN] = sep_field_input

        if len(license_dict) > 0:
            individual_info_dict.setdefault(individual_info['applicantType'], []).append(license_dict)

    compare_info['individualCusInfo'] = individual_info_dict

    if isinstance(last_obj.corporate_cus_info, str):
        corporate_info_dict = json.loads(last_obj.corporate_cus_info)
        corporate_info = {}
        bl_field_input = []
        for bl_field, write_field in consts.CA_CORPORATE_FIELD:
            bl_field_input.append((write_field, corporate_info_dict.get(bl_field, '')))
        corporate_info[consts.BL_EN] = bl_field_input

        compare_info['corporateCusInfo'] = corporate_info

    if last_obj.vehicle_status == consts.VEHICLE_STATUS[0] and isinstance(last_obj.usedcar_info, str):
        usedcar_info_dict = json.loads(last_obj.usedcar_info)
        usedcar_info = {}

        mvc_field_input = []
        for mvc_field in consts.CA_MVC_FIELD:
            mvc_field_input.append((mvc_field, usedcar_info_dict.get(mvc_field, '')))
        usedcar_info[consts.MVC_EN] = mvc_field_input

        dl_field_input = []
        for dl_field in consts.CA_DL_FIELD:
            dl_field_input.append((dl_field, usedcar_info_dict.get(dl_field, '')))
        usedcar_info[consts.DL_EN] = dl_field_input

        compare_info['usedCarInfo'] = usedcar_info

    return compare_info


def ca_compare_license(license_en, ocr_res_dict, field_list):
    ocr_field, compare_logic, special_expiry_date = consts.CA_COMPARE_FIELD[license_en]

    is_find = False
    special_expiry_date_slice = False
    result_field_list = []
    section_img_info = dict()
    field_img_path_dict = dict()
    ocr_res_str = ocr_res_dict.get(ocr_field)
    if ocr_res_str is not None:
        ocr_res_list = json.loads(ocr_res_str)

        # 副页去除 3/4页去除
        if ocr_field == consts.DL_OCR_FIELD or ocr_field == consts.MVC_OCR_FIELD:
            tmp_list = []
            for res in ocr_res_list:
                if compare_logic['vinNo'][0] in res:
                    tmp_list.append(res)
            ocr_res_list = tmp_list

        length = len(ocr_res_list)

        # 身份证、居住证 过期期限特殊处理
        if special_expiry_date:
            expiry_dates = set()
            expiry_dates_img_path = set()
            key = compare_logic.get('idExpiryDate')[0]
            for ocr_res in ocr_res_list:
                if key in ocr_res:
                    expiry_dates.add(ocr_res[key])
                    expiry_dates_img_path.add(ocr_res.get(consts.IMG_PATH_KEY_2, ''))
        else:
            expiry_dates = set()
            expiry_dates_img_path = set()

        for res_idx in range(length-1, -1, -1):
            if is_find:
                break

            for idx, (name, value) in enumerate(field_list):
                ocr_str = ocr_res_list[res_idx].get(compare_logic[name][0])
                if not isinstance(ocr_str, str):
                    result = consts.RESULT_N
                    ocr_str = empty_str
                else:
                    result = getattr(cp, compare_logic[name][1])(value, ocr_str, **compare_logic[name][2])

                if idx == 0 and result == consts.RESULT_N and length > 1:
                    break

                is_find = True
                section_img_info[consts.SECTION_IMG_PATH_KEY] = ocr_res_list[res_idx].get(consts.SECTION_IMG_PATH_KEY, '')
                section_img_info[consts.ALL_POSITION_KEY] = ocr_res_list[res_idx].get(consts.ALL_POSITION_KEY, {})
                if special_expiry_date:
                    section_img_info[consts.SECTION_IMG_PATH_KEY_2] = ocr_res_list[res_idx].get(
                        consts.SECTION_IMG_PATH_KEY_2, '')
                    section_img_info[consts.ALL_POSITION_KEY_2] = ocr_res_list[res_idx].get(consts.ALL_POSITION_KEY_2, {})

                # 过期期限特殊处理
                if special_expiry_date and name == 'idExpiryDate' and result == consts.RESULT_N:
                    for expiry_date in expiry_dates:
                        expiry_date_res = getattr(cp, compare_logic[name][1])(value, expiry_date, **compare_logic[name][2])
                        if expiry_date_res == consts.RESULT_Y:
                            ocr_str = expiry_date
                            result = expiry_date_res
                            break

                    if result == consts.RESULT_N:
                        if consts.IMG_PATH_KEY_2 in ocr_res_list[res_idx]:
                            img_path = ocr_res_list[res_idx].get(consts.IMG_PATH_KEY_2, '')
                            special_expiry_date_slice = True
                        else:
                            img_path = expiry_dates_img_path.pop() if len(expiry_dates_img_path) > 0 else empty_str
                    else:
                        img_path = empty_str
                else:
                    img_path = ocr_res_list[res_idx].get(consts.IMG_PATH_KEY, '') if result == consts.RESULT_N else empty_str
                error_type = empty_error_type if result == consts.RESULT_Y else ErrorType.OCR.value
                result_field_list.append((name, value, result, ocr_str, img_path, error_type))

    if not is_find:
        for name, value in field_list:
            result_field_list.append((name, value, consts.RESULT_N, empty_str, empty_str, ErrorType.NF.value))

    if is_find:
        if special_expiry_date_slice:
            special_section_img_path = section_img_info.get(consts.SECTION_IMG_PATH_KEY_2, '')
            if os.path.exists(special_section_img_path):
                field = 'idExpiryDate'
                special_info = section_img_info.get(consts.ALL_POSITION_KEY_2, {})
                special_section_position = special_info.get(consts.POSITION_KEY, {})
                special_section_angle = special_info.get(consts.ANGLE_KEY, 0)
                try:
                    last_img = img_process(special_section_img_path, special_section_position, special_section_angle)
                except Exception as e:
                    field_img_path_dict[field] = special_section_img_path
                else:
                    pre, suf = os.path.splitext(special_section_img_path)
                    try:
                        res_field = compare_logic[field][0]
                        is_valid, coord_tuple = field_build_coordinates(special_info.get(res_field, {}))
                        if is_valid:
                            save_path = '{0}_{1}{2}'.format(pre, field, suf)
                            field_img = last_img[coord_tuple[0]:coord_tuple[1], coord_tuple[2]:coord_tuple[3], :]
                            cv2.imwrite(save_path, field_img)
                            field_img_path_dict[field] = save_path
                        else:
                            field_img_path_dict[field] = special_section_img_path
                    except Exception as e:
                        field_img_path_dict[field] = special_section_img_path

        section_img_path = section_img_info.get(consts.SECTION_IMG_PATH_KEY, '')
        if os.path.exists(section_img_path):
            failed_field = []
            base_img_path = empty_str
            for name, _, result, _, img_path, _ in result_field_list:
                if result == consts.RESULT_N:
                    if special_expiry_date_slice and name == 'idExpiryDate':
                        continue
                    failed_field.append(name)
                    if base_img_path == empty_str:
                        base_img_path = img_path
            if len(failed_field) > 0:
                info = section_img_info.get(consts.ALL_POSITION_KEY, {})
                section_position = info.get(consts.POSITION_KEY, {})
                section_angle = info.get(consts.ANGLE_KEY, 0)
                try:
                    last_img = img_process(section_img_path, section_position, section_angle)
                except Exception as e:
                    for field in failed_field:
                        field_img_path_dict[field] = base_img_path
                else:
                    pre, suf = os.path.splitext(section_img_path)
                    for field in failed_field:
                        try:
                            if license_en == consts.PP_EN:
                                res_field = consts.PP_SLICE_MAP[field]
                            else:
                                res_field = compare_logic[field][0]
                            is_valid, coord_tuple = field_build_coordinates(info.get(res_field, {}))
                            if is_valid:
                                save_path = '{0}_{1}{2}'.format(pre, field, suf)
                                field_img = last_img[coord_tuple[0]:coord_tuple[1], coord_tuple[2]:coord_tuple[3], :]
                                cv2.imwrite(save_path, field_img)
                                field_img_path_dict[field] = save_path
                            else:
                                field_img_path_dict[field] = base_img_path
                        except Exception as e:
                            field_img_path_dict[field] = base_img_path

    return result_field_list, field_img_path_dict


def ca_compare_process(compare_info, ocr_res_dict):
    # individualCusInfo
    # corporateCusInfo
    # usedCarInfo
    compare_result = []
    total_fields = 0
    failed_count = 0

    for info_key, info_value in compare_info.items():
        if info_key == 'individualCusInfo':
            for idx, license_list in info_value.items():
                for license_dict in license_list:
                    for license_en, field_list in license_dict.items():
                        result_field_list, field_img_path_dict = ca_compare_license(license_en, ocr_res_dict, field_list)
                        for name, value, result, ocr_str, img_path, error_type in result_field_list:
                            total_fields += 1
                            if result == consts.RESULT_N:
                                failed_count += 1
                            compare_result.append(
                                {
                                    consts.HEAD_LIST[0]: info_key,
                                    consts.HEAD_LIST[1]: idx,
                                    consts.HEAD_LIST[2]: license_en,
                                    consts.HEAD_LIST[3]: name,
                                    consts.HEAD_LIST[4]: value,
                                    consts.HEAD_LIST[5]: ocr_str,
                                    consts.HEAD_LIST[6]: result,
                                    consts.HEAD_LIST[7]: field_img_path_dict.get(name, empty_str),
                                    consts.HEAD_LIST[8]: img_path,
                                    consts.HEAD_LIST[9]: error_type,
                                }
                            )
        else:
            for license_en, field_list in info_value.items():
                result_field_list, field_img_path_dict = ca_compare_license(license_en, ocr_res_dict, field_list)
                for name, value, result, ocr_str, img_path, error_type in result_field_list:
                    total_fields += 1
                    if result == consts.RESULT_N:
                        failed_count += 1
                    compare_result.append(
                        {
                            consts.HEAD_LIST[0]: info_key,
                            consts.HEAD_LIST[1]: "0",
                            consts.HEAD_LIST[2]: license_en,
                            consts.HEAD_LIST[3]: name,
                            consts.HEAD_LIST[4]: value,
                            consts.HEAD_LIST[5]: ocr_str,
                            consts.HEAD_LIST[6]: result,
                            consts.HEAD_LIST[7]: field_img_path_dict.get(name, empty_str),
                            consts.HEAD_LIST[8]: img_path,
                            consts.HEAD_LIST[9]: error_type,
                        }
                    )
    return compare_result, total_fields, failed_count


def ca_compare(application_id, application_entity, ocr_res_id, last_obj, ocr_res_dict):
    start_time = datetime.now()

    try:
        # 比对逻辑
        compare_info = get_ca_compare_info(last_obj)
        compare_result, total_fields, failed_count = ca_compare_process(compare_info, ocr_res_dict)
        compare_log.info('{0} [CA] [compare success] [entity={1}] [id={2}] [ocr_res_id={3}] [result={4}]'.format(
            log_base, application_entity, application_id, ocr_res_id, compare_result))
    except Exception as e:
        compare_log.error('{0} [CA] [compare error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                          '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                               traceback.format_exc()))
    else:
        # 将比对结果写入数据库
        try:
            result_table = HILCACompareResult if application_entity == consts.HIL_PREFIX else AFCCACompareResult
            res_obj = result_table.objects.filter(application_id=application_id).first()
            if res_obj is None:
                res_obj = result_table()
                res_obj.application_id = application_id
            res_obj.compare_count = total_fields
            res_obj.failed_count = failed_count
            res_obj.is_finish = failed_count == 0
            res_obj.version = '{0}{1}{2}'.format(consts.INFO_SOURCE[0], consts.SPLIT_STR, last_obj.application_version)
            # res_obj.reason1_count = reason1_count
            res_obj.result = json.dumps(compare_result)
            res_obj.update_time = start_time
            res_obj.save()
            compare_log.info('{0} [CA] [result save success] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                log_base, application_entity, application_id, ocr_res_id))
        except Exception as e:
            compare_log.error('{0} [CA] [result save error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                              '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                                   traceback.format_exc()))

    compare_failed = False
    application_link = '{0}/showList/showList?entity={1}&scheme={2}&case_id={3}'.format(
        conf.BASE_URL, application_entity, consts.COMPARE_DOC_SCHEME_LIST[0], application_id)

    # 比对信息
    try:
        comparison_res = OrderedDict({
            'OCR_Input': {
                'uniqSeq': last_obj.uniq_seq,
                'applicationId': application_id,
                'applicationEntity': application_entity,
                'applicationVersion': last_obj.application_version,
                'vehicleStatus': last_obj.vehicle_status,
                'wholeResult': 'N',
                'wholeResultMessage': empty_str,
                'applicationLink': application_link.replace('&', '&'),
            }
        })

        res_set = set()

        # is_sep = True if last_obj.customer_type == consts.CUSTOMER_TYPE[5] else False

        individual_cus_info_list = json.loads(last_obj.individual_cus_info)
        order_individual_cus_info_list = []
        for individual_cus_info in individual_cus_info_list:
            order_individual_cus_info = get_order_dict(individual_cus_info, consts.IN_ORDER)

            cus_type = order_individual_cus_info.get('customerType')

            # 获取sep下营业执照法人代表
            if cus_type == consts.CUSTOMER_TYPE[5]:
                sep_name = order_individual_cus_info.get('customerChineseName')
                if isinstance(sep_name, str):
                    sep_name = sep_name.strip()
                    if sep_name == empty_str:
                        sep_name = None
            else:
                sep_name = None

            # 个人信息证件
            id_type = order_individual_cus_info.get('idType')
            if id_type not in consts.ID_TYPE_COMPARE:
                do_not_compare(order_individual_cus_info, consts.ITPRC)
            else:
                ocr_field, compare_list, has_expiry_date = consts.ID_TYPE_COMPARE.get(id_type)
                field_compare(order_individual_cus_info, ocr_res_dict, ocr_field, compare_list, res_set,
                              has_expiry_date=has_expiry_date)

            # 第二证件
            second_id_type = order_individual_cus_info.get('secondIdType')
            if second_id_type is not None:
                if second_id_type not in consts.SECOND_ID_TYPE_COMPARE:
                    do_not_compare(order_individual_cus_info, consts.SECOND_ITPRC)
                else:
                    second_ocr_field, second_compare_list = consts.SECOND_ID_TYPE_COMPARE.get(second_id_type)
                    field_compare(order_individual_cus_info, ocr_res_dict, second_ocr_field,
                                  second_compare_list, res_set)

                # 姓名比对
                second_id_res = order_individual_cus_info.pop(consts.SECOND_ID_RES, consts.RESULT_NA)
                if second_id_res == consts.RESULT_Y:
                    second_id_num = order_individual_cus_info.get(consts.SECOND_ID_FIELD)
                    name = order_individual_cus_info.get(consts.NAME_FIELD)
                    if isinstance(second_id_num, str) and isinstance(name, str):
                        second_ocr_field, second_compare_list, _ = consts.ID_TYPE_COMPARE.get(second_id_type)
                        name_right = name_check(ocr_res_dict, second_ocr_field, second_compare_list, second_id_num, name)
                        if not name_right:
                            res_set.add(consts.RESULT_N)
                            second_id_res = consts.RESULT_N
                            order_individual_cus_info[consts.SECOND_ID_FIELD] = '{0}-{1}'.format(second_id_num, name)

                # 重新排列
                new_dict = OrderedDict({})
                for key, value in order_individual_cus_info.items():
                    new_dict[key] = value
                    if key == consts.ID_RES:
                        new_dict[consts.SECOND_ID_RES] = second_id_res
                order_individual_cus_info = new_dict

            # sep营业执照
            if cus_type == consts.CUSTOMER_TYPE[5]:
                field_compare(order_individual_cus_info, ocr_res_dict, consts.BL_OCR_FIELD, consts.TCSEP, res_set,
                              sep_name=sep_name, capital_ignore=True)

            order_individual_cus_info_list.append(order_individual_cus_info)

        comparison_res['OCR_Input']['individualCusInfo'] = order_individual_cus_info_list

        if last_obj.vehicle_status == consts.VEHICLE_STATUS[0] and last_obj.usedcar_info is not None:
            usedcar_info = json.loads(last_obj.usedcar_info)
            order_usedcar_info = get_order_dict(usedcar_info, consts.UC_ORDER)

            mvc_find, mvc_vinos = usedcar_info_compare(order_usedcar_info, ocr_res_dict, consts.MVC_OCR_FIELD,
                                                       consts.PCUSD_MVC, res_set)

            # if order_usedcar_info[consts.PCUSD_MVC[0][0] + 'Result'] == consts.RESULT_Y:
            dl_find, dl_vinos = usedcar_info_compare(order_usedcar_info, ocr_res_dict, consts.DL_OCR_FIELD,
                                                     consts.PCUSD_DL, res_set)

            if mvc_find is True and dl_find is False:
                vino = dl_vinos[-1] if len(dl_vinos) > 0 else empty_str
                order_usedcar_info[consts.PCUSD_MVC[0][0]] = '{0}-{1} {2} {3}-{4}'.format(
                    consts.PREFIX_MVC, consts.RESULT_Y, consts.SPLIT, consts.PREFIX_DL, vino)
                order_usedcar_info[consts.PCUSD_MVC[0][4]] = consts.RESULT_N
            elif mvc_find is False and dl_find is True:
                vino = mvc_vinos[-1] if len(mvc_vinos) > 0 else empty_str
                order_usedcar_info[consts.PCUSD_MVC[0][0]] = '{0}-{1} {2} {3}-{4}'.format(
                    consts.PREFIX_MVC, vino, consts.SPLIT, consts.PREFIX_DL, consts.RESULT_Y)
                order_usedcar_info[consts.PCUSD_MVC[0][4]] = consts.RESULT_N
            elif mvc_find is False and dl_find is False:
                if len(mvc_vinos) == 0 and len(dl_vinos) == 0:
                    order_usedcar_info[consts.PCUSD_MVC[0][0]] = None
                    order_usedcar_info[consts.PCUSD_MVC[0][4]] = consts.RESULT_NA
                else:
                    mvc_vino = mvc_vinos[-1] if len(mvc_vinos) > 0 else empty_str
                    dl_vino = dl_vinos[-1] if len(dl_vinos) > 0 else empty_str
                    vino = '{0}-{1} {2} {3}-{4}'.format(
                        consts.PREFIX_MVC, mvc_vino, consts.SPLIT, consts.PREFIX_DL, dl_vino)
                    order_usedcar_info[consts.PCUSD_MVC[0][0]] = vino
                    order_usedcar_info[consts.PCUSD_MVC[0][4]] = consts.RESULT_N

            comparison_res['OCR_Input']['usedCarInfo'] = order_usedcar_info

        if last_obj.corporate_cus_info is not None:
            corporate_cus_info = json.loads(last_obj.corporate_cus_info)
            order_corporate_cus_info = get_order_dict(corporate_cus_info, consts.CO_ORDER)
            field_compare(order_corporate_cus_info, ocr_res_dict, consts.BL_OCR_FIELD, consts.TCCOR, res_set)

            comparison_res['OCR_Input']['corporateCusInfo'] = order_corporate_cus_info

        comparison_res['OCR_Input'][
            'wholeResult'] = consts.RESULT_N if consts.RESULT_N in res_set or consts.RESULT_NA in res_set else consts.RESULT_Y

    except Exception as e:
        compare_failed = True
        compare_log.error('{0} [CA] [compare error] [entity={1}] [id={2}] [ocr_res_id={3}] [error={4}]'.format(
            log_base, application_entity, application_id, ocr_res_id, traceback.format_exc()))
    else:
        compare_log.info('{0} [CA] [compare success] [entity={1}] [id={2}] [ocr_res_id={3}] [compare_res={4}]'.format(
            log_base, application_entity, application_id, ocr_res_id, comparison_res))

        is_gcap_send = Configs.objects.filter(id=1).first()
        if is_gcap_send is not None and is_gcap_send.value == 'N':
            compare_log.info('{0} [CA] [gcap closed] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                log_base, application_entity, application_id, ocr_res_id))
            return

        # 时间延迟
        send_time = last_obj.create_time + timedelta(seconds=15)
        while datetime.now() < send_time:
            compare_log.info('{0} [CA] [time wait 5s] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                log_base, application_entity, application_id, ocr_res_id))
            time.sleep(5)

        # 将比对结果发送GCAP
        try:
            data = gcap.dict_to_xml(comparison_res)
        except Exception as e:
            compare_log.error('{0} [CA] [dict to xml failed] [entity={1}] [id={2}] [ocr_res_id={3}] [error={4}]'.format(
                log_base, application_entity, application_id, ocr_res_id, traceback.format_exc()))
        else:
            try:
                for times in range(consts.RETRY_TIMES):
                    try:
                        res_text = gcap.send(data)
                    except Exception as e:
                        gcap_exc = str(e)
                    else:
                        break
                else:
                    raise GCAPException(gcap_exc)
            except Exception as e:
                compare_log.error('{0} [CA] [gcap failed] [entity={1}] [id={2}] [ocr_res_id={3}] [error={4}]'.format(
                    log_base, application_entity, application_id, ocr_res_id, traceback.format_exc()))
            else:
                compare_log.info('{0} [CA] [gcap success] [entity={1}] [id={2}] [ocr_res_id={3}] [response={4}]'.format(
                    log_base, application_entity, application_id, ocr_res_id, res_text))
                compare_log.info('{0} [CA] [task success] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                    log_base, application_entity, application_id, ocr_res_id))

        # report
        try:
            end_time = datetime.now()
            if compare_failed:
                successful_at_this_level = False
                failure_reason = 'Compare process error'
                total_fields = 0
            else:
                successful_at_this_level = True if comparison_res['OCR_Input'][
                                                       'wholeResult'] == consts.RESULT_Y else False
                field_failed = {
                    'individualCusInfo': [],
                    'corporateCusInfo': [],
                    'usedCarInfo': []
                }

                individual_list = comparison_res.get('OCR_Input', {}).get('individualCusInfo', [])
                total_fields = 0

                for individual in individual_list:

                    field_list = []
                    if individual.get('idType') in consts.ID_TYPE_COMPARE:
                        total_fields += 4
                        if not successful_at_this_level:
                            for field_name, _, _, _, result_field in consts.ITPRC:
                                if individual.get(result_field) != consts.RESULT_Y:
                                    field_list.append(field_name)

                    if individual.get('secondIdType') in consts.SECOND_ID_TYPE_COMPARE:
                        total_fields += 1
                        if not successful_at_this_level:
                            if individual.get(consts.SECOND_ID_RES) != consts.RESULT_Y:
                                field_list.append(consts.SECOND_ID_FIELD)

                    if individual.get('customerType') == consts.CUSTOMER_TYPE[5]:
                        total_fields += 3
                        if not successful_at_this_level:
                            for field_name, _, _, _, result_field in consts.TCSEP:
                                if individual.get(result_field) != consts.RESULT_Y:
                                    field_list.append(field_name)

                    if len(field_list) > 0:
                        field_failed['individualCusInfo'].append(';'.join(field_list))

                corporate_res = comparison_res.get('OCR_Input', {}).get('corporateCusInfo')
                if corporate_res is not None:
                    total_fields += 8
                    if not successful_at_this_level:
                        corporate_field_list = []
                        for field_name, _, _, _, result_field in consts.TCCOR:
                            if corporate_res.get(result_field) != consts.RESULT_Y:
                                corporate_field_list.append(field_name)
                        if len(corporate_field_list) > 0:
                            field_failed['corporateCusInfo'].append(';'.join(corporate_field_list))

                used_car_res = comparison_res.get('OCR_Input', {}).get('usedCarInfo')
                if used_car_res is not None:
                    total_fields += 3
                    if not successful_at_this_level:
                        used_car_field_list = []
                        for field_name, _, _, _, result_field in consts.PCUSD_MVC:
                            if used_car_res.get(result_field) != consts.RESULT_Y:
                                used_car_field_list.append(field_name)
                        if len(used_car_field_list) > 0:
                            field_failed['usedCarInfo'].append(';'.join(used_car_field_list))

                if not successful_at_this_level:
                    reason_list = []
                    for key, value in field_failed.items():
                        if len(value) > 0:
                            value_str = json.dumps(value)
                            reason_list.append('{0}: {1}'.format(key, value_str))
                    failure_reason = '、'.join(reason_list)

                else:
                    failure_reason = empty_str

            request_trigger = RequestTrigger.SUBMITING.value if ocr_res_id is None else RequestTrigger.UPLOADING.value
            report_class = HILCompareReport if application_entity == consts.HIL_PREFIX else AFCCompareReport
            report_class.objects.create(
                case_number=application_id,
                request_team=RequestTeam.ACCEPTANCE.value,
                request_trigger=request_trigger,
                transaction_start=start_time,
                transaction_end=end_time,
                successful_at_this_level=successful_at_this_level,
                failure_reason=failure_reason,
                process_name=ProcessName.CACOMPARE.value,
                total_fields=total_fields,
                workflow_name=last_obj.customer_type,
            )
            compare_log.info(
                '{0} [CA] [report save success] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                    log_base, application_entity, application_id, ocr_res_id))
        except Exception as e:
            compare_log.error('{0} [CA] [report save error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                              '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                                   traceback.format_exc()))


def get_se_cms_compare_info_auto(last_obj, application_entity):
    cms_info = json.loads(last_obj.content)

    compare_info = {}

    individual_info_dict = {}
    main_role_info = {}
    company_info_list = []

    # 个人信息证件---------------------------------------------------------------------------------------------------------
    # province = cms_info.get('province', '')
    for individual_info in cms_info.get('applicantInformation', []):
        all_id_num = []

        license_dict = {}

        customer_name = individual_info.get('name', '')
        legal_name = individual_info.get('legalRepName', '')
        # establishment_date = individual_info.get('establishmentDate', '')
        # date_of_birth = individual_info.get('dateOfBirth', '')

        for id_info in individual_info.get('IDInformation', []):
            if id_info.get('idType') in consts.SE_CMS_FIRST_ID_FIELD_MAPPING:
                license_en, is_prc = consts.SE_CMS_FIRST_ID_FIELD_MAPPING[id_info['idType']]
                # ['customerName', 'idNum', 'dateOfBirth', 'idExpiryDate', 'hukouProvince']
                id_num = decode_des(id_info.get('idNum', ''), des_key)
                field_input = [('customerName', customer_name), ('idNum', id_num),
                               ('idExpiryDate', id_info.get('idExpiryDate', ''))]
                if is_prc:
                    #     field_input.append(('hukouProvince', province))
                    #     field_input.append(('真伪', consts.IC_RES_MAPPING.get(1)))
                    license_dict[license_en] = field_input
                all_id_num.append(id_num)
            # 营业执照 --------------------------------------------------------------------------------------------------
            elif id_info.get('idType') in ['Unified Social Credit Code', 'Tax Number', 'Business License Number']:
                # ['companyName', 'legalRepName', 'businessLicenseNo', 'organizationCreditCode',
                #  'taxRegistrationCertificateNo', 'establishmentDate', 'businessLicenseDueDate']
                id_num = decode_des(id_info.get('idNum', ''), des_key)
                # bl_field_input = [
                #     ('companyName', customer_name),
                #     ('legalRepName', legal_name),
                #     ('businessLicenseNo', id_num),
                #     ('organizationCreditCode', id_num),
                #     ('taxRegistrationCertificateNo', id_num),
                #     ('establishmentDate', establishment_date),
                #     ('businessLicenseDueDate', id_info.get('idExpiryDate', '')),
                # ]
                # license_dict[consts.BL_EN] = bl_field_input
                all_id_num.append(id_num)
                if individual_info.get('customersubType', '') == 'Corporate':
                    company_info_list.append((customer_name, id_num, legal_name))

        # SME营业执照---------------------------------------------------------------------------------------------------
        # if individual_info.get('customersubType', '').startswith('Self Employed'):
        #     sep_field_input = [
        #         ('legalRepName', customer_name),
        #         ('businessLicenseDueDate', ''),
        #     ]
        #     license_dict[consts.SME_BL_EN] = sep_field_input

        if len(all_id_num) > 0:
            main_role_info.setdefault(individual_info['applicantType'], []).append(
                (customer_name, '、'.join(all_id_num), all_id_num[0])
            )

        if len(license_dict) > 0:
            individual_info_dict.setdefault(individual_info['applicantType'], []).append(license_dict)

    compare_info['applicantInformation'] = individual_info_dict

    main_name = main_num = hmh_name = hmh_id = ''
    for applicant_type in consts.APPLICANT_TYPE_ORDER:
        if applicant_type in main_role_info:
            # main_name, main_num, _ = main_role_info[applicant_type][0]
            hmh_name, _, hmh_id = main_role_info[applicant_type][0]
            break

    # dda_name_list = []
    # dda_num_list = []
    # for applicant_type in consts.APPLICANT_TYPE_ORDER[:2]:
    #     if applicant_type in main_role_info:
    #         for dda_name_part, _, dda_num_part in main_role_info[applicant_type]:
    #             dda_name_list.append(dda_name_part)
    #             dda_num_list.append(dda_num_part)
    # dda_name = '、'.join(dda_name_list)
    # dda_num = '、'.join(dda_num_list)
    # del main_role_info

    if len(company_info_list) > 0:
        company_info = company_info_list[0]
    else:
        company_info = None

    vehicle_info = {}
    vehicle_field_input = []
    vehicle_status = cms_info.get('vehicleStatus', '')
    first_submission_date = cms_info.get('submissionDate', '')
    vin_no = cms_info.get('vehicleInformation', {}).get('vinNo', '')
    amount = str(cms_info.get('financialInformation', {}).get('vehiclePrice', '0.0'))
    # 新车发票----------------------------------------------------------------------------------------------------------
    if vehicle_status == 'New':
        vehicle_field_input.append(('vinNo', vin_no))
        vehicle_field_input.append(
            ('dealer', '、'.join([cms_info.get('dealerName', ''), cms_info.get('fapiaoIssuerDealer', '')])))
        vehicle_field_input.append(('vehicleTransactionAmount', amount))

        if isinstance(company_info, tuple):
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
        else:
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], hmh_name))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], hmh_id))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[2], first_submission_date))
        # vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[3], consts.SE_STAMP_VALUE))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[4], consts.SE_FPL_VALUE))
        bhsj = float(amount) / 1.13
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[5], consts.SPLIT_STR.join([
            format(bhsj, '.2f'),
            format(float(amount) - bhsj, '.2f'),
            consts.RESULT_Y
        ])))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[6], consts.SE_LAYOUT_VALUE))
        vehicle_info[consts.MVI_EN] = vehicle_field_input
        compare_info['vehicleInfo'] = vehicle_info
    # 二手车发票、交易凭证、绿本------------------------------------------------------------------------------------------
    # else:
    #     gb_field_input = [
    #         ('vinNo', vin_no),
    #     ]
    #     gb34_field_input = []
    #     jypz_field_input = []
    #     vehicle_field_input.append(('vinNo', vin_no))
    #     vehicle_field_input.append(('vehicleTransactionAmount', amount))
    #     if isinstance(company_info, tuple):
    #         vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
    #         vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
    #         jypz_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
    #         jypz_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
    #         gb34_field_input.append((consts.SE_GB_USED_FIELD[0], company_info[0]))
    #         gb34_field_input.append((consts.SE_GB_USED_FIELD[1], company_info[1]))
    #     else:
    #         vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], main_name))
    #         vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], main_num))
    #         jypz_field_input.append((consts.SE_NEW_ADD_FIELD[0], main_name))
    #         jypz_field_input.append((consts.SE_NEW_ADD_FIELD[1], main_num))
    #         gb34_field_input.append((consts.SE_GB_USED_FIELD[0], main_name))
    #         gb34_field_input.append((consts.SE_GB_USED_FIELD[1], main_num))
    #     gb34_field_input.append((consts.SE_GB_USED_FIELD[2], first_submission_date))
    #     vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[2], first_submission_date))
    #     # vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[3], consts.SE_STAMP_VALUE))
    #     jypz_field_input.append(('vinNo', vin_no))
    #     jypz_field_input.append(('vehicleTransactionAmount', amount))
    #     jypz_field_input.append((consts.SE_GB_USED_FIELD[-1], first_submission_date))
    #
    #     vehicle_info[consts.MVC_EN] = gb_field_input
    #     vehicle_info[consts.MVC34_EN] = gb34_field_input
    #     if not detect_list[0]:
    #         vehicle_info[consts.UCI_EN] = vehicle_field_input
    #     if not detect_list[1]:
    #         vehicle_info[consts.JYPZ_EN] = jypz_field_input
    #     if detect_list[0] and detect_list[1]:
    #         vehicle_info[consts.UCI_EN] = vehicle_field_input
    # compare_info['vehicleInfo'] = vehicle_info

    # 银行卡-------------------------------------------------------------------------------------------------------
    bank_info = {}
    bank_name = cms_info.get('bankAccountDetails', {}).get('bankName', '')
    account_no = decode_des(cms_info.get('bankAccountDetails', {}).get('accountNo', ''), des_key)
    account_holder_name = cms_info.get('bankAccountDetails', {}).get('accountHolderName', '')
    is_gsyh = True if '工商' in bank_name else False

    if isinstance(company_info, tuple) and company_info[0] == account_holder_name:
        pass
    else:
        bank_field_input = [
            ('accountNo', account_no),
            ('bankName', bank_name),
            ('type', consts.BC_TYPE_VALUE),
        ]
        bank_info[consts.BC_EN] = bank_field_input

    # DDA------------------------------------------------------------------------------------------------------------
    # if is_gsyh or not detect_list[-1]:
    #     dda_field_input = [
    #         ('applicationId(1)', last_obj.application_id),
    #         ('applicationId(2)', last_obj.application_id),
    #         ('bankName', bank_name),
    #         ('companyName',
    #          consts.HIL_COMPANY_NAME if application_entity in consts.HIL_SET else consts.AFC_COMPANY_NAME),
    #         ('customerName', dda_name),
    #         ('idNum', dda_num),
    #         ('accountHolderName', account_holder_name),
    #         ('accountNo', account_no),
    #     ]
    #     bank_info[consts.DDA_EN] = dda_field_input
    # if len(bank_info) > 0:
    #     compare_info['bankInfo'] = bank_info

    # 银行流水 --------------------------------------------------------------------
    if cms_info.get('autoApprovedDetails', {}).get('aaType', '') in ['CAA1', 'CAA2']:
        bs_role_list = []
        for applicant_type in consts.APPLICANT_TYPE_ORDER[:2]:
            if applicant_type in main_role_info:
                for bs_role, _, _ in main_role_info[applicant_type]:
                    bs_role_list.append(bs_role)

        bs_info = dict()
        bs_field_input = [
            (consts.SE_BS_FIELD[0], bs_role_list),
            (consts.SE_BS_FIELD[1], first_submission_date),
            (consts.SE_BS_FIELD[2], 90),
        ]

        dbr_bs_role_list = []
        for dbr_bs_role, _, _ in main_role_info.get(consts.APPLICANT_TYPE_ORDER[2], []):
            dbr_bs_role_list.append(dbr_bs_role)

        if len(dbr_bs_role_list) >= 1:
            bs_field_input.extend([
                (consts.SE_BS_FIELD[3], dbr_bs_role_list[0]),
                (consts.SE_BS_FIELD[4], first_submission_date),
                (consts.SE_BS_FIELD[5], 90),
            ])
            if len(dbr_bs_role_list) >= 2:
                bs_field_input.extend([
                    (consts.SE_BS_FIELD[6], dbr_bs_role_list[1]),
                    (consts.SE_BS_FIELD[7], first_submission_date),
                    (consts.SE_BS_FIELD[8], 90),
                ])
        bs_info[consts.BS_EN] = bs_field_input
        compare_info['Bank Statement'] = bs_info

    # 抵押登记豁免函----------------------------------------------------------------------------------------------------
    other_info = {}
    full_no = cms_info.get('settlemnetVerification', {}).get('applicationNo', '')
    if cms_info.get('mortgageType', '') == 'Mortgage Free' or cms_info.get('mortgageType', '') == 'MortgageFree':
        hmh_field_input = [
            (consts.SE_HMH_FIELD[0], hmh_name),
            (consts.SE_HMH_FIELD[1], hmh_id),
            (consts.SE_HMH_FIELD[2], full_no),
            (consts.SE_HMH_FIELD[3], cms_info.get('financeCompany', '')),
            (consts.SE_HMH_FIELD[4], consts.SE_STAMP_VALUE),
        ]
        other_info[consts.HMH_EN] = hmh_field_input

    # ASP -------------------------------------------------------------------------------------------------------
    asp_list = []
    gzs_status = consts.GZS_STATUS[1]
    gzs_list = [gzs_status]
    gzs_price = '0.00'
    is_asp = False
    # insurance_price = None
    if str(cms_info.get('financialInformation', {}).get('associatedServicePrincipal', '0.00')) != '0.00':
        is_asp = True
        # for asp_info in cms_info.get('associatedServices', []):
        for asp_info in cms_info.get('associatedServices', {}).get('SubassociatedServices', []):
            tmp_asp_name = asp_info.get('associatedServices')
            if isinstance(tmp_asp_name, str) and len(tmp_asp_name) > 0:
                if gzs_status == consts.GZS_STATUS[1] and tmp_asp_name.find(consts.GZS_NAME) != -1:
                    gzs_status = consts.GZS_STATUS[2]
                    gzs_price = asp_info.get('price', '0.00')
                asp_list.append(
                    (
                        tmp_asp_name,
                        asp_info.get('price', '0.00'),
                        asp_info.get('financed', '0.00')
                    )
                )
                # 保单费合计
                # if tmp_asp_name.find('机动车辆保险') != -1:
                #     insurance_price = asp_info.get('price', '0.00')

        fin_total = 0
        # fin_total_tmp = cms_info.get('associatedServices', {}).get('financed total', '0.00')
        # fin_total = '0.00' if fin_total_tmp.strip() == '' else fin_total_tmp
        for asp_name, _, asp_fin in asp_list:
            if gzs_status == consts.GZS_STATUS[2] and asp_name.find(consts.GZS_NAME) == -1:
                gzs_status = consts.GZS_STATUS[0]
            fin_total += float(asp_fin)
        asp_list.append(
            (
                consts.ASP_SUM_NAME,
                '',
                # fin_total,
                format(fin_total, '.2f'),
            )
        )

        # CMS Vehicle Price / 1.13 * 10 %
        gzs_list = [gzs_status]
        if gzs_status != consts.GZS_STATUS[1]:
            gzs_value = float(amount) * 0.1 / 1.13
            gzs_list.append(gzs_value)
            gzs_list.append(float(gzs_price))

    # 保单 -----------------------------------------------------------------------------------------------------------
    # is_insurance = 0
    fp_campaign = cms_info.get('fpCampaign', '')
    # insurance_type = cms_info.get('insuranceDetails', {}).get('insuranceType', '')
    # if insurance_type == 'Waive Insurance' and isinstance(insurance_price, str):
    #     is_insurance = 1
    # elif insurance_type == 'Comprehensive Insurance':
    #     is_insurance = 2
    # if is_insurance != 0:
    #     if fp_campaign.find('OCU') == -1:
    #         ssx_amount = amount
    #     else:
    #         ssx_amount = format(float(amount) * 0.8, '.2f')
    #     if fp_campaign.find('Joy_Plus') == -1 or fp_campaign.find('JoyPlus') == -1:
    #         dszx_amount = '200000'
    #     else:
    #         dszx_amount = '500000'
    #     bd_field_input = [
    #         (consts.SE_BD_FIELD[0], hmh_name),
    #         (consts.SE_BD_FIELD[1], hmh_id),
    #         (consts.SE_BD_FIELD[2], vin_no),
    #         (consts.SE_BD_FIELD[3], ssx_amount),
    #         (consts.SE_BD_FIELD[4], dszx_amount),
    #         (consts.SE_BD_FIELD[5], consts.JDMPV_VALUE),
    #         (consts.SE_BD_FIELD[6], cms_info.get('insuranceDetails', {}).get('startDate', '')),
    #         (consts.SE_BD_FIELD[7], cms_info.get('insuranceDetails', {}).get('endDate', '')),
    #         (consts.SE_BD_FIELD[8], consts.SE_STAMP_VALUE),
    #         (consts.SE_BD_FIELD[9], consts.SE_STAMP_VALUE),
    #     ]
    #     if is_insurance == 1:
    #         bd_field_input.append((consts.SE_BD_FIELD[10], insurance_price))
    #     other_info[consts.BD_EN] = bd_field_input

    if len(other_info) > 0:
        compare_info['other'] = other_info

    schedule_list = []
    total_amount = 0
    for schedule_dict in cms_info.get('paymentSchedule', []):
        tmp_str = "{1}{0}{2}".format(consts.SPLIT_STR, str(schedule_dict.get('no', '')),
                                     str(schedule_dict.get('grossRentalAmount', '')))
        schedule_list.append(tmp_str)
        total_amount += float(schedule_dict.get('grossRentalAmount', '0.0'))
    schedule_list_str = consts.SCHEDULE_SPLIT_STR.join(schedule_list)

    online_sign = cms_info.get('contractSource', 'Online Sign') == 'Online Sign'

    contract_info = {}
    if application_entity in consts.HIL_SET:
        # HIL合同  售后回租合同 --------------------------------------------------------------------------------------
        hil_contract_1_input = [
            (consts.SE_HIL_CON_1_FIELD[0], [full_no] if online_sign else full_no),
            (consts.SE_HIL_CON_1_FIELD[1], full_no),
            (consts.SE_HIL_CON_1_FIELD[2], vin_no),
            (consts.SE_HIL_CON_1_FIELD[3], cms_info.get('dealerName', '')),
            (consts.SE_HIL_CON_1_FIELD[4], amount),
            (consts.SE_HIL_CON_1_FIELD[5],
             str(cms_info.get('financialInformation', {}).get('originationPrincipal', '0.0'))),
            (consts.SE_HIL_CON_1_FIELD[6], str(cms_info.get('terms', '0'))),
            (consts.SE_HIL_CON_1_FIELD[7], schedule_list_str),
            (consts.SE_HIL_CON_1_FIELD[11], account_no),
            (consts.SE_HIL_CON_1_FIELD[12], account_holder_name),
            (consts.SE_HIL_CON_1_FIELD[13], bank_name),
        ]

        if is_asp:
            hil_contract_1_input.append((consts.SE_HIL_CON_1_FIELD[8], asp_list))
            hil_contract_1_input.append((consts.SE_HIL_CON_1_FIELD[9], gzs_list))

        if isinstance(company_info, tuple):
            hil_contract_1_input.append((consts.SE_HIL_CON_1_FIELD[10], company_info[2]))

        for key, app_type, id_idx, field_idx, is_force, e_write in consts.ROLE_LIST_1:
            if not e_write and not online_sign:
                continue
            is_find = False
            if app_type in main_role_info:
                if len(main_role_info[app_type]) >= id_idx + 1:
                    is_find = True
                    if isinstance(field_idx, int):
                        hil_contract_1_input.append((key, main_role_info[app_type][id_idx][field_idx]))
                    else:
                        hil_contract_1_input.append((key, field_idx))
            if not is_find and is_force:
                hil_contract_1_input.append((key, empty_str))
        contract_info[consts.HIL_CONTRACT_1_EN] = hil_contract_1_input

        # HIL合同  车辆处置协议 --------------------------------------------------------------------------------------
        if fp_campaign.find('Joy_Select') != -1 or fp_campaign.find('JoySelect') != -1:
            hil_contract_3_input = [
                (consts.SE_HIL_CON_3_FIELD[0], [full_no] if online_sign else full_no),
                (consts.SE_HIL_CON_3_FIELD[1], hmh_name),
                (consts.SE_HIL_CON_3_FIELD[2], hmh_id),
                (consts.SE_HIL_CON_3_FIELD[3], cms_info.get('dealerName', '')),
                (consts.SE_HIL_CON_3_FIELD[4], full_no),
                (consts.SE_HIL_CON_3_FIELD[5], hmh_name),
                (consts.SE_HIL_CON_3_FIELD[6], hmh_id),
            ]
            if online_sign:
                hil_contract_3_input.append((consts.SE_HIL_CON_3_FIELD[7], hmh_name))
            contract_info[consts.HIL_CONTRACT_3_EN] = hil_contract_3_input

        # HIL合同  车辆租赁抵押合同 --------------------------------------------------------------------------------------
        hil_contract_2_input = [
            (consts.SE_HIL_CON_2_FIELD[0], full_no),
            (consts.SE_HIL_CON_2_FIELD[1], full_no),
            (consts.SE_HIL_CON_2_FIELD[2], vin_no),
            (consts.SE_HIL_CON_2_FIELD[3], format(total_amount, '.2f')),
            (consts.SE_HIL_CON_2_FIELD[4], str(cms_info.get('terms', '0'))),
        ]

        for key, app_type, id_idx, field_idx, is_force, e_write, co_skip in consts.ROLE_LIST_2:
            if co_skip and isinstance(company_info, tuple):
                continue
            if not e_write and not online_sign:
                continue
            is_find = False
            if app_type in main_role_info:
                if len(main_role_info[app_type]) >= id_idx + 1:
                    is_find = True
                    if isinstance(field_idx, int):
                        hil_contract_2_input.append((key, main_role_info[app_type][id_idx][field_idx]))
                    else:
                        hil_contract_2_input.append((key, field_idx))
            if not is_find and is_force:
                hil_contract_2_input.append((key, empty_str))
        contract_info[consts.HIL_CONTRACT_2_EN] = hil_contract_2_input
        compare_info['contract'] = contract_info
        return compare_info, cms_info.get('autoApprovedDetails', {}).get('aaType', ''), is_gsyh
    else:
        # AFC合同------------------------------------------------------------------------------------------------------
        vehicle_principal_str = str(cms_info.get('financialInformation', {}).get('vehiclePrincipal', '0.0'))
        afc_contract_input = [
            (consts.SE_AFC_CON_FIELD[0], full_no),
            (consts.SE_AFC_CON_FIELD[1], amount),
            (consts.SE_AFC_CON_FIELD[2], vin_no),
            (consts.SE_AFC_CON_FIELD[3],
             str(cms_info.get('financialInformation', {}).get('originationPrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[4], str(cms_info.get('terms', '0'))),
            (consts.SE_AFC_CON_FIELD[5], vehicle_principal_str),
            (consts.SE_AFC_CON_FIELD[6],
             str(cms_info.get('financialInformation', {}).get('associatedServicePrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[7], amount),
            (consts.SE_AFC_CON_FIELD[8], vin_no),
            (consts.SE_AFC_CON_FIELD[9], cms_info.get('dealerName', '')),
            (consts.SE_AFC_CON_FIELD[10],
             str(cms_info.get('financialInformation', {}).get('originationPrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[11], vehicle_principal_str),
            (consts.SE_AFC_CON_FIELD[12],
             str(cms_info.get('financialInformation', {}).get('associatedServicePrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[13], str(cms_info.get('terms', '0'))),
            (consts.SE_AFC_CON_FIELD[14], account_no),
            (consts.SE_AFC_CON_FIELD[15], account_holder_name),
            (consts.SE_AFC_CON_FIELD[16], bank_name),
            (consts.SE_AFC_CON_FIELD[17], schedule_list_str),
        ]

        if is_asp:
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[20], asp_list))
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[22], asp_list))
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[21], gzs_list))
        else:
            afc_contract_input.pop(5)
            afc_contract_input.pop(5)
            afc_contract_input.pop(9)
            afc_contract_input.pop(9)

        # '借款人签字及时间', 'Borrower', 0, 0, True
        for key, app_type, id_idx, field_idx, is_force, e_write in consts.ROLE_LIST:
            if not e_write and not online_sign:
                continue
            is_find = False
            if app_type in main_role_info:
                if len(main_role_info[app_type]) >= id_idx + 1:
                    is_find = True
                    if isinstance(field_idx, int):
                        afc_contract_input.append((key, main_role_info[app_type][id_idx][field_idx]))
                    else:
                        afc_contract_input.append((key, field_idx))
            if not is_find and is_force:
                afc_contract_input.append((key, empty_str))

        if online_sign:
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[18], consts.SE_STAMP_VALUE))
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[19], empty_str))

        contract_info[consts.AFC_CONTRACT_EN] = afc_contract_input
        compare_info['contract'] = contract_info
        return compare_info, cms_info.get('autoApprovedDetails', {}).get('aaType', ''), is_gsyh


def get_se_cms_compare_info(last_obj, application_entity, detect_list):
    cms_info = json.loads(last_obj.content)

    compare_info = {}

    individual_info_dict = {}
    main_role_info = {}
    company_info_list = []

    # 个人信息证件---------------------------------------------------------------------------------------------------------
    # province = cms_info.get('province', '')
    for individual_info in cms_info.get('applicantInformation', []):
        all_id_num = []

        license_dict = {}

        customer_name = individual_info.get('name', '').strip()
        legal_name = individual_info.get('legalRepName', '')
        establishment_date = individual_info.get('establishmentDate', '')
        # date_of_birth = individual_info.get('dateOfBirth', '')

        for id_info in individual_info.get('IDInformation', []):
            if id_info.get('idType') in consts.SE_CMS_FIRST_ID_FIELD_MAPPING:
                license_en, is_prc = consts.SE_CMS_FIRST_ID_FIELD_MAPPING[id_info['idType']]
                # ['customerName', 'idNum', 'dateOfBirth', 'idExpiryDate', 'hukouProvince']
                id_num = decode_des(id_info.get('idNum', ''), des_key)
                field_input = [('customerName', customer_name), ('idNum', id_num),
                               ('idExpiryDate', id_info.get('idExpiryDate', ''))]
                # if is_prc:
                #     field_input.append(('hukouProvince', province))
                #     field_input.append(('真伪', consts.IC_RES_MAPPING.get(1)))
                license_dict[license_en] = field_input
                all_id_num.append(id_num)
            # 营业执照 --------------------------------------------------------------------------------------------------
            elif id_info.get('idType') in ['Unified Social Credit Code', 'Tax Number', 'Business License Number']:
                # ['companyName', 'legalRepName', 'businessLicenseNo', 'organizationCreditCode',
                #  'taxRegistrationCertificateNo', 'establishmentDate', 'businessLicenseDueDate']
                id_num = decode_des(id_info.get('idNum', ''), des_key)
                bl_field_input = [
                    ('companyName', customer_name),
                    ('legalRepName', legal_name),
                    ('businessLicenseNo', id_num),
                    ('organizationCreditCode', id_num),
                    ('taxRegistrationCertificateNo', id_num),
                    ('establishmentDate', establishment_date),
                    ('businessLicenseDueDate', id_info.get('idExpiryDate', '')),
                ]
                license_dict[consts.BL_EN] = bl_field_input
                all_id_num.append(id_num)
                if individual_info.get('customersubType', '') == 'Corporate':
                    company_info_list.append((customer_name, id_num, legal_name))

        # SME营业执照---------------------------------------------------------------------------------------------------
        # if individual_info.get('customersubType', '').startswith('Self Employed'):
        #     sep_field_input = [
        #         ('legalRepName', customer_name),
        #         ('businessLicenseDueDate', ''),
        #     ]
        #     license_dict[consts.SME_BL_EN] = sep_field_input

        if len(all_id_num) > 0:
            main_role_info.setdefault(individual_info['applicantType'], []).append(
                (customer_name, '、'.join(all_id_num), all_id_num[0])
            )

        if len(license_dict) > 0:
            individual_info_dict.setdefault(individual_info['applicantType'], []).append(license_dict)

    compare_info['applicantInformation'] = individual_info_dict

    main_name = main_num = hmh_name = hmh_id = ''
    for applicant_type in consts.APPLICANT_TYPE_ORDER:
        if applicant_type in main_role_info:
            main_name, main_num, _ = main_role_info[applicant_type][0]
            hmh_name, _, hmh_id = main_role_info[applicant_type][0]
            break

    dda_name_list = []
    dda_num_list = []
    for applicant_type in consts.APPLICANT_TYPE_ORDER[:2]:
        if applicant_type in main_role_info:
            for dda_name_part, _, dda_num_part in main_role_info[applicant_type]:
                dda_name_list.append(dda_name_part)
                dda_num_list.append(dda_num_part)
    dda_name = '、'.join(dda_name_list)
    dda_num = '、'.join(dda_num_list)
    # del main_role_info

    if len(company_info_list) > 0:
        company_info = company_info_list[0]
    else:
        company_info = None

    vehicle_info = {}
    vehicle_field_input = []
    vehicle_status = cms_info.get('vehicleStatus', '')
    first_submission_date = cms_info.get('submissionDate', '')
    vin_no = cms_info.get('vehicleInformation', {}).get('vinNo', '')
    amount = str(cms_info.get('financialInformation', {}).get('vehiclePrice', '0.0'))
    # 新车发票----------------------------------------------------------------------------------------------------------
    if vehicle_status == 'New':
        vehicle_field_input.append(('vinNo', vin_no))
        vehicle_field_input.append(('dealer', '、'.join([cms_info.get('dealerName', ''), cms_info.get('fapiaoIssuerDealer', '')])))
        vehicle_field_input.append(('vehicleTransactionAmount', amount))

        if isinstance(company_info, tuple):
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
        else:
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], hmh_name))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], hmh_id))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[2], first_submission_date))
        # vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[3], consts.SE_STAMP_VALUE))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[4], consts.SE_FPL_VALUE))
        bhsj = float(amount) / 1.13
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[5], consts.SPLIT_STR.join([
            format(bhsj, '.2f'),
            format(float(amount) - bhsj, '.2f'),
            consts.RESULT_Y
        ])))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[6], consts.SE_LAYOUT_VALUE))
        vehicle_info[consts.MVI_EN] = vehicle_field_input
    # 二手车发票、交易凭证、绿本------------------------------------------------------------------------------------------
    else:
        gb_field_input = [
            ('vinNo', vin_no),
        ]
        gb34_field_input = []
        jypz_field_input = []
        vehicle_field_input.append(('vinNo', vin_no))
        vehicle_field_input.append(('vehicleTransactionAmount', amount))
        if isinstance(company_info, tuple):
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[0], company_info[0]))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[1], company_info[1]))
        else:
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], main_name))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], main_num))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[0], main_name))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[1], main_num))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[0], main_name))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[1], main_num))
        gb34_field_input.append((consts.SE_GB_USED_FIELD[2], first_submission_date))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[2], first_submission_date))
        # vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[3], consts.SE_STAMP_VALUE))
        jypz_field_input.append(('vinNo', vin_no))
        jypz_field_input.append(('vehicleTransactionAmount', amount))
        jypz_field_input.append((consts.SE_GB_USED_FIELD[-1], first_submission_date))

        vehicle_info[consts.MVC_EN] = gb_field_input
        vehicle_info[consts.MVC34_EN] = gb34_field_input
        if not detect_list[0]:
            vehicle_info[consts.UCI_EN] = vehicle_field_input
        if not detect_list[1]:
            vehicle_info[consts.JYPZ_EN] = jypz_field_input
        if detect_list[0] and detect_list[1]:
            vehicle_info[consts.UCI_EN] = vehicle_field_input
    compare_info['vehicleInfo'] = vehicle_info

    # 银行卡-------------------------------------------------------------------------------------------------------
    bank_info = {}
    bank_name = cms_info.get('bankAccountDetails', {}).get('bankName', '')
    account_no = decode_des(cms_info.get('bankAccountDetails', {}).get('accountNo', ''), des_key)
    account_holder_name = cms_info.get('bankAccountDetails', {}).get('accountHolderName', '')
    is_gsyh = True if '工商' in bank_name else False

    if isinstance(company_info, tuple) and company_info[0] == account_holder_name:
        pass
    else:
        bank_field_input = [
            ('accountNo', account_no),
            ('bankName', bank_name),
            ('type', consts.BC_TYPE_VALUE),
        ]
        bank_info[consts.BC_EN] = bank_field_input

    # DDA------------------------------------------------------------------------------------------------------------
    if is_gsyh or not detect_list[-1]:
        dda_field_input = [
            ('applicationId(1)', last_obj.application_id),
            ('applicationId(2)', last_obj.application_id),
            ('bankName', bank_name),
            ('companyName', consts.HIL_COMPANY_NAME if application_entity in consts.HIL_SET else consts.AFC_COMPANY_NAME),
            ('customerName', dda_name),
            ('idNum', dda_num),
            ('accountHolderName', account_holder_name),
            ('accountNo', account_no),
        ]
        bank_info[consts.DDA_EN] = dda_field_input
    if len(bank_info) > 0:
        compare_info['bankInfo'] = bank_info

    # 银行流水 --------------------------------------------------------------------
    if cms_info.get('autoApprovedDetails', {}).get('aaType', '') in ['CAA1', 'CAA2']:
        bs_role_list = []
        for applicant_type in consts.APPLICANT_TYPE_ORDER[:2]:
            if applicant_type in main_role_info:
                for bs_role, _, _ in main_role_info[applicant_type]:
                    bs_role_list.append(bs_role)

        bs_info = dict()
        bs_field_input = [
            (consts.SE_BS_FIELD[0], bs_role_list),
            (consts.SE_BS_FIELD[1], first_submission_date),
            (consts.SE_BS_FIELD[2], 90),
        ]

        dbr_bs_role_list = []
        for dbr_bs_role, _, _ in main_role_info.get(consts.APPLICANT_TYPE_ORDER[2], []):
            dbr_bs_role_list.append(dbr_bs_role)

        if len(dbr_bs_role_list) >= 1:
            bs_field_input.extend([
                (consts.SE_BS_FIELD[3], dbr_bs_role_list[0]),
                (consts.SE_BS_FIELD[4], first_submission_date),
                (consts.SE_BS_FIELD[5], 90),
            ])
            if len(dbr_bs_role_list) >= 2:
                bs_field_input.extend([
                    (consts.SE_BS_FIELD[6], dbr_bs_role_list[1]),
                    (consts.SE_BS_FIELD[7], first_submission_date),
                    (consts.SE_BS_FIELD[8], 90),
                ])
        bs_info[consts.BS_EN] = bs_field_input
        compare_info['Bank Statement'] = bs_info

    # 抵押登记豁免函----------------------------------------------------------------------------------------------------
    other_info = {}
    full_no = cms_info.get('settlemnetVerification', {}).get('applicationNo', '')
    if cms_info.get('mortgageType', '') == 'Mortgage Free' or cms_info.get('mortgageType', '') == 'MortgageFree':
        hmh_field_input = [
            (consts.SE_HMH_FIELD[0], hmh_name),
            (consts.SE_HMH_FIELD[1], hmh_id),
            (consts.SE_HMH_FIELD[2], full_no),
            (consts.SE_HMH_FIELD[3], cms_info.get('financeCompany', '')),
            (consts.SE_HMH_FIELD[4], consts.SE_STAMP_VALUE),
        ]
        other_info[consts.HMH_EN] = hmh_field_input

    # ASP -------------------------------------------------------------------------------------------------------
    asp_list = []
    gzs_status = consts.GZS_STATUS[1]
    gzs_list = [gzs_status]
    gzs_price = '0.00'
    is_asp = False
    insurance_price = None
    if str(cms_info.get('financialInformation', {}).get('associatedServicePrincipal', '0.00')) != '0.00':
        is_asp = True
        # for asp_info in cms_info.get('associatedServices', []):
        for asp_info in cms_info.get('associatedServices', {}).get('SubassociatedServices', []):
            tmp_asp_name = asp_info.get('associatedServices')
            if isinstance(tmp_asp_name, str) and len(tmp_asp_name) > 0:
                if gzs_status == consts.GZS_STATUS[1] and tmp_asp_name.find(consts.GZS_NAME) != -1:
                    gzs_status = consts.GZS_STATUS[2]
                    gzs_price = asp_info.get('price', '0.00')
                asp_list.append(
                    (
                        tmp_asp_name,
                        asp_info.get('price', '0.00'),
                        asp_info.get('financed', '0.00')
                    )
                )
                # 保单费合计
                if tmp_asp_name.find('机动车辆保险') != -1:
                    insurance_price = asp_info.get('price', '0.00')

        fin_total = 0
        # fin_total_tmp = cms_info.get('associatedServices', {}).get('financed total', '0.00')
        # fin_total = '0.00' if fin_total_tmp.strip() == '' else fin_total_tmp
        for asp_name, _, asp_fin in asp_list:
            if gzs_status == consts.GZS_STATUS[2] and asp_name.find(consts.GZS_NAME) == -1:
                gzs_status = consts.GZS_STATUS[0]
            fin_total += float(asp_fin)
        asp_list.append(
            (
                consts.ASP_SUM_NAME,
                '',
                # fin_total,
                format(fin_total, '.2f'),
            )
        )

        # CMS Vehicle Price / 1.13 * 10 %
        gzs_list = [gzs_status]
        if gzs_status != consts.GZS_STATUS[1]:
            gzs_value = float(amount) * 0.1 / 1.13
            gzs_list.append(gzs_value)
            gzs_list.append(float(gzs_price))

    # 保单 -----------------------------------------------------------------------------------------------------------
    is_insurance = 0
    fp_campaign = cms_info.get('fpCampaign', '')
    insurance_type = cms_info.get('insuranceDetails', {}).get('insuranceType', '')
    if insurance_type == 'Waive Insurance' and isinstance(insurance_price, str):
        is_insurance = 1
    elif insurance_type == 'Comprehensive Insurance':
        is_insurance = 2
    if is_insurance != 0:
        if fp_campaign.find('OCU') == -1:
            ssx_amount = amount
        else:
            ssx_amount = format(float(amount) * 0.8, '.2f')
        if fp_campaign.find('Joy_Plus') == -1 or fp_campaign.find('JoyPlus') == -1:
            dszx_amount = '200000'
        else:
            dszx_amount = '500000'
        bd_field_input = [
            (consts.SE_BD_FIELD[0], hmh_name),
            (consts.SE_BD_FIELD[1], hmh_id),
            (consts.SE_BD_FIELD[2], vin_no),
            (consts.SE_BD_FIELD[3], ssx_amount),
            (consts.SE_BD_FIELD[4], dszx_amount),
            (consts.SE_BD_FIELD[5], consts.JDMPV_VALUE),
            (consts.SE_BD_FIELD[6], cms_info.get('insuranceDetails', {}).get('startDate', '')),
            (consts.SE_BD_FIELD[7], cms_info.get('insuranceDetails', {}).get('endDate', '')),
            (consts.SE_BD_FIELD[8], consts.SE_STAMP_VALUE),
            (consts.SE_BD_FIELD[9], consts.SE_STAMP_VALUE),
        ]
        if is_insurance == 1:
            bd_field_input.append((consts.SE_BD_FIELD[10], insurance_price))
        other_info[consts.BD_EN] = bd_field_input

    if len(other_info) > 0:
        compare_info['other'] = other_info

    schedule_list = []
    total_amount = 0
    for schedule_dict in cms_info.get('paymentSchedule', []):
        tmp_str = "{1}{0}{2}".format(consts.SPLIT_STR, str(schedule_dict.get('no', '')),
                                     str(schedule_dict.get('grossRentalAmount', '')))
        schedule_list.append(tmp_str)
        total_amount += float(schedule_dict.get('grossRentalAmount', '0.0'))
    schedule_list_str = consts.SCHEDULE_SPLIT_STR.join(schedule_list)

    online_sign = cms_info.get('contractSource', 'Online Sign') == 'Online Sign'

    contract_info = {}
    if application_entity in consts.HIL_SET:
        # HIL合同  售后回租合同 --------------------------------------------------------------------------------------
        hil_contract_1_input = [
            (consts.SE_HIL_CON_1_FIELD[0], [full_no] if online_sign else full_no),
            (consts.SE_HIL_CON_1_FIELD[1], full_no),
            (consts.SE_HIL_CON_1_FIELD[2], vin_no),
            (consts.SE_HIL_CON_1_FIELD[3], cms_info.get('dealerName', '')),
            (consts.SE_HIL_CON_1_FIELD[4], amount),
            (consts.SE_HIL_CON_1_FIELD[5], str(cms_info.get('financialInformation', {}).get('originationPrincipal', '0.0'))),
            (consts.SE_HIL_CON_1_FIELD[6], str(cms_info.get('terms', '0'))),
            (consts.SE_HIL_CON_1_FIELD[7], schedule_list_str),
            (consts.SE_HIL_CON_1_FIELD[11], account_no),
            (consts.SE_HIL_CON_1_FIELD[12], account_holder_name),
            (consts.SE_HIL_CON_1_FIELD[13], bank_name),
        ]

        if is_asp:
            hil_contract_1_input.append((consts.SE_HIL_CON_1_FIELD[8], asp_list))
            hil_contract_1_input.append((consts.SE_HIL_CON_1_FIELD[9], gzs_list))

        if isinstance(company_info, tuple):
            hil_contract_1_input.append((consts.SE_HIL_CON_1_FIELD[10], company_info[2]))

        for key, app_type, id_idx, field_idx, is_force, e_write in consts.ROLE_LIST_1:
            if not e_write and not online_sign:
                continue
            is_find = False
            if app_type in main_role_info:
                if len(main_role_info[app_type]) >= id_idx+1:
                    is_find = True
                    if isinstance(field_idx, int):
                        hil_contract_1_input.append((key, main_role_info[app_type][id_idx][field_idx]))
                    else:
                        hil_contract_1_input.append((key, field_idx))
            if not is_find and is_force:
                hil_contract_1_input.append((key, empty_str))
        contract_info[consts.HIL_CONTRACT_1_EN] = hil_contract_1_input

        # HIL合同  车辆处置协议 --------------------------------------------------------------------------------------
        if fp_campaign.find('Joy_Select') != -1 or fp_campaign.find('JoySelect') != -1:
            hil_contract_3_input = [
                (consts.SE_HIL_CON_3_FIELD[0], [full_no] if online_sign else full_no),
                (consts.SE_HIL_CON_3_FIELD[1], hmh_name),
                (consts.SE_HIL_CON_3_FIELD[2], hmh_id),
                (consts.SE_HIL_CON_3_FIELD[3], cms_info.get('dealerName', '')),
                (consts.SE_HIL_CON_3_FIELD[4], full_no),
                (consts.SE_HIL_CON_3_FIELD[5], hmh_name),
                (consts.SE_HIL_CON_3_FIELD[6], hmh_id),
            ]
            if online_sign:
                hil_contract_3_input.append((consts.SE_HIL_CON_3_FIELD[7], hmh_name))
            contract_info[consts.HIL_CONTRACT_3_EN] = hil_contract_3_input

        # HIL合同  车辆租赁抵押合同 --------------------------------------------------------------------------------------
        hil_contract_2_input = [
            (consts.SE_HIL_CON_2_FIELD[0], full_no),
            (consts.SE_HIL_CON_2_FIELD[1], full_no),
            (consts.SE_HIL_CON_2_FIELD[2], vin_no),
            (consts.SE_HIL_CON_2_FIELD[3], format(total_amount, '.2f')),
            (consts.SE_HIL_CON_2_FIELD[4], str(cms_info.get('terms', '0'))),
        ]

        for key, app_type, id_idx, field_idx, is_force, e_write, co_skip in consts.ROLE_LIST_2:
            if co_skip and isinstance(company_info, tuple):
                continue
            if not e_write and not online_sign:
                continue
            is_find = False
            if app_type in main_role_info:
                if len(main_role_info[app_type]) >= id_idx+1:
                    is_find = True
                    if isinstance(field_idx, int):
                        hil_contract_2_input.append((key, main_role_info[app_type][id_idx][field_idx]))
                    else:
                        hil_contract_2_input.append((key, field_idx))
            if not is_find and is_force:
                hil_contract_2_input.append((key, empty_str))
        contract_info[consts.HIL_CONTRACT_2_EN] = hil_contract_2_input
        compare_info['contract'] = contract_info
        return compare_info, cms_info.get('applicationVersion', 1), is_gsyh
    else:
        # AFC合同------------------------------------------------------------------------------------------------------
        vehicle_principal_str = str(cms_info.get('financialInformation', {}).get('vehiclePrincipal', '0.0'))
        afc_contract_input = [
            (consts.SE_AFC_CON_FIELD[0], full_no),
            (consts.SE_AFC_CON_FIELD[1], amount),
            (consts.SE_AFC_CON_FIELD[2], vin_no),
            (consts.SE_AFC_CON_FIELD[3], str(cms_info.get('financialInformation', {}).get('originationPrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[4], str(cms_info.get('terms', '0'))),
            (consts.SE_AFC_CON_FIELD[5], vehicle_principal_str),
            (consts.SE_AFC_CON_FIELD[6], str(cms_info.get('financialInformation', {}).get('associatedServicePrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[7], amount),
            (consts.SE_AFC_CON_FIELD[8], vin_no),
            (consts.SE_AFC_CON_FIELD[9], cms_info.get('dealerName', '')),
            (consts.SE_AFC_CON_FIELD[10], str(cms_info.get('financialInformation', {}).get('originationPrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[11], vehicle_principal_str),
            (consts.SE_AFC_CON_FIELD[12], str(cms_info.get('financialInformation', {}).get('associatedServicePrincipal', '0.0'))),
            (consts.SE_AFC_CON_FIELD[13], str(cms_info.get('terms', '0'))),
            (consts.SE_AFC_CON_FIELD[14], account_no),
            (consts.SE_AFC_CON_FIELD[15], account_holder_name),
            (consts.SE_AFC_CON_FIELD[16], bank_name),
            (consts.SE_AFC_CON_FIELD[17], schedule_list_str),
        ]

        if is_asp:
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[20], asp_list))
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[22], asp_list))
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[21], gzs_list))
        else:
            afc_contract_input.pop(5)
            afc_contract_input.pop(5)
            afc_contract_input.pop(9)
            afc_contract_input.pop(9)

        # '借款人签字及时间', 'Borrower', 0, 0, True
        for key, app_type, id_idx, field_idx, is_force, e_write in consts.ROLE_LIST:
            if not e_write and not online_sign:
                continue
            is_find = False
            if app_type in main_role_info:
                if len(main_role_info[app_type]) >= id_idx+1:
                    is_find = True
                    if isinstance(field_idx, int):
                        afc_contract_input.append((key, main_role_info[app_type][id_idx][field_idx]))
                    else:
                        afc_contract_input.append((key, field_idx))
            if not is_find and is_force:
                afc_contract_input.append((key, empty_str))

        if online_sign:
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[18], consts.SE_STAMP_VALUE))
            afc_contract_input.append((consts.SE_AFC_CON_FIELD[19], empty_str))

        contract_info[consts.AFC_CONTRACT_EN] = afc_contract_input
        compare_info['contract'] = contract_info
        return compare_info, cms_info.get('applicationVersion', 1), is_gsyh


def get_se_compare_info(last_obj, application_entity, detect_list):
    compare_info = {}
    individual_info_dict = {}
    main_role_info = {}
    for individual_info in json.loads(last_obj.individual_cus_info):
        if isinstance(individual_info.get('secondIdNum'), str):
            id_num = '{0}、{1}'.format(individual_info['idNum'], individual_info['secondIdNum'])
        else:
            id_num = individual_info['idNum']
        main_role_info.setdefault(individual_info['applicantType'], []).append(
            (individual_info['customerName'], id_num, individual_info['idNum']))

        license_dict = {}

        if individual_info['idType'] in consts.SE_FIRST_ID_FIELD_MAPPING:
            license_en, field_list = consts.SE_FIRST_ID_FIELD_MAPPING[individual_info['idType']]
            field_input = []
            for field in field_list:
                if field in individual_info:
                    field_input.append((field, individual_info[field]))
            license_dict[license_en] = field_input

        if individual_info.get('secondIdType') in consts.SE_SECOND_ID_FIELD_MAPPING:
            second_license_en, second_field_list = consts.SE_SECOND_ID_FIELD_MAPPING[individual_info['secondIdType']]
            if second_license_en not in license_dict:
                second_field_input = []
                for second_field, write_field in second_field_list:
                    if second_field in individual_info:
                        second_field_input.append((write_field, individual_info[second_field]))
                license_dict[second_license_en] = second_field_input

        if individual_info['customerType'] == consts.CUSTOMER_TYPE[5]:
            sep_field_input = []
            for sep_field, sep_write_field in consts.SE_SEP_FIELD:
                if sep_field in individual_info:
                    sep_field_input.append((sep_write_field, individual_info[sep_field]))
            license_dict[consts.BL_EN] = sep_field_input

        if len(license_dict) > 0:
            individual_info_dict.setdefault(individual_info['applicantType'], []).append(license_dict)

    compare_info['individualCusInfo'] = individual_info_dict

    dda_name_list = []
    dda_num_list = []
    for applicant_type in consts.APPLICANT_TYPE:
        if applicant_type in main_role_info:
            main_name, main_num, _ = main_role_info[applicant_type][0]
            hmh_name, _, hmh_id = main_role_info[applicant_type][0]
            break
    for applicant_type in consts.APPLICANT_TYPE[:2]:
        if applicant_type in main_role_info:
            for dda_name_part, _, dda_num_part in main_role_info[applicant_type]:
                dda_name_list.append(dda_name_part)
                dda_num_list.append(dda_num_part)
    dda_name = '、'.join(dda_name_list)
    dda_num = '、'.join(dda_num_list)
    del main_role_info

    company_info = None
    if isinstance(last_obj.corporate_cus_info, str):
        corporate_info_dict = json.loads(last_obj.corporate_cus_info)
        corporate_info = {}
        company_info = (corporate_info_dict['companyName'], corporate_info_dict['businessLicenseNo'])
        if corporate_info_dict['firstIdType'] == consts.ID_TYPE[6]:
            bl_field_input = []
            for bl_field in consts.SE_CORPORATE_ALL_FIELD:
                bl_field_input.append((bl_field, corporate_info_dict[bl_field]))
            corporate_info[consts.BL_EN] = bl_field_input
        else:
            if corporate_info_dict['firstIdType'] in consts.SE_FIRST_ID_FIELD_MAPPING:
                license_en, _ = consts.SE_FIRST_ID_FIELD_MAPPING[corporate_info_dict['firstIdType']]
                first_id_field_input = []
                for first_id_field, first_id_write_field in consts.SE_CORPORATE_ID_FIELD:
                    first_id_field_input.append((first_id_write_field, corporate_info_dict[first_id_field]))
                corporate_info[license_en] = first_id_field_input
            bl_field_input = []
            for bl_field in consts.SE_CORPORATE_FIELD:
                bl_field_input.append((bl_field, corporate_info_dict[bl_field]))
            corporate_info[consts.BL_EN] = bl_field_input

        compare_info['corporateCusInfo'] = corporate_info

    vehicle_info_dict = json.loads(last_obj.vehicle_info)  # TODO 车辆登记证
    vehicle_info = {}
    vehicle_field_input = []
    if vehicle_info_dict['vehicleStatus'] == 'New':
        for vehicle_field in consts.SE_NEW_FIELD:
            vehicle_field_input.append((vehicle_field, vehicle_info_dict[vehicle_field]))
        if isinstance(company_info, tuple):
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
        else:
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], main_name))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], main_num))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[2], last_obj.first_submmison_date))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[3], consts.SE_STAMP_VALUE))
        vehicle_info[consts.MVI_EN] = vehicle_field_input
    else:
        gb_field_input = []
        gb34_field_input = []
        jypz_field_input = []
        for vehicle_field in consts.SE_USED_FIELD:
            vehicle_field_input.append((vehicle_field, vehicle_info_dict[vehicle_field]))
        for gb_field in consts.SE_GB_NEW_FIELD:
            gb_field_input.append((gb_field, vehicle_info_dict[gb_field]))
        if isinstance(company_info, tuple):
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[0], company_info[0]))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[1], company_info[1]))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[0], company_info[0]))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[1], company_info[1]))
        else:
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[0], main_name))
            vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[1], main_num))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[0], main_name))
            jypz_field_input.append((consts.SE_NEW_ADD_FIELD[1], main_num))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[0], main_name))
            gb34_field_input.append((consts.SE_GB_USED_FIELD[1], main_num))
        gb34_field_input.append((consts.SE_GB_USED_FIELD[2], last_obj.first_submmison_date))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[2], last_obj.first_submmison_date))
        vehicle_field_input.append((consts.SE_NEW_ADD_FIELD[3], consts.SE_STAMP_VALUE))
        for jypz_field in consts.SE_USED_FIELD:
            jypz_field_input.append((jypz_field, vehicle_info_dict[jypz_field]))
        jypz_field_input.append((consts.SE_GB_USED_FIELD[-1], last_obj.first_submmison_date))
        vehicle_info[consts.MVC_EN] = gb_field_input
        vehicle_info[consts.MVC34_EN] = gb34_field_input
        if not detect_list[0]:
            vehicle_info[consts.UCI_EN] = vehicle_field_input
        if not detect_list[1]:
            vehicle_info[consts.JYPZ_EN] = jypz_field_input
        if detect_list[0] and detect_list[1]:
            vehicle_info[consts.UCI_EN] = vehicle_field_input
    compare_info['vehicleInfo'] = vehicle_info

    bank_info_dict = json.loads(last_obj.bank_info)
    bank_info = {}
    bank_field_input = []
    for bank_field in consts.SE_BANK_FIELD:
        bank_field_input.append((bank_field, bank_info_dict[bank_field]))
    if '工商' in bank_info_dict.get(consts.SE_BANK_FIELD[-1], ''):
        is_gsyh = True
    else:
        is_gsyh = False
    bank_info[consts.BC_EN] = bank_field_input

    if is_gsyh or not detect_list[-1]:
        dda_field_input = []
        for dda_field in consts.SE_DDA_FIELD:
            if dda_field.startswith('applicationId'):
                dda_field_input.append((dda_field, last_obj.application_id))
            elif dda_field == 'companyName':
                company_name = consts.HIL_COMPANY_NAME if application_entity in consts.HIL_SET else consts.AFC_COMPANY_NAME
                dda_field_input.append((dda_field, company_name))
            elif dda_field == 'customerName':
                dda_field_input.append((dda_field, dda_name))
            elif dda_field == 'idNum':
                dda_field_input.append((dda_field, dda_num))
            else:
                dda_field_input.append((dda_field, bank_info_dict[dda_field]))
        bank_info[consts.DDA_EN] = dda_field_input
    compare_info['bankInfo'] = bank_info

    if not detect_list[2]:
        other_info = {}
        hmh_field_input = []
        hmh_field_input.append((consts.SE_HMH_FIELD[0], hmh_name))
        hmh_field_input.append((consts.SE_HMH_FIELD[1], hmh_id))
        hmh_field_input.append((consts.SE_HMH_FIELD[2], last_obj.application_id))
        other_info[consts.HMH_EN] = hmh_field_input
        compare_info['other'] = other_info

    return compare_info, is_gsyh


def se_bs_compare(license_en, ocr_res_dict, strip_list):
    # 主共借至少提供一个
    # 有担保人,担保人必须提供。主共借没有时,修改comment:人工查看担保人亲属关系

    ocr_field, compare_logic, _ = consts.SE_COMPARE_FIELD[license_en]
    ocr_res_str = ocr_res_dict.get(ocr_field)

    result_field_list = []
    field_img_path_dict = dict()

    if ocr_res_str is not None:
        pre_field_list = strip_list[:3]
        dbr1_field_list = strip_list[3:6]
        dbr2_field_list = strip_list[6:]

        ocr_res_list = json.loads(ocr_res_str)
        # length = len(ocr_res_list)

        # 主共借人
        pre_best_res = {}
        max_correct_count = 0
        for ocr_res in ocr_res_list:
            correct_count = 0
            pre_tmp_res_part = {}
            for idx, (name, value) in enumerate(pre_field_list):
                ocr_str_or_list = ocr_res.get(compare_logic[name][0])
                if isinstance(ocr_str_or_list, str) or isinstance(ocr_str_or_list, list):
                    result = getattr(cp, compare_logic[name][1])(value, ocr_str_or_list, **compare_logic[name][2])
                    if isinstance(ocr_str_or_list, list):
                        ocr_str = json.dumps(ocr_str_or_list, ensure_ascii=False)
                    else:
                        ocr_str = ocr_str_or_list
                    reason = compare_logic[name][3]
                else:
                    result = consts.RESULT_N
                    ocr_str = empty_str
                    reason = compare_logic[name][3]

                if idx == 0 and result == consts.RESULT_N:
                    break

                if result == consts.RESULT_Y:
                    correct_count += 1
                pre_tmp_res_part[name] = (result, ocr_str, reason)

            if correct_count > 0 and correct_count >= max_correct_count:
                max_correct_count = correct_count
                pre_best_res = pre_tmp_res_part

        # 担保人1
        dbr1_best_res = {}
        if len(dbr1_field_list) > 0:
            max_correct_count = 0
            for ocr_res in ocr_res_list:
                correct_count = 0
                dbr1_tmp_res_part = {}
                for idx, (name, value) in enumerate(dbr1_field_list):
                    ocr_str_or_list = ocr_res.get(compare_logic[name][0])
                    if isinstance(ocr_str_or_list, str) or isinstance(ocr_str_or_list, list):
                        result = getattr(cp, compare_logic[name][1])(value, ocr_str_or_list, **compare_logic[name][2])
                        if isinstance(ocr_str_or_list, list):
                            ocr_str = json.dumps(ocr_str_or_list, ensure_ascii=False)
                        else:
                            ocr_str = ocr_str_or_list
                        reason = compare_logic[name][3]
                    else:
                        result = consts.RESULT_N
                        ocr_str = empty_str
                        reason = compare_logic[name][3]

                    if idx == 0 and result == consts.RESULT_N:
                        break

                    if result == consts.RESULT_Y:
                        correct_count += 1
                    dbr1_tmp_res_part[name] = (result, ocr_str, reason)

                if correct_count > 0 and correct_count >= max_correct_count:
                    max_correct_count = correct_count
                    dbr1_best_res = dbr1_tmp_res_part

        # 担保人2
        dbr2_best_res = {}
        if len(dbr1_field_list) > 0:
            max_correct_count = 0
            for ocr_res in ocr_res_list:
                correct_count = 0
                dbr2_tmp_res_part = {}
                for idx, (name, value) in enumerate(dbr2_field_list):
                    ocr_str_or_list = ocr_res.get(compare_logic[name][0])
                    if isinstance(ocr_str_or_list, str) or isinstance(ocr_str_or_list, list):
                        result = getattr(cp, compare_logic[name][1])(value, ocr_str_or_list, **compare_logic[name][2])
                        if isinstance(ocr_str_or_list, list):
                            ocr_str = json.dumps(ocr_str_or_list, ensure_ascii=False)
                        else:
                            ocr_str = ocr_str_or_list
                        reason = compare_logic[name][3]
                    else:
                        result = consts.RESULT_N
                        ocr_str = empty_str
                        reason = compare_logic[name][3]

                    if idx == 0 and result == consts.RESULT_N:
                        break

                    if result == consts.RESULT_Y:
                        correct_count += 1
                    dbr2_tmp_res_part[name] = (result, ocr_str, reason)

                if correct_count > 0 and correct_count >= max_correct_count:
                    max_correct_count = correct_count
                    dbr2_best_res = dbr2_tmp_res_part

        dbr_ok = False
        # 有担保人
        if len(dbr1_field_list) > 0:
            # 有担保人12
            if len(dbr2_field_list) > 0:
                if len(dbr1_best_res) > 0 and len(dbr2_best_res) > 0:
                    dbr_ok = True
            # 有担保人1
            else:
                if len(dbr1_best_res) > 0:
                    dbr_ok = True
        # 无担保人
        # else:
        #     pass

        best_res_empty = False
        if len(pre_best_res) == 0 and len(dbr1_best_res) == 0 and len(dbr2_best_res) == 0:
            best_res_empty = True

        for name, value in pre_field_list:
            if len(pre_best_res) > 0:
                result, ocr_str, reason = pre_best_res[name]
            else:
                result = consts.RESULT_N
                ocr_str = empty_str
                if best_res_empty:
                    reason = consts.SPECIAL_REASON_3
                elif dbr_ok:  # 有担保人且担保人都提供了流水
                    reason = consts.SPECIAL_REASON
                else:
                    reason = compare_logic[pre_field_list[0][0]][3]
            img_path = empty_str
            error_type = empty_error_type if result == consts.RESULT_Y else ErrorType.OCR.value
            if isinstance(value, list):
                value = json.dumps(value, ensure_ascii=False)
            result_field_list.append((name, value, result, ocr_str, img_path, error_type, reason))

        if len(dbr1_field_list) > 0:
            for name, value in dbr1_field_list:
                if len(dbr1_best_res) > 0:
                    result, ocr_str, reason = dbr1_best_res[name]
                else:
                    result = consts.RESULT_N
                    ocr_str = empty_str
                    if best_res_empty:
                        reason = consts.SPECIAL_REASON_3
                    elif len(pre_best_res) > 0:
                        reason = consts.SPECIAL_REASON_2
                    else:
                        reason = compare_logic[dbr1_field_list[0][0]][3]
                img_path = empty_str
                error_type = empty_error_type if result == consts.RESULT_Y else ErrorType.OCR.value
                if isinstance(value, list):
                    value = json.dumps(value, ensure_ascii=False)
                result_field_list.append((name, value, result, ocr_str, img_path, error_type, reason))

        if len(dbr2_field_list) > 0:
            for name, value in dbr2_field_list:
                if len(dbr2_best_res) > 0:
                    result, ocr_str, reason = dbr2_best_res[name]
                else:
                    result = consts.RESULT_N
                    ocr_str = empty_str
                    if best_res_empty:
                        reason = consts.SPECIAL_REASON_3
                    elif len(pre_best_res) > 0:
                        reason = consts.SPECIAL_REASON_2
                    else:
                        reason = compare_logic[dbr2_field_list[0][0]][3]
                img_path = empty_str
                error_type = empty_error_type if result == consts.RESULT_Y else ErrorType.OCR.value
                if isinstance(value, list):
                    value = json.dumps(value, ensure_ascii=False)
                result_field_list.append((name, value, result, ocr_str, img_path, error_type, reason))

    else:
        for name, value in strip_list:
            if isinstance(value, list):
                value = json.dumps(value, ensure_ascii=False)
            result_field_list.append((name, value, consts.RESULT_N, empty_str, empty_str, ErrorType.NF.value,
                                      consts.SPECIAL_REASON_3))

    return result_field_list, field_img_path_dict


def se_compare_license(license_en, ocr_res_dict, field_list):
    ocr_field, compare_logic, special_expiry_date = consts.SE_COMPARE_FIELD[license_en]

    is_find = False
    no_ocr_result = False
    special_expiry_date_slice = False
    result_field_list = []
    section_img_info = dict()
    field_img_path_dict = dict()
    ocr_res_str = ocr_res_dict.get(ocr_field)
    if ocr_res_str is not None:
        ocr_res_list = json.loads(ocr_res_str)

        # 3/4页去除
        if ocr_field == consts.MVC_OCR_FIELD:
            tmp_list = []
            for res in ocr_res_list:
                if compare_logic['vinNo'][0] in res:
                    tmp_list.append(res)
            ocr_res_list = tmp_list

        length = len(ocr_res_list)

        # 身份证、居住证 过期期限特殊处理
        if special_expiry_date:
            expiry_dates = dict()
            key = compare_logic.get('idExpiryDate')[0]
            for date_tmp_idx, ocr_res in enumerate(ocr_res_list):
                if key in ocr_res:
                    expiry_dates[ocr_res[key]] = (ocr_res.get(consts.IMG_PATH_KEY_2, ''), date_tmp_idx)
        else:
            expiry_dates = dict()

        for res_idx in range(length-1, -1, -1):
            if is_find:
                break

            for idx, (name, value) in enumerate(field_list):
                if ocr_field == consts.MVI_OCR_FIELD and name == consts.SE_NEW_ADD_FIELD[5]:
                    ocr_str = getattr(cp, consts.ZW_METHOD)(
                        ocr_res_list[res_idx].get(consts.LOWER_AMOUNT_FIELD, ''),
                        ocr_res_list[res_idx].get(consts.UPPER_AMOUNT_FIELD, ''),
                        ocr_res_list[res_idx].get(consts.BHSJ_FIELD, ''),
                        ocr_res_list[res_idx].get(consts.ZZSSE_FIELD, '')
                    )
                else:
                    ocr_str = ocr_res_list[res_idx].get(compare_logic[name][0])
                if not isinstance(ocr_str, str):
                    result = consts.RESULT_N
                    ocr_str = empty_str
                    no_key = True
                else:
                    result = getattr(cp, compare_logic[name][1])(value, ocr_str, **compare_logic[name][2])
                    no_key = False

                if idx == 0 and result == consts.RESULT_N and length > 1:
                    break

                is_find = True
                section_img_info[consts.SECTION_IMG_PATH_KEY] = ocr_res_list[res_idx].get(consts.SECTION_IMG_PATH_KEY, '')
                section_img_info[consts.ALL_POSITION_KEY] = ocr_res_list[res_idx].get(consts.ALL_POSITION_KEY, {})
                if special_expiry_date:
                    section_img_info[consts.SECTION_IMG_PATH_KEY_2] = ocr_res_list[res_idx].get(
                        consts.SECTION_IMG_PATH_KEY_2, '')
                    section_img_info[consts.ALL_POSITION_KEY_2] = ocr_res_list[res_idx].get(consts.ALL_POSITION_KEY_2, {})

                # 过期期限特殊处理
                if special_expiry_date and name == 'idExpiryDate' and result == consts.RESULT_N:
                    if no_key:
                        for expiry_date, (date_img_path, date_res_idx) in expiry_dates.items():
                            expiry_date_res = getattr(cp, compare_logic[name][1])(value, expiry_date, **compare_logic[name][2])
                            if expiry_date_res == consts.RESULT_N:
                                ocr_str = expiry_date
                                img_path = date_img_path
                                special_expiry_date_slice = True
                                section_img_info[consts.SECTION_IMG_PATH_KEY_2] = ocr_res_list[date_res_idx].get(
                                    consts.SECTION_IMG_PATH_KEY_2, '')
                                section_img_info[consts.ALL_POSITION_KEY_2] = ocr_res_list[date_res_idx].get(
                                    consts.ALL_POSITION_KEY_2, {})
                                break
                        else:
                            ocr_str = empty_str
                            result = consts.RESULT_Y
                            img_path = empty_str
                    else:
                        img_path = ocr_res_list[res_idx].get(consts.IMG_PATH_KEY_2, '')
                        special_expiry_date_slice = True
                else:
                    img_path = ocr_res_list[res_idx].get(consts.IMG_PATH_KEY, '') if result == consts.RESULT_N else empty_str
                if isinstance(value, list):
                    value = json.dumps(value, ensure_ascii=False)
                error_type = empty_error_type if result == consts.RESULT_Y else ErrorType.OCR.value
                result_field_list.append((name, value, result, ocr_str, img_path, error_type, compare_logic[name][3]))
    else:
        no_ocr_result = True

    if not is_find:
        for name, value in field_list:
            if isinstance(value, list):
                value = json.dumps(value, ensure_ascii=False)
            result_field_list.append((name, value, consts.RESULT_N, empty_str, empty_str, ErrorType.NF.value, '{0}未找到'.format(license_en)))

    if is_find:
        if special_expiry_date_slice:
            special_section_img_path = section_img_info.get(consts.SECTION_IMG_PATH_KEY_2, '')
            if os.path.exists(special_section_img_path):
                field = 'idExpiryDate'
                special_info = section_img_info.get(consts.ALL_POSITION_KEY_2, {})
                special_section_position = special_info.get(consts.POSITION_KEY, {})
                special_section_angle = special_info.get(consts.ANGLE_KEY, 0)
                try:
                    last_img = img_process(special_section_img_path, special_section_position, special_section_angle)
                except Exception as e:
                    field_img_path_dict[field] = special_section_img_path
                else:
                    pre, suf = os.path.splitext(special_section_img_path)
                    try:
                        res_field = compare_logic[field][0]
                        is_valid, coord_tuple = field_build_coordinates(special_info.get(res_field, {}))
                        if is_valid:
                            save_path = '{0}_{1}{2}'.format(pre, field, suf)
                            field_img = last_img[coord_tuple[0]:coord_tuple[1], coord_tuple[2]:coord_tuple[3], :]
                            cv2.imwrite(save_path, field_img)
                            field_img_path_dict[field] = save_path
                        else:
                            field_img_path_dict[field] = special_section_img_path
                    except Exception as e:
                        field_img_path_dict[field] = special_section_img_path

        section_img_path = section_img_info.get(consts.SECTION_IMG_PATH_KEY, '')
        if os.path.exists(section_img_path):
            failed_field = []
            base_img_path = empty_str
            for name, _, result, _, img_path, _, _ in result_field_list:
                if result == consts.RESULT_N:
                    if special_expiry_date_slice and name == 'idExpiryDate':
                        continue
                    failed_field.append(name)
                    if base_img_path == empty_str:
                        base_img_path = img_path
            if len(failed_field) > 0:
                info = section_img_info.get(consts.ALL_POSITION_KEY, {})
                section_position = info.get(consts.POSITION_KEY, {})
                section_angle = info.get(consts.ANGLE_KEY, 0)
                try:
                    last_img = img_process(section_img_path, section_position, section_angle)
                except Exception as e:
                    for field in failed_field:
                        field_img_path_dict[field] = base_img_path
                else:
                    pre, suf = os.path.splitext(section_img_path)
                    for field in failed_field:
                        try:
                            res_field = compare_logic[field][0]
                            is_valid, coord_tuple = field_build_coordinates(info.get(res_field, {}))
                            if is_valid:
                                save_path = '{0}_{1}{2}'.format(pre, field, suf)
                                field_img = last_img[coord_tuple[0]:coord_tuple[1], coord_tuple[2]:coord_tuple[3], :]
                                cv2.imwrite(save_path, field_img)
                                field_img_path_dict[field] = save_path
                            else:
                                field_img_path_dict[field] = base_img_path
                        except Exception as e:
                            field_img_path_dict[field] = base_img_path

    return result_field_list, no_ocr_result, field_img_path_dict


def se_contract_compare(license_en, ocr_res_dict, strip_list, is_gsyh):
    ocr_field, compare_logic, _ = consts.SE_COMPARE_FIELD[license_en]
    ocr_res_str = ocr_res_dict.get(ocr_field)

    result_field_list = []
    field_img_path_dict = dict()

    if ocr_res_str is not None:
        ocr_res_list = json.loads(ocr_res_str)
        ocr_res = ocr_res_list.pop()

        for name, value in strip_list:
            if name == consts.SE_AFC_CON_FIELD[21]:
                if len(value) == 3:
                    reason = []
                    gzs_verify = value[1] >= value[2]
                    if gzs_verify:
                        if value[0] == consts.GZS_STATUS[0]:
                            reason.append(consts.GZS_REASON_1)
                            result = consts.RESULT_N
                        else:
                            result = consts.RESULT_Y
                    else:
                        if value[0] == consts.GZS_STATUS[0]:
                            reason.append(consts.GZS_REASON_1)
                        result = consts.RESULT_N
                        reason.append(consts.GZS_REASON_2)
                else:
                    result = consts.RESULT_N
                    reason = consts.GZS_REASON_1
                ocr_str = empty_str
            else:
                ocr_str_or_list = ocr_res.get(compare_logic[name][0])
                if ocr_str_or_list is None and license_en == consts.AFC_CONTRACT_EN \
                        and is_gsyh is True and name in consts.CON_BANK_FIELD:
                    result = consts.RESULT_Y
                    ocr_str = empty_str
                    reason = compare_logic[name][3]
                elif isinstance(ocr_str_or_list, str) or isinstance(ocr_str_or_list, list):
                    if is_gsyh is True and name in consts.CON_BANK_FIELD:
                        update_args = {'is_gsyh': is_gsyh}
                        for k, v in compare_logic[name][2].items():
                            update_args[k] = v
                    else:
                        update_args = compare_logic[name][2]
                    result = getattr(cp, compare_logic[name][1])(value, ocr_str_or_list, **update_args)
                    if isinstance(ocr_str_or_list, list):
                        ocr_str = json.dumps(ocr_str_or_list, ensure_ascii=False)
                    else:
                        ocr_str = ocr_str_or_list
                    reason = compare_logic[name][3]
                else:
                    result = consts.RESULT_N
                    ocr_str = empty_str
                    reason = compare_logic[name][3]

            # img_path = empty_str
            if name not in compare_logic:
                img_path = empty_str
            else:
                img_path = ocr_res.get(consts.IMG_PATH_KEY, {}).get(compare_logic[name][0], empty_str) if result == consts.RESULT_N else empty_str
            error_type = empty_error_type if result == consts.RESULT_Y else ErrorType.OCR.value
            if isinstance(value, list):
                value = json.dumps(value, ensure_ascii=False)
            result_field_list.append((name, value, result, ocr_str, img_path, error_type, reason))
    else:
        for name, value in strip_list:
            if isinstance(value, list):
                value = json.dumps(value, ensure_ascii=False)
            result_field_list.append((name, value, consts.RESULT_N, empty_str, empty_str, ErrorType.NF.value,
                                      '{0}未找到'.format(license_en)))

    return result_field_list, field_img_path_dict


def se_mvc34_compare(license_en, ocr_res_dict, field_list):
    ocr_field, compare_logic, _ = consts.SE_COMPARE_FIELD[license_en]
    ocr_res_str = ocr_res_dict.get(ocr_field)

    is_find = False
    result_field_list = []
    field_img_path_dict = dict()

    if ocr_res_str is not None:
        ocr_res_list = json.loads(ocr_res_str)
        length = len(ocr_res_list)

        page34_date_dict = dict()
        first_res = None
        for res_idx in range(length-1, -1, -1):
            if consts.TRANSFER_DATE in ocr_res_list[res_idx]:
                img_path = ocr_res_list[res_idx].get(consts.IMG_PATH_KEY_2, '')
                section_img_path = ocr_res_list[res_idx].get(consts.SECTION_IMG_PATH_KEY_2, '')
                for idx, transfer_date in enumerate(ocr_res_list[res_idx].get(consts.TRANSFER_DATE, [])):
                    try:
                        transfer_name = ocr_res_list[res_idx].get(consts.TRANSFER_NAME, [])[idx]
                    except Exception as e:
                        transfer_name = empty_str
                    try:
                        transfer_num = ocr_res_list[res_idx].get(consts.TRANSFER_NUM, [])[idx]
                    except Exception as e:
                        transfer_num = empty_str
                    try:
                        position_info_date = ocr_res_list[res_idx].get(consts.ALL_POSITION_KEY_2, dict()).get(
                            consts.TRANSFER_DATE, [])[idx]
                    except Exception as e:
                        position_info_date = {}
                    try:
                        position_info_name = ocr_res_list[res_idx].get(consts.ALL_POSITION_KEY_2, dict()).get(
                            consts.TRANSFER_NAME, [])[idx]
                    except Exception as e:
                        position_info_name = {}
                    try:
                        position_info_num = ocr_res_list[res_idx].get(consts.ALL_POSITION_KEY_2, dict()).get(
                            consts.TRANSFER_NUM, [])[idx]
                    except Exception as e:
                        position_info_num = {}
                    core_info = {
                        consts.TRANSFER_NAME: transfer_name,
                        consts.TRANSFER_NUM: transfer_num,
                        consts.TRANSFER_DATE: transfer_date,
                        consts.IMG_PATH_KEY_2: img_path,
                        consts.SECTION_IMG_PATH_KEY_2: section_img_path,
                        consts.ALL_POSITION_KEY: {
                            consts.TRANSFER_NAME: position_info_name,
                            consts.TRANSFER_NUM: position_info_num,
                            consts.TRANSFER_DATE: position_info_date,
                        },
                    }
                    page34_date_dict.setdefault(transfer_date, []).append(core_info)
                    if first_res is None:
                        first_res = core_info

        max_date = None
        for date_tmp in page34_date_dict.keys():
            try:
                max_date_part = time.strptime(date_tmp, "%Y-%m-%d")
            except Exception as e:
                pass
            else:
                if max_date is None or max_date_part > max_date:
                    max_date = max_date_part

        if max_date is not None or first_res is not None:
            is_find = True
            ocr_res = first_res if max_date is None else page34_date_dict[time.strftime('%Y-%m-%d', max_date)][0]
            failed_field = []
            base_img_path = ocr_res.get(consts.IMG_PATH_KEY_2, '')
            for name, value in field_list:
                ocr_str = ocr_res.get(compare_logic[name][0])
                if not isinstance(ocr_str, str):
                    result = consts.RESULT_N
                    ocr_str = empty_str
                else:
                    result = getattr(cp, compare_logic[name][1])(value, ocr_str, **compare_logic[name][2])
                img_path = base_img_path if result == consts.RESULT_N else empty_str
                error_type = empty_error_type if result == consts.RESULT_Y else ErrorType.OCR.value
                result_field_list.append((name, value, result, ocr_str, img_path, error_type, compare_logic[name][3]))

                if result == consts.RESULT_N:
                    failed_field.append(name)

            section_img_path = ocr_res.get(consts.SECTION_IMG_PATH_KEY_2, '')
            if len(failed_field) > 0 and os.path.exists(section_img_path):
                info = ocr_res.get(consts.ALL_POSITION_KEY, {})
                try:
                    last_img = img_process(section_img_path, {}, 0)
                except Exception as e:
                    for field in failed_field:
                        field_img_path_dict[field] = base_img_path
                else:
                    pre, suf = os.path.splitext(section_img_path)
                    for field in failed_field:
                        try:
                            res_field = compare_logic[field][0]
                            is_valid, coord_tuple = field_build_coordinates(info.get(res_field, {}))
                            if is_valid:
                                save_path = '{0}_{1}{2}'.format(pre, field, suf)
                                field_img = last_img[coord_tuple[0]:coord_tuple[1], coord_tuple[2]:coord_tuple[3], :]
                                cv2.imwrite(save_path, field_img)
                                field_img_path_dict[field] = save_path
                            else:
                                field_img_path_dict[field] = base_img_path
                        except Exception as e:
                            field_img_path_dict[field] = base_img_path

    if not is_find:
        for name, value in field_list:
            result_field_list.append((name, value, consts.RESULT_N, empty_str, empty_str, ErrorType.NF.value, '{0}未找到'.format(license_en)))

    return result_field_list, field_img_path_dict


def se_compare_process(compare_info, ocr_res_dict, is_gsyh):
    # individualCusInfo
    # corporateCusInfo
    # vehicleInfo
    # bankInfo
    compare_result = []
    total_fields = 0
    failed_count = 0
    successful_at_this_level = True
    failure_reason = {}
    cn_reason_list = []

    for info_key, info_value in compare_info.items():
        if info_key in ['individualCusInfo', 'applicantInformation']:
            for idx, license_list in info_value.items():
                for license_dict in license_list:
                    for license_en, field_list in license_dict.items():
                        strip_list = []
                        for a, b in field_list:
                            if isinstance(b, str):
                                strip_list.append((a, b.strip()))
                            elif isinstance(b, list):
                                c = []
                                for i in b:
                                    if isinstance(i, str):
                                        c.append(i.strip())
                                    else:
                                        c.append(i)
                                strip_list.append((a, c))
                            else:
                                strip_list.append((a, b))
                        failure_field = []
                        result_field_list, no_ocr_result, field_img_path_dict = se_compare_license(license_en, ocr_res_dict, strip_list)
                        for name, value, result, ocr_str, img_path, error_type, cn_reason in result_field_list:
                            if license_en not in consts.SKIP_CARD or not no_ocr_result:
                                total_fields += 1
                                if result == consts.RESULT_N:
                                    failed_count += 1
                                    successful_at_this_level = False
                                    failure_field.append(name)
                                    cn_reason_list.append(cn_reason)
                            compare_result.append(
                                {
                                    consts.HEAD_LIST[0]: info_key,
                                    consts.HEAD_LIST[1]: idx,
                                    consts.HEAD_LIST[2]: license_en,
                                    consts.HEAD_LIST[3]: name,
                                    consts.HEAD_LIST[4]: value,
                                    consts.HEAD_LIST[5]: ocr_str,
                                    consts.HEAD_LIST[6]: result,
                                    consts.HEAD_LIST[7]: field_img_path_dict.get(name, empty_str),
                                    consts.HEAD_LIST[8]: img_path,
                                    consts.HEAD_LIST[9]: error_type,
                                }
                            )
                        if len(failure_field) > 0:
                            failure_reason.setdefault(info_key, []).append(';'.join(failure_field))
        else:
            for license_en, field_list in info_value.items():
                strip_list = []
                for a, b in field_list:
                    if isinstance(b, str):
                        strip_list.append((a, b.strip()))
                    elif isinstance(b, list):
                        c = []
                        for i in b:
                            if isinstance(i, str):
                                c.append(i.strip())
                            else:
                                c.append(i)
                        strip_list.append((a, c))
                    else:
                        strip_list.append((a, b))
                failure_field = []
                if license_en == consts.MVC34_EN:
                    result_field_list, field_img_path_dict = se_mvc34_compare(license_en, ocr_res_dict, strip_list)
                elif license_en in [consts.HIL_CONTRACT_1_EN, consts.HIL_CONTRACT_2_EN, consts.HIL_CONTRACT_3_EN, consts.AFC_CONTRACT_EN]:
                    result_field_list, field_img_path_dict = se_contract_compare(license_en, ocr_res_dict, strip_list, is_gsyh)
                elif license_en == consts.BS_EN:
                    result_field_list, field_img_path_dict = se_bs_compare(license_en, ocr_res_dict, strip_list)
                else:
                    result_field_list, _, field_img_path_dict = se_compare_license(license_en, ocr_res_dict, strip_list)

                for name, value, result, ocr_str, img_path, error_type, cn_reason in result_field_list:
                    total_fields += 1
                    if result == consts.RESULT_N:
                        failed_count += 1
                        successful_at_this_level = False
                        failure_field.append(name)
                        if isinstance(cn_reason, str):
                            cn_reason_list.append(cn_reason)
                        elif isinstance(cn_reason, list):
                            cn_reason_list.extend(cn_reason)
                    compare_result.append(
                        {
                            consts.HEAD_LIST[0]: info_key,
                            consts.HEAD_LIST[1]: "0",
                            consts.HEAD_LIST[2]: license_en,
                            consts.HEAD_LIST[3]: name,
                            consts.HEAD_LIST[4]: value,
                            consts.HEAD_LIST[5]: ocr_str,
                            consts.HEAD_LIST[6]: result,
                            consts.HEAD_LIST[7]: field_img_path_dict.get(name, empty_str),
                            consts.HEAD_LIST[8]: img_path,
                            consts.HEAD_LIST[9]: error_type,
                        }
                    )
                if len(failure_field) > 0:
                    failure_reason.setdefault(info_key, []).append(';'.join(failure_field))
    if failed_count == 0:
        failure_reason_str = ''
        cn_failure_reason_str = ''
        bs_failure_reason_str = ''
    else:
        reason_list = []
        for key, value in failure_reason.items():
            if len(value) > 0:
                value_str = json.dumps(value)
                reason_list.append('{0}: {1}'.format(key, value_str))
        failure_reason_str = '、'.join(reason_list)

        tmp_set = set()
        last_cn_reason_list = []
        bs_cn_reason_list = []
        for i in cn_reason_list:
            if i in tmp_set:
                continue
            # elif i in consts.BS_REASON:
            #     tmp_set.add(i)
            #     bs_cn_reason_list.append(i)
            else:
                tmp_set.add(i)
                last_cn_reason_list.append(i)
        cn_failure_reason_str = '\n'.join(last_cn_reason_list)
        bs_failure_reason_str = '\n'.join(bs_cn_reason_list)
    return compare_result, total_fields, failed_count, successful_at_this_level, failure_reason_str, cn_failure_reason_str, bs_failure_reason_str


def se_result_detect(ocr_res_dict):
    detect_list = []
    for license_en in consts.SE_DETECT_CARD:
        ocr_field, _, _ = consts.SE_COMPARE_FIELD[license_en]
        ocr_res_str = ocr_res_dict.get(ocr_field)
        detect_list.append(ocr_res_str is None)
    return detect_list


def se_compare_auto(application_id, application_entity, ocr_res_id, last_obj, ocr_res_dict, auto_obj):
    try:
        # 比对逻辑
        # detect_list = se_result_detect(ocr_res_dict)
        compare_info, aa_type, is_gsyh = get_se_cms_compare_info_auto(
            last_obj, application_entity)
        compare_result, total_fields, failed_count, successful_at_this_level, failure_reason_str, cn_failure_reason_str, bs_failure_reason_str = se_compare_process(compare_info, ocr_res_dict, is_gsyh)
        compare_log.info('{0} [Auto SE] [compare success] [entity={1}] [id={2}] [ocr_res_id={3}] [result={4}]'.format(
            log_base, application_entity, application_id, ocr_res_id, compare_result))
    except Exception as e:
        compare_log.error('{0} [Auto SE] [compare error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                          '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                               traceback.format_exc()))
    else:
        # 将比对结果写入数据库 auto settlement
        try:
            auto_obj.aa_type = aa_type
            auto_obj.ocr_auto_result_pass = successful_at_this_level
            auto_obj.ocr_auto_result = json.dumps(compare_result)
            auto_obj.ocr_latest_comparison_time = datetime.now()
            auto_obj.save()
            compare_log.info('{0} [Auto SE] [result save success] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                log_base, application_entity, application_id, ocr_res_id))
        except Exception as e:
            compare_log.error('{0} [Auto SE] [result save error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                              '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                                   traceback.format_exc()))


def se_compare(application_id, application_entity, ocr_res_id, last_obj, ocr_res_dict, is_cms):
    try:
        # 比对逻辑
        start_time = datetime.now()
        detect_list = se_result_detect(ocr_res_dict)
        # if is_cms:
        #     last_obj = rebuild_compare_info(last_obj, application_id)
        if is_cms:
            compare_info, application_version, is_gsyh = get_se_cms_compare_info(
                last_obj, application_entity, detect_list)
        else:
            compare_info, is_gsyh = get_se_compare_info(last_obj, application_entity, detect_list)
            application_version = last_obj.application_version
        compare_result, total_fields, failed_count, successful_at_this_level, failure_reason_str, cn_failure_reason_str, bs_failure_reason_str = se_compare_process(compare_info, ocr_res_dict, is_gsyh)
        compare_log.info('{0} [SE] [compare success] [entity={1}] [id={2}] [ocr_res_id={3}] [result={4}]'.format(
            log_base, application_entity, application_id, ocr_res_id, compare_result))
    except Exception as e:
        compare_log.error('{0} [SE] [compare error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                          '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                               traceback.format_exc()))
    else:
        # 将比对结果写入数据库
        try:
            result_table = HILSECompareResult if application_entity == consts.HIL_PREFIX else AFCSECompareResult
            res_obj = result_table.objects.filter(application_id=application_id).first()
            if res_obj is None:
                res_obj = result_table()
                res_obj.application_id = application_id
            res_obj.compare_count = total_fields
            res_obj.failed_count = failed_count
            res_obj.is_finish = successful_at_this_level
            source = consts.INFO_SOURCE[1] if is_cms else consts.INFO_SOURCE[0]
            res_obj.version = '{0}{1}{2}'.format(source, consts.SPLIT_STR, application_version)
            # res_obj.reason1_count = reason1_count
            res_obj.result = json.dumps(compare_result)
            res_obj.update_time = datetime.now()
            res_obj.save()
            compare_log.info('{0} [SE] [result save success] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                log_base, application_entity, application_id, ocr_res_id))
        except Exception as e:
            compare_log.error('{0} [SE] [result save error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                              '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                                   traceback.format_exc()))

        # report
        end_time = datetime.now()
        try:
            request_trigger = RequestTrigger.SUBMITING.value if ocr_res_id is None else RequestTrigger.UPLOADING.value
            report_class = HILCompareReport if application_entity == consts.HIL_PREFIX else AFCCompareReport
            report_class.objects.create(
                case_number=application_id,
                request_team=RequestTeam.SETTLEMENT.value,
                request_trigger=request_trigger,
                transaction_start=start_time,
                transaction_end=end_time,
                successful_at_this_level=successful_at_this_level,
                failure_reason=failure_reason_str,
                process_name=ProcessName.SE_CACOMPARE.value,
                total_fields=total_fields,
                workflow_name='' if is_cms else last_obj.customer_type,
            )
            compare_log.info('{0} [SE] [report save success] [entity={1}] [id={2}] [ocr_res_id={3}]'.format(
                    log_base, application_entity, application_id, ocr_res_id))
        except Exception as e:
            compare_log.error('{0} [SE] [report save error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                              '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                                   traceback.format_exc()))

        # cms结果发送
        # if is_cms:
        try:
            application_link = '{0}/showList/showList?entity={1}&scheme={2}&case_id={3}'.format(
                conf.BASE_URL, application_entity, consts.COMPARE_DOC_SCHEME_LIST[1], application_id)
            data = {
                "SubtenantId": consts.TENANT_MAP[application_entity],
                "Data": {
                    "Result_Message": "Pass" if successful_at_this_level else "Fail",
                    "Failure_Reason": cn_failure_reason_str,
                    "Application_Number": application_id,
                    "Bank_Statement": bs_failure_reason_str,
                    "Link_URL": application_link,
                    "OCR_Version": 1,
                    "Origin": consts.INFO_SOURCE[1]
                }
            }
            response = cms.send(data)
        except Exception as e:
            compare_log.error('{0} [SE] [cms error] [entity={1}] [id={2}] [ocr_res_id={3}] '
                              '[error={4}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                                   traceback.format_exc()))
        else:
            compare_log.info('{0} [SE] [cms success] [entity={1}] [id={2}] [ocr_res_id={3}] [data={4}] '
                             '[response={5}]'.format(log_base, application_entity, application_id, ocr_res_id,
                                                     data, response))


@app.task
def compare(application_id, application_entity, uniq_seq, ocr_res_id, is_ca=True, is_cms=False):
    # POS: application_id, application_entity, uniq_seq, None
    # OCR: application_id, business_type(application_entity), None, ocr_res_id

    compare_log.info('{0} [receive task] [entity={1}] [id={2}] [uniq_seq={3}] [ocr_res_id={4}] [is_ca={5}] '
                     '[is_cms={6}]'.format(log_base, application_entity, application_id, uniq_seq, ocr_res_id,
                                           is_ca, is_cms))

    # 根据application_id查找最新的比对信息,如果没有,结束
    if is_ca:
        comparison_class = HILComparisonInfo if application_entity == consts.HIL_PREFIX else AFCComparisonInfo
    else:
        if application_entity == consts.HIL_PREFIX:
            comparison_class = HILSECMSInfo if is_cms else HILSEComparisonInfo
        else:
            comparison_class = AFCSECMSInfo if is_cms else AFCSEComparisonInfo
    last_obj = comparison_class.objects.filter(application_id=application_id).last()
    if last_obj is None:
        compare_log.info('{0} [comparison info empty] [entity={1}] [id={2}] [uniq_seq={3}] [ocr_res_id={4}] '
                         '[is_ca={5}] [is_cms]={6}'.format(log_base, application_entity, application_id, uniq_seq,
                                                           ocr_res_id, is_ca, is_cms))
        return

    # 根据application_id查找OCR累计结果指定license字段,如果没有,结束
    if is_ca:
        result_class = HILOCRResult if application_entity == consts.HIL_PREFIX else AFCOCRResult
        ca_ocr_res_dict = dict()
    else:
        result_class = HILSEOCRResult if application_entity == consts.HIL_PREFIX else AFCSEOCRResult
        ca_result_class = HILOCRResult if application_entity == consts.HIL_PREFIX else AFCOCRResult
        # if ocr_res_id is None:
        ca_ocr_res_dict = ca_result_class.objects.filter(application_id=application_id).values(
            *consts.CA_ADD_COMPARE_FIELDS).first()
        # else:
        #     ca_ocr_res_dict = ca_result_class.objects.filter(id=ocr_res_id).values(
        #         *consts.CA_ADD_COMPARE_FIELDS).first()
    if ocr_res_id is None:
        ocr_res_dict = result_class.objects.filter(application_id=application_id).values(*consts.COMPARE_FIELDS).first()
    else:
        ocr_res_dict = result_class.objects.filter(id=ocr_res_id).values(*consts.COMPARE_FIELDS).first()
    if ocr_res_dict is None:
        compare_log.info('{0} [ocr info empty] [entity={1}] [id={2}] [uniq_seq={3}] [ocr_res_id={4}] '
                         '[is_ca={5}] [is_cms]={6}'.format(log_base, application_entity, application_id,
                                                           uniq_seq, ocr_res_id, is_ca, is_cms))
        return

    if is_ca:
        ca_compare(application_id, application_entity, ocr_res_id, last_obj, ocr_res_dict)
    else:
        for field_name in consts.CA_ADD_COMPARE_FIELDS:
            if isinstance(ca_ocr_res_dict, dict) and isinstance(ca_ocr_res_dict.get(field_name), str):
                tmp_ca_result = json.loads(ca_ocr_res_dict.get(field_name))
                if isinstance(ocr_res_dict.get(field_name), str):
                    tmp_se_result = json.loads(ocr_res_dict.get(field_name))
                    tmp_ca_result.extend(tmp_se_result)
                ocr_res_dict[field_name] = json.dumps(tmp_ca_result)
        # auto settlement
        auto_class = HILAutoSettlement if application_entity == consts.HIL_PREFIX else AFCAutoSettlement
        auto_obj = auto_class.objects.filter(application_id=application_id, on_off=True).first()
        if auto_obj is not None:
            se_compare_auto(application_id, application_entity, ocr_res_id, last_obj, ocr_res_dict, auto_obj)
        se_compare(application_id, application_entity, ocr_res_id, last_obj, ocr_res_dict, is_cms)