summaryrefslogtreecommitdiff
path: root/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs
blob: f6e2cdfa3cb55b30cd1981da92878625efef8b8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
using AutoMapper;
using Gestor.Common.Helpers;
using Gestor.Common.Validation;
using Gestor.Infrastructure.Entities.Generic;
using Gestor.Infrastructure.Entities.Seguros;
using Gestor.Infrastructure.Helpers;
using Gestor.Infrastructure.Mappers;
using Gestor.Infrastructure.Repository.Generic;
using Gestor.Infrastructure.Repository.Interface;
using Gestor.Infrastructure.UnitOfWork.Generic;
using Gestor.Model.Common;
using Gestor.Model.Domain.Aggilizador;
using Gestor.Model.Domain.Common;
using Gestor.Model.Domain.Generic;
using Gestor.Model.Domain.Relatorios;
using Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao;
using Gestor.Model.Domain.Seguros;
using NHibernate;
using NHibernate.Connection;
using NHibernate.Impl;
using NHibernate.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace Gestor.Infrastructure.Repository.Logic
{
	public class ParcelaRepository : GenericRepository<ParcelaDb>, IParcelaRepository, IGenericRepository<ParcelaDb>
	{
		private readonly GenericUnitOfWork _unitOfWork;

		public ParcelaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
		{
			this._unitOfWork = unitOfWork;
		}

		public async Task<List<Documento>> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false)
		{
			List<Documento> documentos = new List<Documento>();
			return await this.BuscaDocumentosPorVigenciaNew(filtro, buscaAssinaturas, painelBi);
		}

		private async Task<List<Documento>> BuscaDocumentosPorVigenciaNew(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false)
		{
			NegocioCorretora fieldValue;
			Predicate<Estipulante> predicate;
			object connection;
			bool count;
			string str;
			bool flag;
			object vendedor;
			bool count1;
			Documento documento1;
			List<Item> itensAtivo;
			object produto;
			object obj;
			object statu;
			object banco;
			List<StatusDocumentoAssinado> statusDocumentoAssinados;
			bool flag1;
			StatusAssinatura statusAssinatura;
			NegocioCorretora negocioCorretora;
			bool count2;
			bool flag2;
			Predicate<Estipulante> predicate1 = null;
			Predicate<Estipulante> predicate2 = null;
			Predicate<Estipulante> predicate3 = null;
			Predicate<Estipulante> predicate4 = null;
			Predicate<Estipulante> predicate5 = null;
			List<Documento> documentos = new List<Documento>();
			string str1 = "CAST(f.vigenciai AS DATE)";
			string referencia = filtro.Referencia;
			if (referencia == "EMISSÃO")
			{
				str1 = "CAST(f.emissao AS DATE)";
			}
			else if (referencia == "TRANSMISSÃO PROPOSTA")
			{
				str1 = "CAST(d.remessa AS DATE)";
			}
			else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO")
			{
				str1 = "CAST(p.cri_data AS DATE)";
			}
			List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, str1);
			List<Condicao> condicaos1 = new List<Condicao>();
			Condicao condicao = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = null,
				Grupo = 1,
				Operacao = Operacao.Or
			};
			condicaos1.Add(condicao);
			Condicao condicao1 = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = "0".CriarValor<string>(),
				Grupo = 1,
				Operacao = Operacao.Or
			};
			condicaos1.Add(condicao1);
			condicaos.AddRange(condicaos1);
			SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0);
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					bool flag3 = await this.ExisteTabelasAssinatura();
					bool flag4 = flag3;
					List<Parcela> parcelas = new List<Parcela>();
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandTimeout = 1000;
						string str2 = "SELECT f.IDFATURA IdFatura, p.IDPARCELA IdParcela, d.IDDOCUMENTO IdDocumento, c.IDEMPRESA IdEmpresa, c.IDCLIENTE IdCliente, clie.CGCCPF DocumentoCliente, clie.MalaDireta MalaDireta, clie.NOME NomeCliente, clie.pasta PastaCliente, c.IDCONTROLE IdControle, cm.idclimail IdEmail, cm.email, ct.idclitelefone IdTelefone, ct.ddd Prefixo, ct.fone Numero, d.CONTRATO Apolice, d.PROPOSTA Proposta, d.PEDADIT PropostaEndosso, f.NumFatura NumeroFatura, f.Emissao EmissaoFatura, d.idnegocio Negocio, d.SITUACAO Situacao, f.VIGENCIAI VigenciaInicial, f.VIGENCIAF VigenciaFinal, p.VALOR PremioTotal, p.VALORLF PremioLiquido, p.comiss Comissao, c.IDRAMO IdRamo, r.NOME NomeRamo, c.IDCIASEG IdCiaSeg, cia.NOME NomeCia, cia.NomeSocial NomeSocialCia, c.IDPRODUTO IdProduto, pr.NOME NomeProduto, d.idestipulante IdEstipulante,d.idestipulante2 IdEstipulante2,d.idestipulante3 IdEstipulante3,d.idestipulante4 IdEstipulante4,d.idestipulante5 IdEstipulante5, e.nome NomeEstipulante, d.NegocioCorretora NegocioCorretora, p.datacontrole DataControleParcela, d.idstatus IdStatus, s.nome NomeStatus, p.CRI_DATA DataCriacaoParcela, d.TIPO Tipo, d.REMESSA Remessa, d.idbanco IdBanco, b.NOMEBANCO NomeBanco, d.AGENCIA Agencia, d.CONTA Conta, d.PASTA PastaDocumento, d.apoconferida ApoliceConferida, d.propassinada PropostaAssinada, vp.IDVENDEDORPARCELA IdVendedorParcela, vp.idtipovendedor IdTipoVendedor, vp.IDVENDEDOR IdVendedor, vp.VREP PorcentagemRepasse, v.NOME NomeVendedor FROM fatura f INNER JOIN parcela p ON p.IDPARCELA = f.IDPARCELA INNER JOIN documento d ON d.IDDOCUMENTO = p.IDDOCUMENTO INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN codigobanco b ON b.IDCODIGOBANCO = d.IDBANCO LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDPARCELA = f.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE ";
						sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao, " ORDER BY f.IDPARCELA, d.IDDOCUMENTO, d.IDCONTROLE, vp.idtipovendedor, vp.IDVENDEDOR");
						sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
						using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
						{
							while (true)
							{
								if (!await sqlDataReader.ReadAsync())
								{
									break;
								}
								TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue<TipoSeguro>("Situacao", true, true);
								if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora"))
								{
									fieldValue = sqlDataReader.GetFieldValue<NegocioCorretora>("NegocioCorretora", true, true);
								}
								else
								{
									flag3 = tipoSeguro == TipoSeguro.Renovacao;
									if (flag3)
									{
										flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio");
									}
									negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue<string>("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
									fieldValue = negocioCorretora;
								}
								NegocioCorretora negocioCorretora1 = fieldValue;
								List<long> negocio = filtro.Negocio;
								if (negocio != null)
								{
									count = negocio.Count > 0;
								}
								else
								{
									count = false;
								}
								if (!count || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora1))
								{
									List<Estipulante> estipulantes = new List<Estipulante>();
									sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
									if (sqlDataReader.GetFieldValue<long>("idestipulante", true, true) != 0)
									{
										List<Estipulante> estipulantes1 = estipulantes;
										Estipulante nome = new Estipulante();
										List<Estipulante> estipulantes2 = Auxiliar.Estipulantes;
										Predicate<Estipulante> predicate6 = predicate1;
										if (predicate6 == null)
										{
											Predicate<Estipulante> predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
											predicate = predicate7;
											predicate1 = predicate7;
											predicate6 = predicate;
										}
										nome.Nome = estipulantes2.Find(predicate6).Nome;
										estipulantes1.Add(nome);
									}
									sqlDataReader.GetFieldValue<long>("idestipulante2", true, true);
									if (sqlDataReader.GetFieldValue<long>("idestipulante2", true, true) != 0)
									{
										List<Estipulante> estipulantes3 = estipulantes;
										Estipulante nome1 = new Estipulante();
										List<Estipulante> estipulantes4 = Auxiliar.Estipulantes;
										Predicate<Estipulante> predicate8 = predicate2;
										if (predicate8 == null)
										{
											Predicate<Estipulante> predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante2", true, true);
											predicate = predicate9;
											predicate2 = predicate9;
											predicate8 = predicate;
										}
										nome1.Nome = estipulantes4.Find(predicate8).Nome;
										estipulantes3.Add(nome1);
									}
									sqlDataReader.GetFieldValue<long>("idestipulante3", true, true);
									if (sqlDataReader.GetFieldValue<long>("idestipulante3", true, true) != 0)
									{
										List<Estipulante> estipulantes5 = estipulantes;
										Estipulante estipulante1 = new Estipulante();
										List<Estipulante> estipulantes6 = Auxiliar.Estipulantes;
										Predicate<Estipulante> predicate10 = predicate3;
										if (predicate10 == null)
										{
											Predicate<Estipulante> predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante3", true, true);
											predicate = predicate11;
											predicate3 = predicate11;
											predicate10 = predicate;
										}
										estipulante1.Nome = estipulantes6.Find(predicate10).Nome;
										estipulantes5.Add(estipulante1);
									}
									sqlDataReader.GetFieldValue<long>("idestipulante4", true, true);
									if (sqlDataReader.GetFieldValue<long>("idestipulante4", true, true) != 0)
									{
										List<Estipulante> estipulantes7 = estipulantes;
										Estipulante nome2 = new Estipulante();
										List<Estipulante> estipulantes8 = Auxiliar.Estipulantes;
										Predicate<Estipulante> predicate12 = predicate4;
										if (predicate12 == null)
										{
											Predicate<Estipulante> predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante4", true, true);
											predicate = predicate13;
											predicate4 = predicate13;
											predicate12 = predicate;
										}
										nome2.Nome = estipulantes8.Find(predicate12).Nome;
										estipulantes7.Add(nome2);
									}
									sqlDataReader.GetFieldValue<long>("idestipulante5", true, true);
									if (sqlDataReader.GetFieldValue<long>("idestipulante5", true, true) != 0)
									{
										List<Estipulante> estipulantes9 = estipulantes;
										Estipulante estipulante2 = new Estipulante();
										List<Estipulante> estipulantes10 = Auxiliar.Estipulantes;
										Predicate<Estipulante> predicate14 = predicate5;
										if (predicate14 == null)
										{
											Predicate<Estipulante> predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante5", true, true);
											predicate = predicate15;
											predicate5 = predicate15;
											predicate14 = predicate;
										}
										estipulante2.Nome = estipulantes10.Find(predicate14).Nome;
										estipulantes9.Add(estipulante2);
									}
									if (estipulantes.Count > 0)
									{
										List<Estipulante> estipulantes11 = estipulantes;
										str = string.Join(" | ", 
											from estipulante in estipulantes11
											select estipulante.Nome);
									}
									else
									{
										str = "";
									}
									string str3 = str;
									long num = sqlDataReader.GetFieldValue<long>("IdDocumento", true, true);
									long fieldValue1 = sqlDataReader.GetFieldValue<long>("IdParcela", true, true);
									Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1);
									if (observableCollection == null)
									{
										Parcela parcela = parcelas.Find((Parcela d) => d.Documento.Id == num);
										if (parcela != null)
										{
											documento1 = parcela.Documento;
										}
										else
										{
											documento1 = null;
										}
										Documento zero = documento1;
										if (zero != null)
										{
											zero = zero.DeepCopy();
										}
										else
										{
											long num1 = sqlDataReader.GetFieldValue<long>("IdControle", true, true);
											long fieldValue2 = sqlDataReader.GetFieldValue<long>("IdEmpresa", true, true);
											Documento documento2 = documentos.Find((Documento p) => p.Controle.Id == num1);
											if (documento2 != null)
											{
												itensAtivo = documento2.ItensAtivo;
											}
											else
											{
												itensAtivo = null;
											}
											List<Item> items = itensAtivo;
											if (items == null)
											{
												items = await this.BuscaItemsPorIdControle(num1);
											}
											Documento valueOrDefault = new Documento()
											{
												Id = num
											};
											Controle controle = new Controle()
											{
												Id = num1,
												IdEmpresa = fieldValue2
											};
											Cliente cliente = new Cliente()
											{
												Id = sqlDataReader.GetFieldValue<long>("IdCliente", true, true),
												Nome = sqlDataReader.GetFieldValue<string>("NomeCliente", true, true),
												Documento = sqlDataReader.GetFieldValue<string>("DocumentoCliente", true, true),
												Pasta = sqlDataReader.GetFieldValue<string>("PastaCliente", true, true)
											};
											bool? fieldValue3 = sqlDataReader.GetFieldValue<bool?>("MalaDireta", true, true);
											cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true));
											ObservableCollection<ClienteTelefone> observableCollection1 = new ObservableCollection<ClienteTelefone>();
											ClienteTelefone clienteTelefone = new ClienteTelefone()
											{
												Id = sqlDataReader.GetFieldValue<long>("IdTelefone", true, true),
												Prefixo = sqlDataReader.GetFieldValue<string>("Prefixo", true, true),
												Numero = sqlDataReader.GetFieldValue<string>("Numero", true, true)
											};
											observableCollection1.Add(clienteTelefone);
											cliente.Telefones = observableCollection1;
											ObservableCollection<ClienteEmail> observableCollection2 = new ObservableCollection<ClienteEmail>();
											ClienteEmail clienteEmail = new ClienteEmail()
											{
												Id = sqlDataReader.GetFieldValue<long>("IdEmail", true, true),
												Email = sqlDataReader.GetFieldValue<string>("Email", true, true)
											};
											observableCollection2.Add(clienteEmail);
											cliente.Emails = observableCollection2;
											controle.Cliente = cliente;
											Ramo ramo = new Ramo()
											{
												Id = sqlDataReader.GetFieldValue<long>("IdRamo", true, true),
												Nome = sqlDataReader.GetFieldValue<string>("NomeRamo", true, true)
											};
											controle.Ramo = ramo;
											Seguradora seguradora = new Seguradora()
											{
												Id = sqlDataReader.GetFieldValue<long>("IdCiaSeg", true, true),
												Nome = sqlDataReader.GetFieldValue<string>("NomeCia", true, true),
												NomeSocial = sqlDataReader.GetFieldValue<string>("NomeSocialCia", true, true)
											};
											controle.Seguradora = seguradora;
											if (sqlDataReader.FieldIsNull("IdProduto"))
											{
												produto = null;
											}
											else
											{
												produto = new Produto();
												((DomainBase)produto).Id = sqlDataReader.GetFieldValue<long>("IdProduto", true, true);
												((Produto)produto).Nome = sqlDataReader.GetFieldValue<string>("NomeProduto", true, true);
											}
											controle.Produto = (Produto)produto;
											valueOrDefault.Controle = controle;
											if (sqlDataReader.FieldIsNull("IdEstipulante"))
											{
												obj = null;
											}
											else
											{
												obj = new Estipulante();
												((DomainBase)obj).Id = sqlDataReader.GetFieldValue<long>("IdEstipulante", true, true);
												((Estipulante)obj).Nome = sqlDataReader.GetFieldValue<string>("NomeEstipulante", true, true);
											}
											valueOrDefault.Estipulante1 = (Estipulante)obj;
											valueOrDefault.Estipulantes = str3;
											if (sqlDataReader.FieldIsNull("IdStatus"))
											{
												statu = null;
											}
											else
											{
												statu = new Status();
												((DomainBase)statu).Id = sqlDataReader.GetFieldValue<long>("IdStatus", true, true);
												((Status)statu).Nome = sqlDataReader.GetFieldValue<string>("NomeStatus", true, true);
											}
											valueOrDefault.Status = (Status)statu;
											valueOrDefault.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura);
											valueOrDefault.Tipo = sqlDataReader.GetFieldValue<int>("Tipo", true, true);
											valueOrDefault.NegocioCorretora = new NegocioCorretora?(negocioCorretora1);
											valueOrDefault.Situacao = tipoSeguro;
											fieldValue3 = sqlDataReader.GetFieldValue<bool?>("ApoliceConferida", true, true);
											valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault();
											fieldValue3 = sqlDataReader.GetFieldValue<bool?>("PropostaAssinada", true, true);
											valueOrDefault.PropostaAssinada = fieldValue3.GetValueOrDefault();
											valueOrDefault.Proposta = sqlDataReader.GetFieldValue<string>("Proposta", true, true);
											valueOrDefault.Apolice = sqlDataReader.GetFieldValue<string>("Apolice", true, true);
											valueOrDefault.PropostaEndosso = sqlDataReader.GetFieldValue<string>("PropostaEndosso", true, true);
											valueOrDefault.Remessa = sqlDataReader.GetFieldValue<DateTime?>("Remessa", true, true);
											valueOrDefault.DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleParcela", true, true);
											valueOrDefault.DataCriacao = sqlDataReader.GetFieldValue<DateTime?>("DataCriacaoParcela", true, true);
											valueOrDefault.Pasta = sqlDataReader.GetFieldValue<string>("PastaDocumento", true, true);
											if (sqlDataReader.FieldIsNull("IdBanco"))
											{
												banco = null;
											}
											else
											{
												banco = new Banco();
												((Banco)banco).Id = sqlDataReader.GetFieldValue<int>("IdBanco", true, true);
												((Banco)banco).Nome = sqlDataReader.GetFieldValue<string>("NomeBanco", true, true);
											}
											valueOrDefault.Banco = (Banco)banco;
											valueOrDefault.Agencia = sqlDataReader.GetFieldValue<string>("Agencia", true, true);
											valueOrDefault.Conta = sqlDataReader.GetFieldValue<string>("Conta", true, true);
											valueOrDefault.ItensAtivo = items;
											zero = valueOrDefault;
											if (flag4 & buscaAssinaturas)
											{
												List<StatusDocumentoAssinado> statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(zero.Id);
												string str4 = (zero.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO");
												statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => {
													if (a.Documento.ToUpper() == str4 || a.Documento.ToUpper().Contains(str4))
													{
														a.Selecionado = true;
													}
												});
												List<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados1;
												StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault<StatusDocumentoAssinado>((StatusDocumentoAssinado a) => a.Selecionado);
												Documento documento3 = zero;
												if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0)
												{
													statusDocumentoAssinados = null;
												}
												else
												{
													statusDocumentoAssinados = statusDocumentoAssinados1;
												}
												documento3.Assinaturas = statusDocumentoAssinados;
												Documento documento4 = zero;
												flag1 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false);
												documento4.AssinadaSiggner = flag1;
												Documento documento5 = zero;
												statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado);
												documento5.StatusAssinatura = statusAssinatura;
											}
										}
										zero.Tipo = 2;
										zero.AdicionalComiss = false;
										zero.PremioAdicional = decimal.Zero;
										zero.NumeroParcelas = decimal.One;
										zero.Endosso = string.Concat("F ", sqlDataReader.GetFieldValue<string>("NumeroFatura", true, true));
										zero.Comissao = sqlDataReader.GetFieldValue<decimal>("Comissao", true, true);
										zero.PremioLiquido = sqlDataReader.GetFieldValue<decimal>("PremioLiquido", true, true);
										zero.PremioTotal = sqlDataReader.GetFieldValue<decimal>("PremioTotal", true, true);
										zero.Vigencia1 = sqlDataReader.GetFieldValue<DateTime>("VigenciaInicial", true, true);
										zero.Vigencia2 = sqlDataReader.GetFieldValue<DateTime?>("VigenciaFinal", true, true);
										zero.Emissao = sqlDataReader.GetFieldValue<DateTime?>("EmissaoFatura", true, true);
										zero.DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleParcela", true, true);
										if (zero.Controle.Cliente.Telefones != null)
										{
											long num2 = sqlDataReader.GetFieldValue<long>("IdTelefone", true, true);
											if (zero.Controle.Cliente.Telefones.FirstOrDefault<ClienteTelefone>((ClienteTelefone t) => t.Id == num2) == null)
											{
												ObservableCollection<ClienteTelefone> telefones = zero.Controle.Cliente.Telefones;
												ClienteTelefone clienteTelefone1 = new ClienteTelefone()
												{
													Id = num2,
													Prefixo = sqlDataReader.GetFieldValue<string>("Prefixo", true, true),
													Numero = sqlDataReader.GetFieldValue<string>("Numero", true, true)
												};
												telefones.Add(clienteTelefone1);
											}
										}
										if (zero.Controle.Cliente.Emails != null)
										{
											long num3 = sqlDataReader.GetFieldValue<long>("IdEmail", true, true);
											if (zero.Controle.Cliente.Emails.FirstOrDefault<ClienteEmail>((ClienteEmail t) => t.Id == num3) == null)
											{
												ObservableCollection<ClienteEmail> emails = zero.Controle.Cliente.Emails;
												ClienteEmail clienteEmail1 = new ClienteEmail()
												{
													Id = num3,
													Email = sqlDataReader.GetFieldValue<string>("Email", true, true)
												};
												emails.Add(clienteEmail1);
											}
										}
										Parcela parcela1 = new Parcela()
										{
											Id = fieldValue1,
											Documento = zero
										};
										observableCollection = parcela1;
										parcelas.Add(observableCollection);
										zero = null;
									}
									List<long> tipoVendedor = filtro.TipoVendedor;
									if (tipoVendedor != null)
									{
										flag = tipoVendedor.Count > 0;
									}
									else
									{
										flag = false;
									}
									if (!flag)
									{
										List<long> nums = filtro.Vendedores;
										if (nums != null)
										{
											count1 = nums.Count > 0;
										}
										else
										{
											count1 = false;
										}
										if (!count1)
										{
											if (observableCollection.Vendedores == null)
											{
												observableCollection.Vendedores = new ObservableCollection<VendedorParcela>();
											}
											long fieldValue4 = sqlDataReader.GetFieldValue<long>("IdTipoVendedor", true, true);
											long num4 = sqlDataReader.GetFieldValue<long>("IdVendedor", true, true);
											if (observableCollection.Vendedores.ToList<VendedorParcela>().Find((VendedorParcela vps) => {
												if (vps.TipoVendedor.Id != fieldValue4)
												{
													return false;
												}
												return vps.Vendedor.Id == num4;
											}) == null)
											{
												ObservableCollection<VendedorParcela> observableCollection3 = observableCollection.Vendedores;
												VendedorParcela vendedorParcela1 = new VendedorParcela()
												{
													PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue<decimal>("PorcentagemRepasse", true, true)),
													TipoVendedor = new TipoVendedor()
													{
														Id = fieldValue4
													}
												};
												Vendedor vendedor1 = new Vendedor()
												{
													Id = num4,
													Nome = sqlDataReader.GetFieldValue<string>("NomeVendedor", true, true)
												};
												vendedorParcela1.Vendedor = vendedor1;
												observableCollection3.Add(vendedorParcela1);
											}
										}
									}
									if (observableCollection.Documento.VendedorPrincipal == null)
									{
										Documento documento6 = observableCollection.Documento;
										if (sqlDataReader.FieldIsNull("IdVendedor"))
										{
											vendedor = null;
										}
										else
										{
											vendedor = new Vendedor();
											((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue<long>("IdVendedor", true, true);
											((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue<string>("NomeVendedor", true, true);
										}
										documento6.VendedorPrincipal = (Vendedor)vendedor;
									}
									str3 = null;
								}
							}
						}
					}
					sqlCommand = null;
					List<long> tipoVendedor1 = filtro.TipoVendedor;
					if (tipoVendedor1 != null)
					{
						count2 = tipoVendedor1.Count > 0;
					}
					else
					{
						count2 = false;
					}
					if (!count2)
					{
						List<long> nums1 = filtro.Vendedores;
						if (nums1 != null)
						{
							flag2 = nums1.Count > 0;
						}
						else
						{
							flag2 = false;
						}
						if (!flag2)
						{
							goto Label0;
						}
					}
					foreach (Parcela parcela2 in parcelas)
					{
						Parcela parcela3 = parcela2;
						List<VendedorParcela> vendedorParcelas1 = await this.BuscaVendedoresPorIdParcela(parcela2.Id, parcela2.Documento.Controle.IdEmpresa, (long)1);
						parcela3.Vendedores = new ObservableCollection<VendedorParcela>(vendedorParcelas1);
						parcela3 = null;
					}
				Label0:
					parcelas.ForEach((Parcela p) => {
						decimal? nullable2;
						decimal? porcentagemRepasse;
						ObservableCollection<VendedorParcela> vendedores = p.Vendedores;
						Func<VendedorParcela, long> u003cu003e9_1516 = ParcelaRepository.u003cu003ec.u003cu003e9__15_16;
						if (u003cu003e9_1516 == null)
						{
							u003cu003e9_1516 = (VendedorParcela tipo) => tipo.TipoVendedor.Id;
							ParcelaRepository.u003cu003ec.u003cu003e9__15_16 = u003cu003e9_1516;
						}
						IOrderedEnumerable<VendedorParcela> vendedorParcelas = vendedores.OrderBy<VendedorParcela, long>(u003cu003e9_1516);
						Func<VendedorParcela, Vendedor> u003cu003e9_1517 = ParcelaRepository.u003cu003ec.u003cu003e9__15_17;
						if (u003cu003e9_1517 == null)
						{
							u003cu003e9_1517 = (VendedorParcela v) => v.Vendedor;
							ParcelaRepository.u003cu003ec.u003cu003e9__15_17 = u003cu003e9_1517;
						}
						List<Vendedor> list = vendedorParcelas.Select<VendedorParcela, Vendedor>(u003cu003e9_1517).ToList<Vendedor>();
						p.Documento.Vendedores = list;
						Documento documento = p.Documento;
						VendedorParcela vendedorParcela = p.Vendedores.FirstOrDefault<VendedorParcela>((VendedorParcela v) => {
							long? nullable;
							long id = v.Vendedor.Id;
							Vendedor vendedorPrincipal = p.Documento.VendedorPrincipal;
							nullable = (vendedorPrincipal != null ? new long?(vendedorPrincipal.Id) : null);
							long? nullable1 = nullable;
							return id == nullable1.GetValueOrDefault() & nullable1.HasValue;
						});
						if (vendedorParcela != null)
						{
							porcentagemRepasse = vendedorParcela.PorcentagemRepasse;
						}
						else
						{
							nullable2 = null;
							porcentagemRepasse = nullable2;
						}
						nullable2 = porcentagemRepasse;
						documento.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault());
						documentos.Add(p.Documento);
					});
					parcelas = null;
				}
				sqlConnection = null;
			}
			sessionFactory = null;
			List<Documento> documentos1 = documentos;
			sqlQueryCondition = null;
			return documentos1;
		}

		private async Task<List<Documento>> BuscaDocumentosPorVigenciaPrivate(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false)
		{
			NegocioCorretora negocioCorretora;
			List<long>.Enumerator enumerator;
			decimal? nullable;
			DateTime? nullable1;
			object connection;
			bool count;
			string str;
			bool flag;
			Seguradora seguradora;
			Ramo ramo1;
			Produto produto1;
			bool flag1;
			Negocio negocio;
			DateTime? nullable2;
			DateTime dateTime;
			DateTime? nullable3;
			DateTime? nullable4;
			Estipulante estipulante1;
			DateTime? nullable5;
			Status statu;
			bool flag2;
			List<StatusDocumentoAssinado> statusDocumentoAssinados;
			bool flag3;
			StatusAssinatura statusAssinatura;
			DateTime? nullable6;
			decimal? porcentagemRepasse;
			List<long> list;
			List<long> nums;
			NegocioCorretora negocioCorretora1;
			bool count1;
			Func<VendedorParcela, bool> func = null;
			Func<Seguradora, bool> func1 = null;
			Func<Ramo, bool> func2 = null;
			Func<Produto, bool> func3 = null;
			Func<Estipulante, bool> func4 = null;
			Func<Status, bool> func5 = null;
			List<Documento> documentos = new List<Documento>();
			string str1 = "CAST(f.vigenciai AS DATE)";
			string referencia = filtro.Referencia;
			if (referencia == "EMISSÃO")
			{
				str1 = "CAST(f.emissao AS DATE)";
			}
			else if (referencia == "TRANSMISSÃO PROPOSTA")
			{
				str1 = "CAST(d.remessa AS DATE)";
			}
			else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO")
			{
				str1 = "CAST(p.cri_data AS DATE)";
			}
			List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, str1);
			List<Condicao> condicaos1 = new List<Condicao>();
			Condicao condicao = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = null,
				Grupo = 1,
				Operacao = Operacao.Or
			};
			condicaos1.Add(condicao);
			Condicao condicao1 = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = "0".CriarValor<string>(),
				Grupo = 1,
				Operacao = Operacao.Or
			};
			condicaos1.Add(condicao1);
			condicaos.AddRange(condicaos1);
			SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0);
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandTimeout = 0;
						Auxiliar.CriarAuxiliar(sqlCommand, false);
						bool flag4 = await this.ExisteTabelasAssinatura();
						bool flag5 = flag4;
						List<long> tipoVendedor = filtro.TipoVendedor;
						if (tipoVendedor != null)
						{
							count = tipoVendedor.Count > 0;
						}
						else
						{
							count = false;
						}
						if (!count)
						{
							List<long> vendedores = filtro.Vendedores;
							if (vendedores != null)
							{
								count1 = vendedores.Count > 0;
							}
							else
							{
								count1 = false;
							}
							if (count1)
							{
								goto Label1;
							}
							str = "";
							goto Label0;
						}
					Label1:
						str = "INNER JOIN vendedorparcela vp ON p.idparcela = vp.idparcela";
					Label0:
						string str2 = string.Concat("SELECT DISTINCT c.IdEmpresa,c.IdCliente,cli.CGCCPF,cli.MalaDireta,cli.Nome,d.IdControle,p.IdParcela,d.IdDocumento,d.Contrato,f.NumFatura,f.Emissao,d.IdNegocio,d.Situacao,f.VigenciaI,f.VigenciaF,ISNULL(p.Valor, 0.00) Total,ISNULL(p.ValorLF, 0.00) Liquido,ISNULL(p.comiss, 0.00) Comissao,c.IdRamo,c.IdCiaSeg,c.IdProduto,d.IdEstipulante,d.NegocioCorretora,p.DataControle,d.IdStatus,p.Cri_Data,d.Remessa,d.IdBanco,cb.NomeBanco,d.Agencia,d.Conta,d.Pasta,d.ApoConferida,d.PropAssinada,cli.pasta PastaCliente FROM fatura f INNER JOIN parcela p ON p.IdParcela = f.IdParcela ", str, " INNER JOIN documento d ON d.IdDocumento = p.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle INNER JOIN cliente cli ON cli.IdCliente = c.IdCliente LEFT JOIN codigobanco cb ON d.idbanco = cb.idcodigobanco WHERE ");
						sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao);
						sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
						using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
						{
							while (true)
							{
								if (!await sqlDataReader.ReadAsync())
								{
									break;
								}
								long item = (long)sqlDataReader["idparcela"];
								long num = (long)sqlDataReader["iddocumento"];
								long item1 = (long)sqlDataReader["idcontrole"];
								long num1 = (long)sqlDataReader["idempresa"];
								string str3 = "PEDIDO DE ENDOSSO";
								if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora")))
								{
									negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString());
								}
								else
								{
									flag4 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao;
									if (flag4)
									{
										flag4 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio"));
									}
									negocioCorretora1 = (!flag4 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
									negocioCorretora = negocioCorretora1;
								}
								NegocioCorretora negocioCorretora2 = negocioCorretora;
								Vendedor vendedor = new Vendedor();
								List<Vendedor> vendedors = new List<Vendedor>();
								List<Item> items = new List<Item>();
								List<StatusDocumentoAssinado> statusDocumentoAssinados1 = new List<StatusDocumentoAssinado>();
								StatusDocumentoAssinado statusDocumentoAssinado = null;
								decimal valueOrDefault = new decimal();
								if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora2))
								{
									if (!painelBi)
									{
										List<VendedorParcela> vendedorParcelas = await this.BuscaVendedoresPorIdParcela(item, num1, (long)1);
										if (filtro.Vendedores != null && filtro.Vendedores.Count > 0)
										{
											bool flag6 = true;
											foreach (long list1 in filtro.Vendedores.ToList<long>())
											{
												if (!vendedorParcelas.Any<VendedorParcela>((VendedorParcela v) => v.Vendedor.Id == list1))
												{
													continue;
												}
												flag6 = false;
											}
											if (flag6)
											{
												continue;
											}
										}
										List<VendedorParcela> vendedorParcelas1 = vendedorParcelas;
										IOrderedEnumerable<VendedorParcela> id = 
											from tipo in vendedorParcelas1
											orderby tipo.TipoVendedor.Id
											select tipo;
										vendedors = (
											from v in id
											select v.Vendedor).ToList<Vendedor>();
										if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count != 0)
										{
											if (filtro.TipoVendedor != null)
											{
												List<long> tipoVendedor1 = filtro.TipoVendedor;
												if (tipoVendedor1.Any<long>((long v) => v == (long)1))
												{
													goto Label3;
												}
											}
											Vendedor vendedor1 = null;
											Filtros filtro1 = filtro;
											if (filtro1 != null)
											{
												List<long> nums1 = filtro1.TipoVendedor;
												if (nums1 != null)
												{
													list = (
														from t in nums1
														orderby t
														select t).ToList<long>();
												}
												else
												{
													list = null;
												}
											}
											else
											{
												list = null;
											}
											enumerator = list.GetEnumerator();
											try
											{
												do
												{
													if (!enumerator.MoveNext())
													{
														break;
													}
													long current = enumerator.Current;
													Filtros filtro2 = filtro;
													if (filtro2 != null)
													{
														List<long> vendedores1 = filtro2.Vendedores;
														if (vendedores1 != null)
														{
															nums = vendedores1.ToList<long>();
														}
														else
														{
															nums = null;
														}
													}
													else
													{
														nums = null;
													}
													List<long>.Enumerator enumerator1 = nums.GetEnumerator();
													try
													{
														do
														{
															if (!enumerator1.MoveNext())
															{
																break;
															}
															long current1 = enumerator1.Current;
															IEnumerable<VendedorParcela> vendedorParcelas2 = vendedorParcelas.Where<VendedorParcela>((VendedorParcela v) => {
																if (v.TipoVendedor.Id != current)
																{
																	return false;
																}
																return v.Vendedor.Id == current1;
															});
															vendedor1 = (
																from v in vendedorParcelas2
																select v.Vendedor).FirstOrDefault<Vendedor>();
														}
														while (vendedor1 == null);
													}
													finally
													{
														((IDisposable)enumerator1).Dispose();
													}
												}
												while (vendedor1 == null);
											}
											finally
											{
												((IDisposable)enumerator).Dispose();
											}
											if ((filtro.Vendedores == null || filtro.Vendedores.Count == 0) && vendedor1 == null)
											{
												List<VendedorParcela> vendedorParcelas3 = vendedorParcelas;
												Func<VendedorParcela, bool> func6 = func;
												if (func6 == null)
												{
													Func<VendedorParcela, bool> id1 = (VendedorParcela v) => v.TipoVendedor.Id == filtro.TipoVendedor.FirstOrDefault<long>();
													Func<VendedorParcela, bool> func7 = id1;
													func = id1;
													func6 = func7;
												}
												IEnumerable<VendedorParcela> vendedorParcelas4 = vendedorParcelas3.Where<VendedorParcela>(func6);
												vendedor1 = (
													from v in vendedorParcelas4
													select v.Vendedor).FirstOrDefault<Vendedor>();
											}
											Vendedor vendedor2 = vendedor1;
											if (vendedor2 == null)
											{
												vendedor2 = vendedors.FirstOrDefault<Vendedor>();
											}
											vendedor = vendedor2;
											goto Label2;
										}
										List<VendedorParcela> vendedorParcelas5 = vendedorParcelas;
										IEnumerable<VendedorParcela> id2 = 
											from v in vendedorParcelas5
											where v.TipoVendedor.Id == (long)1
											select v;
										vendedor = (
											from v in id2
											select v.Vendedor).FirstOrDefault<Vendedor>();
									Label2:
										VendedorParcela vendedorParcela = vendedorParcelas.FirstOrDefault<VendedorParcela>((VendedorParcela v) => v.Vendedor.Id == vendedor.Id);
										if (vendedorParcela != null)
										{
											porcentagemRepasse = vendedorParcela.PorcentagemRepasse;
										}
										else
										{
											nullable = null;
											porcentagemRepasse = nullable;
										}
										nullable = porcentagemRepasse;
										valueOrDefault = nullable.GetValueOrDefault();
										if (flag5 & buscaAssinaturas)
										{
											statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(num);
											statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => {
												if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3))
												{
													a.Selecionado = true;
												}
											});
											List<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados1;
											statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault<StatusDocumentoAssinado>((StatusDocumentoAssinado a) => a.Selecionado);
										}
										items = await this.BuscaItemsPorIdControle(item1);
									}
									List<Documento> documentos1 = documentos;
									Documento documento = new Documento()
									{
										Id = num
									};
									Documento documento1 = documento;
									Controle controle = new Controle()
									{
										Id = item1,
										IdEmpresa = num1
									};
									Controle controle1 = controle;
									Cliente cliente = new Cliente()
									{
										Id = (long)sqlDataReader["idcliente"],
										Nome = sqlDataReader["nome"].ToString(),
										Documento = sqlDataReader["cgccpf"].ToString(),
										IdEmpresa = num1,
										Pasta = sqlDataReader["pastacliente"].ToString()
									};
									Cliente cliente1 = cliente;
									flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("maladireta"));
									Cliente cliente2 = cliente1;
									flag = (flag4 ? true : (bool)sqlDataReader["maladireta"]);
									cliente2.MalaDireta = new bool?(flag);
									controle1.Cliente = cliente;
									Controle controle2 = controle;
									bool flag7 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idciaseg"));
									Controle controle3 = controle2;
									if (flag7)
									{
										seguradora = null;
									}
									else
									{
										List<Seguradora> seguradoras = Auxiliar.Seguradoras;
										Func<Seguradora, bool> func8 = func1;
										if (func8 == null)
										{
											Func<Seguradora, bool> id3 = (Seguradora seg) => seg.Id == (long)sqlDataReader["idciaseg"];
											Func<Seguradora, bool> func9 = id3;
											func1 = id3;
											func8 = func9;
										}
										seguradora = seguradoras.FirstOrDefault<Seguradora>(func8);
									}
									controle3.Seguradora = seguradora;
									Controle controle4 = controle;
									bool flag8 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idramo"));
									Controle controle5 = controle4;
									if (flag8)
									{
										ramo1 = null;
									}
									else
									{
										List<Ramo> ramos = Auxiliar.Ramos;
										Func<Ramo, bool> func10 = func2;
										if (func10 == null)
										{
											Func<Ramo, bool> id4 = (Ramo ramo) => ramo.Id == (long)sqlDataReader["idramo"];
											Func<Ramo, bool> func11 = id4;
											func2 = id4;
											func10 = func11;
										}
										ramo1 = ramos.FirstOrDefault<Ramo>(func10);
									}
									controle5.Ramo = ramo1;
									Controle controle6 = controle;
									bool flag9 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idproduto"));
									Controle controle7 = controle6;
									if (flag9)
									{
										produto1 = null;
									}
									else
									{
										List<Produto> produtos = Auxiliar.Produtos;
										Func<Produto, bool> func12 = func3;
										if (func12 == null)
										{
											Func<Produto, bool> id5 = (Produto produto) => produto.Id == (long)sqlDataReader["idproduto"];
											Func<Produto, bool> func13 = id5;
											func3 = id5;
											func12 = func13;
										}
										produto1 = produtos.FirstOrDefault<Produto>(func12);
									}
									controle7.Produto = produto1;
									documento1.Controle = controle;
									documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura);
									documento.AdicionalComiss = false;
									documento.Apolice = sqlDataReader["contrato"].ToString();
									Documento documento2 = documento;
									bool flag10 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("apoconferida"));
									Documento documento3 = documento2;
									flag1 = (flag10 ? false : sqlDataReader["apoconferida"].ToString() == "1");
									documento3.ApoliceConferida = flag1;
									documento.Endosso = string.Format("F {0}", sqlDataReader["numfatura"]);
									documento.Comissao = (decimal)sqlDataReader["comissao"];
									Documento documento4 = documento;
									bool flag11 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio"));
									Documento documento5 = documento4;
									negocio = (flag11 ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), sqlDataReader["idnegocio"].ToString()));
									documento5.Negocio = new Negocio?(negocio);
									documento.PremioLiquido = (decimal)sqlDataReader["liquido"];
									documento.PremioTotal = (decimal)sqlDataReader["total"];
									documento.NumeroParcelas = decimal.One;
									Documento documento6 = documento;
									bool flag12 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciaf"));
									Documento documento7 = documento6;
									if (flag12)
									{
										nullable1 = null;
										nullable2 = nullable1;
									}
									else
									{
										nullable2 = new DateTime?((DateTime)sqlDataReader["vigenciaf"]);
									}
									documento7.Vigencia2 = nullable2;
									Documento documento8 = documento;
									bool flag13 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciai"));
									Documento documento9 = documento8;
									dateTime = (flag13 ? DateTime.MinValue : (DateTime)sqlDataReader["vigenciai"]);
									documento9.Vigencia1 = dateTime;
									Documento documento10 = documento;
									bool flag14 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("emissao"));
									Documento documento11 = documento10;
									if (flag14)
									{
										nullable1 = null;
										nullable3 = nullable1;
									}
									else
									{
										nullable3 = new DateTime?((DateTime)sqlDataReader["emissao"]);
									}
									documento11.Emissao = nullable3;
									Documento documento12 = documento;
									bool flag15 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("remessa"));
									Documento documento13 = documento12;
									if (flag15)
									{
										nullable1 = null;
										nullable4 = nullable1;
									}
									else
									{
										nullable4 = new DateTime?((DateTime)sqlDataReader["remessa"]);
									}
									documento13.Remessa = nullable4;
									documento.PercentualRepasse = new decimal?(valueOrDefault);
									Documento documento14 = documento;
									bool flag16 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idestipulante"));
									Documento documento15 = documento14;
									if (flag16)
									{
										estipulante1 = null;
									}
									else
									{
										List<Estipulante> estipulantes = Auxiliar.Estipulantes;
										Func<Estipulante, bool> func14 = func4;
										if (func14 == null)
										{
											Func<Estipulante, bool> id6 = (Estipulante estipulante) => estipulante.Id == (long)sqlDataReader["idestipulante"];
											Func<Estipulante, bool> func15 = id6;
											func4 = id6;
											func14 = func15;
										}
										estipulante1 = estipulantes.FirstOrDefault<Estipulante>(func14);
									}
									documento15.Estipulante1 = estipulante1;
									documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora2);
									documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString());
									documento.Tipo = 2;
									Documento documento16 = documento;
									bool flag17 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("datacontrole"));
									Documento documento17 = documento16;
									if (flag17)
									{
										nullable1 = null;
										nullable5 = nullable1;
									}
									else
									{
										nullable5 = new DateTime?((DateTime)sqlDataReader["datacontrole"]);
									}
									documento17.DataControle = nullable5;
									Documento documento18 = documento;
									bool flag18 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idstatus"));
									Documento documento19 = documento18;
									if (flag18)
									{
										statu = null;
									}
									else
									{
										List<Status> statusApolice = Auxiliar.StatusApolice;
										Func<Status, bool> func16 = func5;
										if (func16 == null)
										{
											Func<Status, bool> id7 = (Status status) => status.Id == (long)sqlDataReader["idstatus"];
											Func<Status, bool> func17 = id7;
											func5 = id7;
											func16 = func17;
										}
										statu = statusApolice.FirstOrDefault<Status>(func16);
									}
									documento19.Status = statu;
									documento.ItensAtivo = items;
									Documento documento20 = documento;
									bool flag19 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("propassinada"));
									Documento documento21 = documento20;
									flag2 = (flag19 ? false : sqlDataReader["propassinada"].ToString() == "1");
									documento21.PropostaAssinada = flag2;
									documento.VendedorPrincipal = vendedor;
									documento.Vendedores = vendedors;
									Documento documento22 = documento;
									if (statusDocumentoAssinados1.Count == 0)
									{
										statusDocumentoAssinados = null;
									}
									else
									{
										statusDocumentoAssinados = statusDocumentoAssinados1;
									}
									documento22.Assinaturas = statusDocumentoAssinados;
									Documento documento23 = documento;
									StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado;
									if (statusDocumentoAssinado1 != null)
									{
										flag3 = statusDocumentoAssinado1.Status == StatusAssinatura.Assinado;
									}
									else
									{
										flag3 = false;
									}
									documento23.AssinadaSiggner = flag3;
									Documento documento24 = documento;
									StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado;
									if (statusDocumentoAssinado2 != null)
									{
										statusAssinatura = statusDocumentoAssinado2.Status;
									}
									else
									{
										statusAssinatura = StatusAssinatura.NaoEnviado;
									}
									documento24.StatusAssinatura = statusAssinatura;
									documento.Pasta = sqlDataReader["pasta"].ToString();
									Documento documento25 = documento;
									bool flag20 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("cri_data"));
									Documento documento26 = documento25;
									if (flag20)
									{
										nullable1 = null;
										nullable6 = nullable1;
									}
									else
									{
										nullable6 = new DateTime?((DateTime)sqlDataReader["cri_data"]);
									}
									documento26.DataCriacao = nullable6;
									Documento documento27 = documento;
									Banco banco = new Banco()
									{
										Nome = sqlDataReader["nomebanco"].ToString()
									};
									documento27.Banco = banco;
									documento.Agencia = sqlDataReader["agencia"].ToString();
									documento.Conta = sqlDataReader["conta"].ToString();
									documentos1.Add(documento);
									documentos1 = null;
									documento1 = null;
									controle1 = null;
									cliente1 = null;
									cliente = null;
									controle2 = null;
									controle4 = null;
									controle6 = null;
									controle = null;
									documento2 = null;
									documento4 = null;
									documento6 = null;
									documento8 = null;
									documento10 = null;
									documento12 = null;
									documento14 = null;
									documento16 = null;
									documento18 = null;
									documento20 = null;
									documento25 = null;
									documento = null;
									vendedors = null;
									items = null;
									statusDocumentoAssinados1 = null;
									statusDocumentoAssinado = null;
								}
							}
						}
					}
					sqlCommand = null;
				}
				sqlConnection = null;
			}
			sessionFactory = null;
			List<Documento> documentos2 = documentos;
			documentos = null;
			sqlQueryCondition = null;
			return documentos2;
		}

		private async Task<List<Item>> BuscaItemsPorIdControle(long idControle)
		{
			object connection;
			List<Item> items = new List<Item>();
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandTimeout = 1000;
						sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)";
						sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle;
						using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
						{
							while (true)
							{
								if (!await sqlDataReader.ReadAsync())
								{
									break;
								}
								List<Item> items1 = items;
								Item item = new Item()
								{
									Id = sqlDataReader.GetFieldValue<long>("iditem", true, true),
									Descricao = sqlDataReader.GetFieldValue<string>("descricao", true, true)
								};
								items1.Add(item);
							}
						}
						sqlDataReader = null;
					}
					sqlCommand = null;
				}
				sqlConnection = null;
			}
			sessionFactory = null;
			List<Item> items2 = items;
			items = null;
			return items2;
		}

		private async Task<List<Item>> BuscaItemsPorIdControle(SqlConnection connection, long idControle)
		{
			List<Item> items = new List<Item>();
			using (SqlCommand sqlCommand = connection.CreateCommand())
			{
				sqlCommand.CommandTimeout = 1000;
				sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)";
				sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle;
				using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
				{
					while (true)
					{
						if (!await sqlDataReader.ReadAsync())
						{
							break;
						}
						List<Item> items1 = items;
						Item item = new Item()
						{
							Id = (long)sqlDataReader["iditem"],
							Descricao = sqlDataReader["descricao"].ToString()
						};
						items1.Add(item);
					}
				}
				sqlDataReader = null;
			}
			sqlCommand = null;
			List<Item> items2 = items;
			items = null;
			return items2;
		}

		public Documento BuscarApolice(long id)
		{
			DocumentoDb documento;
			ParcelaDb parcelaDb = base.All().FirstOrDefault<ParcelaDb>((ParcelaDb x) => x.Id == id);
			if (parcelaDb != null)
			{
				documento = parcelaDb.Documento;
			}
			else
			{
				documento = null;
			}
			return ApplicationMapper.Mapper.Map<DocumentoDb, Documento>(documento);
		}

		public string BuscarLogAntigo(long id, string conn)
		{
			object connection;
			string str = "";
			List<Condicao> condicaos = new List<Condicao>()
			{
				new Condicao()
				{
					Campo = "id",
					Valores = id.CriarValor<long>()
				},
				new Condicao()
				{
					Campo = "idname",
					Valores = "IDParcela".CriarValor<string>()
				}
			};
			this._unitOfWork.CriarAuxiliar();
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			string str1 = "oldbacklog";
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog";
					SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
					sqlDataReader.Read();
					string str2 = sqlDataReader["bdname"].ToString();
					str1 = sqlDataReader["tabela"].ToString();
					sqlDataReader.Close();
					if (sqlConnection.Database != str2)
					{
						conn = conn.Replace(sqlConnection.Database, str2);
					}
				}
			}
			DataTable dataTable = new DataTable();
			using (SqlConnection sqlConnection1 = new SqlConnection(conn))
			{
				sqlConnection1.Open();
				using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand())
				{
					sqlCommand1.CommandTimeout = 15000;
					dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), "");
				}
			}
			if (dataTable == null || dataTable.Rows.Count == 0)
			{
				return "";
			}
			if (dataTable != null)
			{
				dataTable.AsEnumerable().OrderBy<DataRow, long>((DataRow x) => x.Field<long>("idbacklog")).ToList<DataRow>().ForEach((DataRow x) => {
					str = string.Concat(new string[] { str, "<br><FONT face=verdana color=#FF0000 size=2><strong>(", x.Field<object>("data").ToString(), ")</font><FONT face=verdana size=2 color=#000000> ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field<long>("idusuario")).Nome, "</strong></font><br>" });
					str = string.Concat(str, "<FONT face=verdana color=#000000 size=1>", x.Field<object>("historico").ToString().Replace(Environment.NewLine, "<br>"), "</font>");
				});
			}
			return str;
		}

		public ParcelaPendente BuscarPendencia(long id)
		{
			ParcelaPendente parcelaPendente;
			object connection;
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					try
					{
						sqlCommand.CommandText = string.Format("SELECT * FROM parcelapendente WHERE idparcelapendente = {0}", id);
						SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
						if (sqlDataReader.HasRows)
						{
							sqlDataReader.Read();
							parcelaPendente = new ParcelaPendente()
							{
								Id = (long)sqlDataReader["idparcelapendente"],
								IdParcela = (long)sqlDataReader["idparcela"],
								Seguradora = (string)sqlDataReader["seguradora"],
								Cliente = (string)sqlDataReader["cliente"],
								Apolice = (string)sqlDataReader["apolice"],
								Parcela = (int)sqlDataReader["parcela"],
								Valor = decimal.Parse(sqlDataReader["valor"].ToString()),
								Vencimento = DateTime.Parse(sqlDataReader["vencto"].ToString())
							};
						}
						else
						{
							parcelaPendente = null;
						}
					}
					catch (Exception exception)
					{
						parcelaPendente = null;
					}
				}
			}
			return parcelaPendente;
		}

		private async Task<List<StatusDocumentoAssinado>> BuscaStatusAssinadosPorIdDocumento(long idDocumento)
		{
			object connection;
			DateTime? nullable;
			Usuario usuario1;
			Func<Usuario, bool> func = null;
			List<StatusDocumentoAssinado> statusDocumentoAssinados = new List<StatusDocumentoAssinado>();
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandTimeout = 1000;
						sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)";
						sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento;
						using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
						{
							while (true)
							{
								if (!await sqlDataReader.ReadAsync())
								{
									break;
								}
								List<StatusDocumentoAssinado> statusDocumentoAssinados1 = statusDocumentoAssinados;
								StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado()
								{
									Id = (long)sqlDataReader["idnewarquivodigital"],
									Documento = sqlDataReader["descricao"].ToString(),
									Status = (StatusAssinatura)((int)sqlDataReader["status"])
								};
								StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado;
								bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado"));
								StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1;
								if (flag)
								{
									nullable = null;
								}
								else
								{
									nullable = new DateTime?((DateTime)sqlDataReader["enviado"]);
								}
								statusDocumentoAssinado2.Envio = nullable;
								StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado;
								bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid"));
								StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3;
								if (flag1)
								{
									usuario1 = null;
								}
								else
								{
									List<Usuario> usuarios = Auxiliar.Usuarios;
									Func<Usuario, bool> func1 = func;
									if (func1 == null)
									{
										Func<Usuario, bool> id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"];
										Func<Usuario, bool> func2 = id;
										func = id;
										func1 = func2;
									}
									usuario1 = usuarios.FirstOrDefault<Usuario>(func1);
								}
								statusDocumentoAssinado4.Usuario = usuario1;
								statusDocumentoAssinados1.Add(statusDocumentoAssinado);
								statusDocumentoAssinados1 = null;
								statusDocumentoAssinado1 = null;
								statusDocumentoAssinado3 = null;
								statusDocumentoAssinado = null;
							}
						}
					}
					sqlCommand = null;
				}
				sqlConnection = null;
			}
			sessionFactory = null;
			List<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados;
			statusDocumentoAssinados = null;
			return statusDocumentoAssinados2;
		}

		private async Task<List<VendedorParcela>> BuscaVendedoresPorIdParcela(long idParcela, long idEmpresa = 0L, long idSubTipo = 0L)
		{
			object connection;
			string str;
			string str1;
			List<VendedorParcela> vendedorParcelas = new List<VendedorParcela>();
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						str = (idSubTipo > (long)0 ? " INNER JOIN parcela p ON p.idparcela = vp.idparcela " : string.Empty);
						string str2 = str;
						str1 = (idSubTipo > (long)0 ? " AND p.idsubtipo = @subtipo " : string.Empty);
						string str3 = string.Concat("SELECT DISTINCT vp.idvendedor,v.nome nomevendedor,vp.vrep,vp.vlrrep,vp.dataprepagto,vp.datapgt,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN vendedor v ON v.idvendedor = vp.idvendedor ", str2, " WHERE vp.idparcela = @parcela ", str1);
						sqlCommand.CommandTimeout = 1000;
						sqlCommand.CommandText = str3;
						sqlCommand.Parameters.Add("@parcela", SqlDbType.BigInt).Value = idParcela;
						sqlCommand.Parameters.Add("@subtipo", SqlDbType.BigInt).Value = idSubTipo;
						using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
						{
							while (true)
							{
								if (!await sqlDataReader.ReadAsync())
								{
									break;
								}
								List<VendedorParcela> vendedorParcelas1 = vendedorParcelas;
								VendedorParcela vendedorParcela = new VendedorParcela();
								TipoVendedor tipoVendedor = new TipoVendedor()
								{
									Id = sqlDataReader.GetFieldValue<long>("idtipovendedor", true, true)
								};
								vendedorParcela.TipoVendedor = tipoVendedor;
								Vendedor vendedor = new Vendedor()
								{
									Id = sqlDataReader.GetFieldValue<long>("idvendedor", true, true),
									Nome = sqlDataReader.GetFieldValue<string>("nomevendedor", true, true)
								};
								vendedorParcela.Vendedor = vendedor;
								vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue<decimal?>("vrep", true, true);
								vendedorParcela.ValorRepasse = sqlDataReader.GetFieldValue<decimal?>("vlrrep", true, true);
								vendedorParcela.DataPagamento = sqlDataReader.GetFieldValue<DateTime?>("datapgt", true, true);
								vendedorParcela.DataPrePagamento = sqlDataReader.GetFieldValue<DateTime?>("dataprepagto", true, true);
								vendedorParcelas1.Add(vendedorParcela);
							}
							if (idEmpresa > (long)0)
							{
								List<VendedorParcela> vendedorParcelas2 = vendedorParcelas;
								if (!vendedorParcelas2.Any<VendedorParcela>((VendedorParcela v) => v.TipoVendedor.Id == (long)1))
								{
									List<VendedorParcela> vendedorParcelas3 = vendedorParcelas;
									VendedorParcela vendedorParcela1 = new VendedorParcela()
									{
										TipoVendedor = new TipoVendedor()
										{
											Id = (long)1
										},
										Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor v) => {
											if (v.IdEmpresa != idEmpresa)
											{
												return false;
											}
											return v.Corretora;
										}),
										PorcentagemRepasse = new decimal?(new decimal())
									};
									vendedorParcelas3.Add(vendedorParcela1);
								}
							}
						}
						sqlDataReader = null;
					}
					sqlCommand = null;
				}
				sqlConnection = null;
			}
			sessionFactory = null;
			List<VendedorParcela> vendedorParcelas4 = vendedorParcelas;
			List<VendedorParcela> list = (
				from v in vendedorParcelas4
				orderby v.TipoVendedor.Id
				select v).ToList<VendedorParcela>();
			vendedorParcelas = null;
			return list;
		}

		private List<Condicao> CriaCondicaoDocumento(Filtros filtro, string referencia)
		{
			bool count;
			bool flag;
			bool count1;
			bool flag1;
			bool count2;
			bool flag2;
			bool count3;
			bool flag3;
			List<Condicao> condicaos = new List<Condicao>()
			{
				new Condicao()
				{
					Campo = referencia,
					Valores = filtro.Inicio.CriarValor<DateTime>(),
					Operador = Operador.MaiorEIgual
				},
				new Condicao()
				{
					Campo = referencia,
					Valores = filtro.Fim.CriarValor<DateTime>(),
					Operador = Operador.MenorEIgual
				}
			};
			List<long> seguradoras = filtro.Seguradoras;
			if (seguradoras != null)
			{
				count = seguradoras.Count > 0;
			}
			else
			{
				count = false;
			}
			if (count)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idciaseg",
					Valores = filtro.Seguradoras.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> ramos = filtro.Ramos;
			if (ramos != null)
			{
				flag = ramos.Count > 0;
			}
			else
			{
				flag = false;
			}
			if (flag)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idramo",
					Valores = filtro.Ramos.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> status = filtro.Status;
			if (status != null)
			{
				count1 = status.Count > 0;
			}
			else
			{
				count1 = false;
			}
			if (count1)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "d.situacao",
					Valores = filtro.Status.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> tipoVendedor = filtro.TipoVendedor;
			if (tipoVendedor != null)
			{
				flag1 = tipoVendedor.Count > 0;
			}
			else
			{
				flag1 = false;
			}
			if (flag1)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "vp.idtipovendedor",
					Valores = filtro.TipoVendedor.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> vendedores = filtro.Vendedores;
			if (vendedores != null)
			{
				count2 = vendedores.Count > 0;
			}
			else
			{
				count2 = false;
			}
			if (count2)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "vp.idvendedor",
					Valores = filtro.Vendedores.CriarValor<long>(),
					Grupo = 5,
					Operacao = Operacao.Or
				});
			}
			List<long> estipulantes = filtro.Estipulantes;
			if (estipulantes != null)
			{
				flag2 = estipulantes.Count > 0;
			}
			else
			{
				flag2 = false;
			}
			if (flag2)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "d.idestipulante",
					Valores = filtro.Estipulantes.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> produtos = filtro.Produtos;
			if (produtos != null)
			{
				count3 = produtos.Count > 0;
			}
			else
			{
				count3 = false;
			}
			if (count3)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idproduto",
					Valores = filtro.Produtos.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> negocio = filtro.Negocio;
			if (negocio != null)
			{
				flag3 = negocio.Count > 0;
			}
			else
			{
				flag3 = false;
			}
			if (flag3)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "d.NegocioCorretora",
					Valores = filtro.Negocio.CriarValor<long>(),
					Operacao = Operacao.Or,
					Grupo = 6
				});
				condicaos.Add(new Condicao()
				{
					Campo = "d.NegocioCorretora",
					Valores = null,
					Operacao = Operacao.Or,
					Grupo = 6
				});
			}
			if (filtro.IdEmpresa > (long)0)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idempresa",
					Valores = filtro.IdEmpresa.CriarValor<long>(),
					Grupo = 5
				});
			}
			return condicaos;
		}

		private List<Condicao> CriaCondicaoFaturaPendente(Filtros filtro, string referencia)
		{
			return new List<Condicao>()
			{
				new Condicao()
				{
					Campo = referencia,
					Valores = filtro.Inicio.CriarValor<DateTime>(),
					Operador = Operador.MenorEIgual
				},
				new Condicao()
				{
					Campo = referencia,
					Valores = filtro.Fim.CriarValor<DateTime>(),
					Operador = Operador.MaiorEIgual
				}
			};
		}

		private List<Condicao> CriaCondicaoFaturaPendenteVigencia(Filtros filtro, string referencia, string referencia2)
		{
			bool count;
			bool flag;
			bool count1;
			bool flag1;
			bool count2;
			bool flag2;
			bool count3;
			bool flag3;
			List<Condicao> condicaos = new List<Condicao>()
			{
				new Condicao()
				{
					Campo = referencia,
					Valores = filtro.Fim.CriarValor<DateTime>(),
					Operador = Operador.MenorEIgual
				},
				new Condicao()
				{
					Campo = referencia2,
					Valores = filtro.Inicio.CriarValor<DateTime>(),
					Grupo = 1,
					Operador = Operador.MaiorEIgual,
					Operacao = Operacao.Or
				},
				new Condicao()
				{
					Campo = referencia2,
					Valores = null,
					Grupo = 1
				}
			};
			List<long> seguradoras = filtro.Seguradoras;
			if (seguradoras != null)
			{
				count = seguradoras.Count > 0;
			}
			else
			{
				count = false;
			}
			if (count)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idciaseg",
					Valores = filtro.Seguradoras.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> ramos = filtro.Ramos;
			if (ramos != null)
			{
				flag = ramos.Count > 0;
			}
			else
			{
				flag = false;
			}
			if (flag)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idramo",
					Valores = filtro.Ramos.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> status = filtro.Status;
			if (status != null)
			{
				count1 = status.Count > 0;
			}
			else
			{
				count1 = false;
			}
			if (count1)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "d.situacao",
					Valores = filtro.Status.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> tipoVendedor = filtro.TipoVendedor;
			if (tipoVendedor != null)
			{
				flag1 = tipoVendedor.Count > 0;
			}
			else
			{
				flag1 = false;
			}
			if (flag1)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "vp.idtipovendedor",
					Valores = filtro.TipoVendedor.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> vendedores = filtro.Vendedores;
			if (vendedores != null)
			{
				count2 = vendedores.Count > 0;
			}
			else
			{
				count2 = false;
			}
			if (count2)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "vp.idvendedor",
					Valores = filtro.Vendedores.CriarValor<long>(),
					Grupo = 5,
					Operacao = Operacao.Or
				});
			}
			List<long> estipulantes = filtro.Estipulantes;
			if (estipulantes != null)
			{
				flag2 = estipulantes.Count > 0;
			}
			else
			{
				flag2 = false;
			}
			if (flag2)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "d.idestipulante",
					Valores = filtro.Estipulantes.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> produtos = filtro.Produtos;
			if (produtos != null)
			{
				count3 = produtos.Count > 0;
			}
			else
			{
				count3 = false;
			}
			if (count3)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idproduto",
					Valores = filtro.Produtos.CriarValor<long>(),
					Grupo = 5
				});
			}
			List<long> negocio = filtro.Negocio;
			if (negocio != null)
			{
				flag3 = negocio.Count > 0;
			}
			else
			{
				flag3 = false;
			}
			if (flag3)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "d.NegocioCorretora",
					Valores = filtro.Negocio.CriarValor<long>(),
					Operacao = Operacao.Or,
					Grupo = 5
				});
				condicaos.Add(new Condicao()
				{
					Campo = "d.NegocioCorretora",
					Valores = null,
					Operacao = Operacao.Or,
					Grupo = 5
				});
			}
			if (filtro.IdEmpresa > (long)0)
			{
				condicaos.Add(new Condicao()
				{
					Campo = "c.idempresa",
					Valores = filtro.IdEmpresa.CriarValor<long>(),
					Grupo = 5
				});
			}
			return condicaos;
		}

		private List<Condicao> CriarCondicaoFatura(Filtros filtro, string referencia)
		{
			bool count;
			List<Condicao> condicaos = new List<Condicao>()
			{
				new Condicao()
				{
					Campo = "d.Excluido",
					Valores = null,
					Grupo = 1,
					Operacao = Operacao.Or
				},
				new Condicao()
				{
					Campo = "d.Excluido",
					Valores = "0".CriarValor<string>(),
					Grupo = 1,
					Operacao = Operacao.Or
				},
				new Condicao()
				{
					Campo = "d.tiporecebimento",
					Valores = 2.CriarValor<int>()
				}
			};
			Condicao condicao = new Condicao()
			{
				Campo = referencia
			};
			DateTime inicio = filtro.Inicio;
			condicao.Valores = inicio.ToString("yyyy-MM-dd").CriarValor<string>();
			condicao.Operador = Operador.MaiorEIgual;
			condicaos.Add(condicao);
			Condicao condicao1 = new Condicao()
			{
				Campo = referencia
			};
			inicio = filtro.Fim;
			condicao1.Valores = inicio.ToString("yyyy-MM-dd").CriarValor<string>();
			condicao1.Operador = Operador.MenorEIgual;
			condicaos.Add(condicao1);
			condicaos.Add(new Condicao()
			{
				Campo = "p.valorr",
				Valores = 0.CriarValor<int>()
			});
			condicaos.Add(new Condicao()
			{
				Campo = "p.datarec",
				Valores = null
			});
			List<Condicao> condicaos1 = condicaos;
			if (filtro.Status.Count > 0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "situacao",
					Valores = filtro.Status.CriarValor<long>()
				});
			}
			if (filtro.Negocio.Count > 0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "negociocorretora",
					Valores = filtro.Negocio.CriarValor<long>()
				});
			}
			if (filtro.Seguradoras.Count > 0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "c.idciaseg",
					Valores = filtro.Seguradoras.CriarValor<long>()
				});
			}
			if (filtro.Ramos.Count > 0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "c.idramo",
					Valores = filtro.Ramos.CriarValor<long>()
				});
			}
			if (filtro.Produtos.Count > 0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "c.idproduto",
					Valores = filtro.Produtos.CriarValor<long>()
				});
			}
			if (filtro.Vendedores.Count > 0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "vp.idvendedor",
					Valores = filtro.Vendedores.CriarValor<long>(),
					Grupo = 2,
					Operacao = Operacao.Or
				});
				condicaos1.Add(new Condicao()
				{
					Campo = "vp.idvendedor",
					Valores = null,
					Operacao = Operacao.Or,
					Grupo = 2
				});
			}
			if (filtro.Estipulantes.Count > 0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "d.idestipulante",
					Valores = filtro.Estipulantes.CriarValor<long>()
				});
			}
			if (filtro.IdEmpresa > (long)0)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "c.idempresa",
					Valores = filtro.IdEmpresa.CriarValor<long>()
				});
			}
			List<long> tipoVendedor = filtro.TipoVendedor;
			if (tipoVendedor != null)
			{
				count = tipoVendedor.Count > 0;
			}
			else
			{
				count = false;
			}
			if (count)
			{
				condicaos1.Add(new Condicao()
				{
					Campo = "vp.idtipovendedor",
					Valores = filtro.TipoVendedor.CriarValor<long>()
				});
			}
			return condicaos1;
		}

		public void Delete(long id)
		{
			List<VendedorParcelaDb> list = (
				from x in this._unitOfWork.Query<VendedorParcelaDb>()
				where x.Parcela.Id == id
				select x).ToList<VendedorParcelaDb>();
			if (list.Any<VendedorParcelaDb>())
			{
				this._unitOfWork.Repository<VendedorParcelaDb>().DeleteRange(list);
			}
			ParcelaDb parcelaDb = base.FindEntityById(id);
			if (parcelaDb == null)
			{
				return;
			}
			base.Delete(parcelaDb);
		}

		public void DeleteRange(long id)
		{
			List<VendedorParcelaDb> list = (
				from x in this._unitOfWork.Query<VendedorParcelaDb>()
				where x.Parcela.Documento.Id == id
				select x).ToList<VendedorParcelaDb>();
			if (list.Any<VendedorParcelaDb>())
			{
				this._unitOfWork.Repository<VendedorParcelaDb>().DeleteRange(list);
			}
			List<ParcelaDb> parcelaDbs = (
				from i in base.All()
				where i.Documento.Id == id && (int)i.SubTipo == 1
				select i).ToList<ParcelaDb>();
			base.DeleteRange(parcelaDbs);
		}

		public bool ExcluirVinculoParcelaPendenteDocExcluido(Documento doc)
		{
			object connection;
			try
			{
				List<Parcela> parcelas = this.FindByDocumento(doc);
				if (parcelas != null && parcelas.Count > 0)
				{
					SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
					if (sessionFactory != null)
					{
						connection = sessionFactory.ConnectionProvider.GetConnection();
					}
					else
					{
						connection = null;
					}
					using (SqlConnection sqlConnection = connection as SqlConnection)
					{
						parcelas.ForEach((Parcela p) => {
							using (SqlCommand id = sqlConnection.CreateCommand())
							{
								id.CommandText = "UPDATE ParcelaPendente SET IdParcela = NULL WHERE IdParcela = @parcela";
								id.Parameters.Add("@parcela", SqlDbType.BigInt).Value = p.Id;
								id.ExecuteNonQuery();
							}
						});
					}
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		private async Task<bool> ExisteTabelasAssinatura()
		{
			bool flag;
			object connection;
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe";
						flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value;
					}
				}
			}
			return flag;
		}

		public async Task<List<Documento>> FaturaPendente(Filtros filtro)
		{
			List<Documento> documentos;
			NegocioCorretora fieldValue;
			object connection;
			bool count;
			List<Item> itensAtivo;
			DateTime dateTime;
			DateTime dateTime1;
			DateTime dateTime2;
			DateTime dateTime3;
			object produto;
			string str;
			Vendedor vendedor;
			Estipulante estipulante;
			object statu;
			NegocioCorretora negocioCorretora;
			Func<Vendedor, bool> func = null;
			Func<Estipulante, bool> func1 = null;
			string str1 = "f.vigenciai";
			string str2 = "d.vigencia1";
			string str3 = "d.vigencia2";
			if (filtro.Referencia == "VENCIMENTO")
			{
				str1 = "p.vencto";
			}
			List<Condicao> condicaos = this.CriaCondicaoFaturaPendenteVigencia(filtro, str2, str3);
			List<Condicao> condicaos1 = this.CriaCondicaoFaturaPendente(filtro, str1);
			List<Condicao> condicaos2 = new List<Condicao>();
			Condicao condicao = new Condicao()
			{
				Campo = "d.tiporecebimento",
				Valores = 2.CriarValor<int>(),
				Grupo = 2
			};
			condicaos2.Add(condicao);
			List<Condicao> condicaos3 = condicaos2;
			List<Condicao> condicaos4 = new List<Condicao>();
			Condicao condicao1 = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = null,
				Grupo = 4,
				Operacao = Operacao.Or
			};
			condicaos4.Add(condicao1);
			Condicao condicao2 = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = "0".CriarValor<string>(),
				Grupo = 4
			};
			condicaos4.Add(condicao2);
			List<Condicao> condicaos5 = condicaos4;
			List<Condicao> condicaos6 = new List<Condicao>();
			Condicao condicao3 = new Condicao()
			{
				Campo = "d.situacao",
				Valores = 1.CriarValor<int>(),
				Grupo = 3,
				Operacao = Operacao.Or
			};
			condicaos6.Add(condicao3);
			Condicao condicao4 = new Condicao()
			{
				Campo = "d.situacao",
				Valores = 2.CriarValor<int>(),
				Grupo = 3
			};
			condicaos6.Add(condicao4);
			List<Condicao> condicaos7 = condicaos6;
			condicaos.AddRange(condicaos3);
			condicaos.AddRange(condicaos7);
			condicaos.AddRange(condicaos5);
			SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0);
			SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(0);
			List<Documento> documentos1 = new List<Documento>();
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandTimeout = 1000;
						string str4 = "WITH tabfatura AS ( SELECT MAX ( f.vigenciaf ) AS vigenciaf, MAX ( f.vigenciai ) AS vigenciai, MAX ( p.idparcela ) AS idparcela,  MAX ( p.vencto ) AS Vencimento, MAX (f.idfatura) as idfatura, d.iddocumento  FROM documento d LEFT JOIN parcela p ON p.iddocumento = d.iddocumento LEFT JOIN fatura f ON p.idparcela = f.idparcela  GROUP BY d.iddocumento  ) SELECT DISTINCT d.iddocumento, d.idcontrole, IIF ( d.vigencia2 IS NULL, GETDATE(), d.vigencia2 ) AS vigenciafinalfatura, tabfatura.idparcela,tabfatura.vigenciai AS vigenciaIultimafatura, tabfatura.vigenciaf AS vigenciafultimafatura, f.numfatura,tabfatura.Vencimento, cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome AS cliente, d.contrato AS apolice, d.emissao, d.remessa, d.aditamento AS endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 AS vigenciainicial, d.vigencia2 AS vigenciafinal, c.idramo, r.nome AS nomeramo, c.idciaseg AS idseguradora, cs.nome AS nomeseguradora, c.idproduto, pr.nome AS nomeproduto, CAST ( d.tipo AS INTEGER ) AS tipo, vp.idvendedor,  d.idestipulante, d.datacontrole, d.idstatus, st.nome AS nomestatus, d.pasta, cl.pasta AS pastacliente  FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ciaseg cs ON cs.idciaseg = c.idciaseg INNER JOIN ramo r ON r.idramo = c.idramo INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT JOIN produto pr ON pr.idproduto = c.idproduto LEFT JOIN status st ON st.idstatus = d.idstatus LEFT JOIN parcela p ON p.iddocumento = d.iddocumento \tLEFT JOIN vendedorparcela vp ON vp.idparcela = p.idparcela  LEFT JOIN tabfatura ON tabfatura.iddocumento = d.iddocumento  LEFT JOIN fatura f on tabfatura.idfatura = f.idfatura WHERE";
						string str5 = " AND NOT EXISTS ( SELECT 1 FROM parcela p INNER JOIN fatura f ON f.idparcela = p.idparcela WHERE p.iddocumento = d.iddocumento AND  ";
						SqlCommand sqlCommand1 = sqlCommand;
						string[] strArrays = new string[] { str4, " ", sqlQueryCondition.Condicao, "  ", str5, " ", sqlQueryCondition1.Condicao, " ) ORDER BY d.IDDOCUMENTO" };
						sqlCommand1.CommandText = string.Concat(strArrays);
						foreach (SqlParameter parametro in sqlQueryCondition.Parametros)
						{
							if (sqlCommand.Parameters.Contains(parametro.ParameterName))
							{
								continue;
							}
							sqlCommand.Parameters.Add(parametro);
						}
						foreach (SqlParameter sqlParameter in sqlQueryCondition1.Parametros)
						{
							if (sqlCommand.Parameters.Contains(sqlParameter.ParameterName))
							{
								continue;
							}
							sqlCommand.Parameters.Add(sqlParameter);
						}
						using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
						{
							while (true)
							{
								if (!await sqlDataReader.ReadAsync())
								{
									break;
								}
								TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue<TipoSeguro>("situacao", true, true);
								if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "negociocorretora"))
								{
									fieldValue = sqlDataReader.GetFieldValue<NegocioCorretora>("negociocorretora", true, true);
								}
								else
								{
									bool flag = tipoSeguro == TipoSeguro.Renovacao;
									if (flag)
									{
										flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "idnegocio");
									}
									negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue<string>("idnegocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
									fieldValue = negocioCorretora;
								}
								NegocioCorretora negocioCorretora1 = fieldValue;
								List<long> negocio = filtro.Negocio;
								if (negocio != null)
								{
									count = negocio.Count > 0;
								}
								else
								{
									count = false;
								}
								if (!count || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora1))
								{
									long num = sqlDataReader.GetFieldValue<long>("IdControle", true, true);
									long fieldValue1 = sqlDataReader.GetFieldValue<long>("IdEmpresa", true, true);
									Documento documento = documentos1.Find((Documento p) => p.Controle.Id == num);
									if (documento != null)
									{
										itensAtivo = documento.ItensAtivo;
									}
									else
									{
										itensAtivo = null;
									}
									List<Item> items = itensAtivo;
									if (items == null)
									{
										items = await this.BuscaItemsPorIdControle(num);
									}
									List<Item> items1 = items;
									DateTime? nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciafultimafatura", true, true);
									dateTime = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
									DateTime dateTime4 = dateTime;
									nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciaIultimafatura", true, true);
									dateTime1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
									DateTime dateTime5 = dateTime1;
									nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciainicial", true, true);
									dateTime2 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
									DateTime dateTime6 = dateTime2;
									nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciafinalfatura", true, true);
									dateTime3 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
									if (dateTime4 < dateTime3)
									{
										Documento observableCollection = new Documento()
										{
											Id = sqlDataReader.GetFieldValue<long>("iddocumento", true, true)
										};
										Controle controle = new Controle()
										{
											IdEmpresa = fieldValue1
										};
										Cliente cliente = new Cliente()
										{
											Id = sqlDataReader.GetFieldValue<long>("idcliente", true, true),
											Nome = sqlDataReader.GetFieldValue<string>("cliente", true, true),
											IdEmpresa = fieldValue1,
											Pasta = sqlDataReader.GetFieldValue<string>("pastaCliente", true, true)
										};
										bool? nullable1 = sqlDataReader.GetFieldValue<bool?>("MalaDireta", true, true);
										cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true));
										controle.Cliente = cliente;
										Seguradora seguradora = new Seguradora()
										{
											Id = sqlDataReader.GetFieldValue<long>("idseguradora", true, true),
											Nome = sqlDataReader.GetFieldValue<string>("nomeseguradora", true, true)
										};
										controle.Seguradora = seguradora;
										Ramo ramo = new Ramo()
										{
											Id = sqlDataReader.GetFieldValue<long>("idramo", true, true),
											Nome = sqlDataReader.GetFieldValue<string>("nomeramo", true, true)
										};
										controle.Ramo = ramo;
										if (sqlDataReader.FieldIsNull("idproduto"))
										{
											produto = null;
										}
										else
										{
											produto = new Produto();
											((DomainBase)produto).Id = sqlDataReader.GetFieldValue<long>("idproduto", true, true);
											((Produto)produto).Nome = sqlDataReader.GetFieldValue<string>("nomeproduto", true, true);
										}
										controle.Produto = (Produto)produto;
										observableCollection.Controle = controle;
										observableCollection.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura);
										observableCollection.Apolice = sqlDataReader.GetFieldValue<string>("apolice", true, true);
										observableCollection.Pasta = sqlDataReader.GetFieldValue<string>("Pasta", true, true);
										str = (sqlDataReader.GetFieldValue<int>("tipo", true, true) == 0 ? "" : string.Concat("E ", sqlDataReader.GetFieldValue<string>("endosso", true, true)));
										observableCollection.Endosso = str;
										observableCollection.Vigencia2 = sqlDataReader.GetFieldValue<DateTime?>("vigenciafinal", true, true);
										observableCollection.Vigencia1 = dateTime6;
										observableCollection.Emissao = sqlDataReader.GetFieldValue<DateTime?>("emissao", true, true);
										observableCollection.Remessa = sqlDataReader.GetFieldValue<DateTime?>("remessa", true, true);
										if (sqlDataReader.GetFieldValue<object>("idvendedor", true, true) != null)
										{
											List<Vendedor> vendedores = Auxiliar.Vendedores;
											Func<Vendedor, bool> func2 = func;
											if (func2 == null)
											{
												Func<Vendedor, bool> id = (Vendedor p) => p.Id == sqlDataReader.GetFieldValue<long>("idvendedor", true, true);
												Func<Vendedor, bool> func3 = id;
												func = id;
												func2 = func3;
											}
											vendedor = vendedores.FirstOrDefault<Vendedor>(func2);
										}
										else
										{
											vendedor = null;
										}
										observableCollection.VendedorPrincipal = vendedor;
										if (sqlDataReader.GetFieldValue<object>("idestipulante", true, true) != null)
										{
											List<Estipulante> estipulantes = Auxiliar.Estipulantes;
											Func<Estipulante, bool> func4 = func1;
											if (func4 == null)
											{
												Func<Estipulante, bool> id1 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
												Func<Estipulante, bool> func5 = id1;
												func1 = id1;
												func4 = func5;
											}
											estipulante = estipulantes.FirstOrDefault<Estipulante>(func4);
										}
										else
										{
											estipulante = null;
										}
										observableCollection.Estipulante1 = estipulante;
										observableCollection.NegocioCorretora = new NegocioCorretora?(negocioCorretora1);
										observableCollection.Situacao = tipoSeguro;
										List<Parcela> parcelas = new List<Parcela>();
										Parcela parcela = new Parcela()
										{
											Id = sqlDataReader.GetFieldValue<long>("idparcela", true, true),
											VigenciaFinal = new DateTime?(dateTime4),
											Fatura = sqlDataReader.GetFieldValue<string>("numfatura", true, true),
											Vencimento = sqlDataReader.GetFieldValue<DateTime>("Vencimento", true, true),
											VigenciaIncial = new DateTime?(dateTime5)
										};
										parcelas.Add(parcela);
										observableCollection.Parcelas = new ObservableCollection<Parcela>(parcelas);
										observableCollection.Tipo = sqlDataReader.GetFieldValue<int>("tipo", true, true);
										observableCollection.DataControle = sqlDataReader.GetFieldValue<DateTime?>("datacontrole", true, true);
										if (sqlDataReader.FieldIsNull("idstatus"))
										{
											statu = null;
										}
										else
										{
											statu = new Status();
											((DomainBase)statu).Id = sqlDataReader.GetFieldValue<long>("idstatus", true, true);
											((Status)statu).Nome = sqlDataReader.GetFieldValue<string>("nomestatus", true, true);
										}
										observableCollection.Status = (Status)statu;
										observableCollection.ItensAtivo = items1;
										documentos1.Add(observableCollection);
									}
								}
							}
						}
					}
					sqlCommand = null;
				}
				sqlConnection = null;
				documentos = documentos1;
			}
			documentos1 = null;
			return documentos;
		}

		public List<Parcela> FindByDocumentId(List<long> ids)
		{
			List<Parcela> parcelas;
			object connection;
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					string str = string.Concat(" p.iddocumento IN (", string.Join<long>(",", ids), ")");
					sqlCommand.CommandText = string.Concat("SELECT p.iddocumento, ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss,p.obs, p.vlrcomiss, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, f.* FROM parcela p OUTER APPLY (SELECT numfatura, vigenciai, vigenciaf, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE ", str);
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						goto Label0;
					}
					else
					{
						parcelas = new List<Parcela>();
					}
				}
			}
			return parcelas;
		Label0:
			List<DataRow> list = dataTable.AsEnumerable().ToList<DataRow>();
			return list.Select<DataRow, Parcela>((DataRow x) => {
				Parcela parcela = new Parcela()
				{
					Id = x.Field<long>("idparcela"),
					IdEmpresa = x.Field<long>("idempresa"),
					Documento = new Documento()
					{
						Id = x.Field<long>("iddocumento")
					},
					NumeroParcela = int.Parse(x.Field<object>("parcela").ToString())
				};
				DateTime? nullable = x.Field<DateTime?>("vencto");
				parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Today);
				parcela.DataRecebimento = x.Field<DateTime?>("datarec");
				parcela.DataQuitacao = x.Field<DateTime?>("dataquit");
				parcela.DataControle = x.Field<DateTime?>("datacontrole");
				parcela.DataCredito = x.Field<DateTime?>("datacred");
				decimal? nullable1 = x.Field<decimal?>("valor");
				parcela.Valor = nullable1.GetValueOrDefault();
				nullable1 = x.Field<decimal?>("valorr");
				parcela.ValorRealizado = nullable1.GetValueOrDefault();
				nullable1 = x.Field<decimal?>("comiss");
				parcela.Comissao = nullable1.GetValueOrDefault();
				nullable1 = x.Field<decimal?>("vlrcomiss");
				parcela.ValorComissao = nullable1.GetValueOrDefault();
				nullable1 = x.Field<decimal?>("vlrcomdesc");
				parcela.ValorComDesconto = nullable1.GetValueOrDefault();
				parcela.Observacao = x.Field<string>("obs");
				parcela.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field<object>("idsubtipo").ToString());
				parcela.TipoPagamento = (x.Field<object>("idtipopagto") == null ? TipoPagamento.Nenhum : (TipoPagamento)Enum.Parse(typeof(TipoPagamento), x.Field<object>("idtipopagto").ToString()));
				nullable1 = x.Field<decimal?>("valorlf");
				parcela.ValorLiquidoFatura = nullable1.GetValueOrDefault();
				parcela.Fatura = x.Field<string>("numfatura");
				parcela.VigenciaIncial = x.Field<DateTime?>("vigenciai");
				parcela.VigenciaFinal = x.Field<DateTime?>("vigenciaf");
				parcela.Emissao = x.Field<DateTime?>("emissao");
				parcela.Extrato = x.Field<string>("extrato");
				parcela.StatusPagamento = new StatusPagamento?((x.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field<object>("StatusPagamento").ToString())));
				parcela.IdParcelaPendente = x.Field<long?>("IdParcelaPendente").GetValueOrDefault();
				nullable1 = x.Field<decimal?>("irr");
				parcela.Irr = nullable1.GetValueOrDefault();
				nullable1 = x.Field<decimal?>("iss");
				parcela.Iss = nullable1.GetValueOrDefault();
				nullable1 = x.Field<decimal?>("desconto");
				parcela.Desconto = nullable1.GetValueOrDefault();
				nullable1 = x.Field<decimal?>("outros");
				parcela.Outros = nullable1.GetValueOrDefault();
				return parcela;
			}).ToList<Parcela>();
		}

		public List<Parcela> FindByDocumentId(long id)
		{
			List<Parcela> parcelas;
			object connection;
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					sqlCommand.CommandText = string.Concat("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", id));
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						Documento documento = (new DocumentoRepository(this._unitOfWork)).FindById(id, false, false);
						return dataTable.MapParcela(documento);
					}
					else
					{
						parcelas = new List<Parcela>();
					}
				}
			}
			return parcelas;
		}

		public List<Documento> FindByDocumentIds(string ids, List<Documento> documentos)
		{
			object connection;
			DataTable dataTable = new DataTable();
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					sqlCommand.CommandText = string.Concat("SELECT iddocumento, idempresa, idparcela, parcela, vencto, valor, idtipopagto, StatusPagamento, IdParcelaPendente FROM parcela WHERE iddocumento IN (", ids, ");");
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
				}
			}
			documentos.ForEach((Documento x) => {
				List<Parcela> parcelas = new List<Parcela>();
				dataTable.AsEnumerable().Where<DataRow>((DataRow y) => y.Field<long>("iddocumento") == x.Id).ToList<DataRow>().ForEach((DataRow y) => {
					Parcela parcela = new Parcela()
					{
						Id = y.Field<long>("idparcela"),
						IdEmpresa = (!y.Field<long?>("idempresa").HasValue ? (long)0 : y.Field<long>("idempresa")),
						NumeroParcela = int.Parse(y.Field<object>("parcela").ToString()),
						Vencimento = (y.Field<object>("vencto") == null ? new DateTime() : y.Field<DateTime>("vencto")),
						Valor = y.Field<decimal>("valor"),
						TipoPagamento = (y.Field<object>("idtipopagto") == null ? TipoPagamento.Nenhum : (int)y.Field<long>("idtipopagto")),
						StatusPagamento = new StatusPagamento?((y.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), y.Field<object>("StatusPagamento").ToString()))),
						IdParcelaPendente = y.Field<long?>("IdParcelaPendente").GetValueOrDefault()
					};
					parcelas.Add(parcela);
				});
				x.Parcelas = new ObservableCollection<Parcela>(parcelas);
			});
			return documentos;
		}

		public List<Parcela> FindByDocumento(Documento documento)
		{
			List<Parcela> parcelas;
			object connection;
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					sqlCommand.CommandText = string.Concat("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", documento.Id));
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						return dataTable.MapParcela(documento);
					}
					else
					{
						parcelas = new List<Parcela>();
					}
				}
			}
			return parcelas;
		}

		public Parcela FindById(long id)
		{
			DateTime? nullable;
			string fatura;
			DateTime? vigenciaInicial;
			DateTime? vigenciaFinal;
			DateTime? emissao;
			ParcelaDb parcelaDb = base.FindEntityById(id);
			if (parcelaDb == null)
			{
				return null;
			}
			if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela || !string.IsNullOrEmpty(parcelaDb.Fatura))
			{
				return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
			}
			FaturaDb faturaDb = this._unitOfWork.Query<FaturaDb>().FirstOrDefault<FaturaDb>((FaturaDb x) => x.Parcela.Id == id);
			ParcelaDb parcelaDb1 = parcelaDb;
			if (faturaDb != null)
			{
				fatura = faturaDb.Fatura;
			}
			else
			{
				fatura = null;
			}
			parcelaDb1.Fatura = fatura;
			ParcelaDb parcelaDb2 = parcelaDb;
			if (faturaDb != null)
			{
				vigenciaInicial = faturaDb.VigenciaInicial;
			}
			else
			{
				nullable = null;
				vigenciaInicial = nullable;
			}
			parcelaDb2.VigenciaIncial = vigenciaInicial;
			ParcelaDb parcelaDb3 = parcelaDb;
			if (faturaDb != null)
			{
				vigenciaFinal = faturaDb.VigenciaFinal;
			}
			else
			{
				nullable = null;
				vigenciaFinal = nullable;
			}
			parcelaDb3.VigenciaFinal = vigenciaFinal;
			ParcelaDb parcelaDb4 = parcelaDb;
			if (faturaDb != null)
			{
				emissao = faturaDb.Emissao;
			}
			else
			{
				nullable = null;
				emissao = nullable;
			}
			parcelaDb4.Emissao = emissao;
			return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
		}

		public List<VendedorParcela> FindByPagamento(Filtros filtro, bool reciboPagamento, bool segundaViaReciboPagamento, bool datacontrole)
		{
			List<VendedorParcela> vendedorParcelas;
			string str;
			object connection;
			string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",", 
				from v in filtro.Status
				select v), ")"));
			string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND (NegocioCorretora IN (", string.Join<long>(",", 
				from v in filtro.Negocio
				select v), ") OR NegocioCorretora IS NULL)"));
			string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",", 
				from v in filtro.Seguradoras
				select v), ")"));
			string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",", 
				from v in filtro.Ramos
				select v), ")"));
			string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",", 
				from v in filtro.Produtos
				select v), ")"));
			string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",", 
				from v in filtro.Vendedores
				select v), ")"));
			string str7 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "" : string.Concat(" AND vp.idtipovendedor IN (", string.Join<long>(",", 
				from v in filtro.TipoVendedor
				select v), ")"));
			string str8 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",", 
				from v in filtro.Estipulantes
				select v), ")"));
			string str9 = (!reciboPagamento || segundaViaReciboPagamento ? "" : "AND vp.datapgt IS NULL ");
			if (segundaViaReciboPagamento)
			{
				str = "CAST(vp.datapgt AS DATE)";
			}
			else
			{
				str = (datacontrole ? "CAST(d.datacontrole AS DATE)" : "CAST(vp.dataprepagto AS DATE)");
			}
			string str10 = str;
			string str11 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
			string str12 = (filtro.ParcelasEspeciais.Any<FiltroTipoParcela>((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND p.idsubtipo IN (", string.Join<int>(",", 
				from x in filtro.ParcelasEspeciais
				where x.Selecionado
				select x into v
				select (int)v.Tipo), ")") : "");
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					sqlCommand.CommandTimeout = 15000;
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					string str13 = "SELECT DISTINCT cl.idempresa, vp.idvendedorparcela, cl.idcliente, cl.MalaDireta, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, p.idparcela, d.iddocumento, d.N_PARC as numeroparcelas, d.datacontrole, cl.nome as cliente, d.contrato as apolice, d.aditamento as endosso, d.situacao, d.idnegocio, d.vigencia1 as vigenciainicial, d.proposta, d.vigencia2 as vigenciafinal, f.vigenciaf as vigenciaf, ISNULL(d.com01, 0) as comissao, ISNULL(p.comiss, 0.00) as comiss, p.parcela, d.tiporecebimento, ISNULL(d.pr_liq, 0.00) as liquido, ISNULL(d.pr_total, 0.00) as total, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as liquidofatura, f.vigenciai, f.numfatura as fatura, vp.dataprepagto as recebimento, ISNULL(vp.vlrrep,0) as repasse, ISNULL(vp.vrep, 0) as percentual, p.idsubtipo, vp.datapgt, vp.idrepasse as idrepasse, rep.tipo as tiporepasse, d.cri_data, d.emissao, p.datarec, p.vlrcomdesc, d.NegocioCorretora, CASE WHEN ((Round(ISNULL( d.pr_liq, 0.00 ) * (ISNULL( d.com01, 0 ) / 100 ),2) * ( vp.vrep/ 100 )) -  ROUND(vp.valortotal,2) - ROUND(cia.tolerancia,2)) > 0 THEN  'SIM' ELSE 'NÃO'END AS RecebidoPorCompleto  FROM vendedorparcela  vp INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela INNER JOIN repasse rep on rep.idrepasse = vp.idrepasse INNER JOIN ciaseg cia on cia.idciaseg = c.idciaseg WHERE (d.excluido IS NULL OR d.excluido = 0)";
					sqlCommand.CommandText = string.Format("{0} {1} AND vp.idvendedor != {2} AND {3} >= '{4:yyyy-MM-dd}' AND {5} <= '{6:yyyy-MM-dd}' {7} {8} {9} {10} {11} {12} {13} {14} {15}{16}", new object[] { str13, str11, Auxiliar.Vendedores.First<Vendedor>((Vendedor x) => x.Corretora).Id, str10, filtro.Inicio, str10, filtro.Fim, str9, str1, str2, str3, str4, str5, str8, str6, str7, str12 });
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						Action<DataRow> action = (DataRow x) => x.SetField<object>("NegocioCorretora", (!(x.Field<object>("situacao").ToString() == "2") || x.Field<object>("idnegocio") == null || !(x.Field<object>("idnegocio").ToString() == "1") ? "0" : "1"));
						(
							from x in dataTable.AsEnumerable().ToList<DataRow>()
							where x.Field<object>("NegocioCorretora") == null
							select x).ForEach<DataRow>(action);
						if (!str2.IsNullOrEmpty())
						{
							Func<DataRow, bool> func = (DataRow p) => filtro.Negocio.Any<long>((long filter) => filter.ToString() == p.Field<object>("NegocioCorretora").ToString());
							dataTable = dataTable.AsEnumerable().Where<DataRow>(func).CopyToDataTable<DataRow>();
						}
						goto Label0;
					}
					else
					{
						vendedorParcelas = new List<VendedorParcela>();
					}
				}
			}
			return vendedorParcelas;
		Label0:
			List<DataRow> list = dataTable.AsEnumerable().ToList<DataRow>();
			return list.Select<DataRow, VendedorParcela>((DataRow x) => {
				decimal? nullable;
				decimal valueOrDefault;
				decimal num;
				VendedorParcela vendedorParcela = new VendedorParcela()
				{
					Id = x.Field<long>("idvendedorparcela"),
					Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")),
					Repasse = new Repasse()
					{
						Id = x.Field<long>("idrepasse"),
						Tipo = new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field<object>("tiporepasse").ToString()))
					}
				};
				Documento documento = new Documento()
				{
					Id = x.Field<long>("iddocumento"),
					Controle = new Controle()
					{
						IdEmpresa = x.Field<long>("idempresa"),
						Cliente = new Cliente()
						{
							Id = x.Field<long>("idcliente"),
							Nome = x.Field<string>("cliente"),
							IdEmpresa = x.Field<long>("idempresa"),
							MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
						},
						Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
						Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
						Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null)
					},
					Apolice = x.Field<string>("apolice"),
					Endosso = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<string>("endosso") : string.Concat("F ", x.Field<string>("fatura"))),
					Comissao = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<decimal>("comissao") : x.Field<decimal>("comiss"))
				};
				if (x.Field<object>("tiporecebimento").ToString() == "1")
				{
					nullable = x.Field<decimal?>("liquido");
					valueOrDefault = nullable.GetValueOrDefault();
				}
				else
				{
					nullable = x.Field<decimal?>("liquidofatura");
					valueOrDefault = nullable.GetValueOrDefault();
				}
				documento.PremioLiquido = valueOrDefault;
				if (x.Field<object>("tiporecebimento").ToString() == "1")
				{
					nullable = x.Field<decimal?>("total");
					num = nullable.GetValueOrDefault();
				}
				else
				{
					nullable = x.Field<decimal?>("valor");
					num = nullable.GetValueOrDefault();
				}
				documento.PremioTotal = num;
				documento.Vigencia1 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime>("vigenciainicial") : (x.Field<object>("vigenciai") != null ? x.Field<DateTime>("vigenciai") : new DateTime()));
				documento.Vigencia2 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime?>("vigenciafinal") : x.Field<DateTime?>("vigenciaf"));
				documento.Proposta = x.Field<string>("proposta");
				documento.NegocioCorretora = new NegocioCorretora?((NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("NegocioCorretora").ToString()));
				documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
				documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
				documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString()));
				documento.NumeroParcelas = x.Field<int>("numeroparcelas");
				documento.DataCriacao = x.Field<DateTime?>("cri_data");
				documento.DataControle = x.Field<DateTime?>("datacontrole");
				documento.Emissao = x.Field<DateTime?>("emissao");
				vendedorParcela.Documento = documento;
				Parcela parcela = new Parcela()
				{
					NumeroParcela = int.Parse(x.Field<object>("parcela").ToString()),
					Id = x.Field<long>("idparcela"),
					SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field<object>("idsubtipo").ToString()),
					IdEmpresa = x.Field<long>("idempresa"),
					Valor = x.Field<decimal>("valor")
				};
				nullable = x.Field<decimal?>("vlrcomdesc");
				parcela.ValorComDesconto = nullable.GetValueOrDefault();
				parcela.DataRecebimento = x.Field<DateTime?>("datarec");
				vendedorParcela.Parcela = parcela;
				vendedorParcela.ValorRepasse = new decimal?(x.Field<decimal>("repasse"));
				DateTime? nullable1 = x.Field<DateTime?>("recebimento");
				vendedorParcela.DataPrePagamento = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue));
				vendedorParcela.PorcentagemRepasse = new decimal?(x.Field<decimal>("percentual"));
				vendedorParcela.DataPagamento = x.Field<DateTime?>("datapgt");
				vendedorParcela.RecebidoPorCompleto = x.Field<string>("RecebidoPorCompleto");
				return vendedorParcela;
			}).ToList<VendedorParcela>();
		}

		public List<Parcela> FindByPendente(Filtros filtro, bool pendente, bool somenteAtivos)
		{
			List<Parcela> parcelas;
			object connection;
			List<long> nums = null;
			string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",", 
				from v in filtro.Status
				select v), ")"));
			string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",", 
				from v in filtro.Negocio
				select v), ")"));
			string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",", 
				from v in filtro.Seguradoras
				select v), ")"));
			string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",", 
				from v in filtro.Ramos
				select v), ")"));
			string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",", 
				from v in filtro.Produtos
				select v), ")"));
			string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",", 
				from v in filtro.Vendedores
				select v), ")"));
			string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp2.idvendedor FROM vendedorparcela vp2 WHERE (d.tiporecebimento = 2  AND vp2.IDPARCELA = p.IDPARCELA) OR (d.tiporecebimento = 1  AND vp2.iddocumento = p.iddocumento)) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join<long>(",", 
				from v in filtro.TipoVendedor
				select v), ")"));
			string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",", 
				from v in filtro.Estipulantes
				select v), ")"));
			string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
			string str9 = (somenteAtivos ? " AND i.idsubstituido IS NULL" : "");
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			DataTable dataTable1 = new DataTable();
			DataTable dataTable2 = new DataTable();
			DataTable dataTable3 = new DataTable();
			DataTable dataTable4 = new DataTable();
			string str10 = (pendente ? "AND p.datarec IS NULL" : "");
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					sqlCommand.CommandTimeout = 15000;
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					string str11 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.dataquit as quitacao, p.datacontrole as dataparcelacontrole, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0) as valorcomissao, p.iddocumento, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.proposta, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorr, 0.00) as valorr, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01,0) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.N_PARC as numeroparcelas, d.datacontrole, d.idstatus, p.idsubtipo, cl.cgccpf, d.formapagamento, d.propassinada, d.pasta, cl.pasta as pastacliente FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", (somenteAtivos ? "INNER JOIN item i on d.iddocumento = i.iddocumento " : ""), str6, " LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)");
					string str12 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 ";
					string str13 = "SELECT iddocumento, idparcela as id, parcela, datarec as recebimento, vencto as vencimento, vlrcomdesc as valorcomdesconto, ISNULL(vlrcomiss, 0.00) as valorcomissao, ISNULL(valor, 0.00) as valor,  ISNULL(comiss, 0.00) as comiss, ISNULL(StatusPagamento, 0) AS StatusPagamento, ISNULL(IdParcelaPendente, 0) AS IdParcelaPendente FROM parcela where datarec IS NOT NULL ";
					string str14 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL ";
					string str15 = "SELECT DISTINCT idcliente, idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE ";
					sqlCommand.CommandText = string.Format("{0} {1} {2} AND p.vencto >= '{3:yyyy-MM-dd}' AND p.vencto <= '{4:yyyy-MM-dd}' {5} {6} {7} {8} {9} {10} {11} {12}", new object[] { str11, str8, str10, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5, str9 });
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						string str16 = string.Concat(" AND vp.idparcela IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
						sqlCommand.CommandText = string.Concat(str12, " ", str16);
						using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
						{
							sqlDataAdapter1.SelectCommand = sqlCommand;
							sqlDataAdapter1.Fill(dataTable1);
						}
						string str17 = string.Concat(" AND iddocumento IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("iddocumento"))), ")");
						sqlCommand.CommandText = string.Concat(str13, " ", str17);
						using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
						{
							sqlDataAdapter2.SelectCommand = sqlCommand;
							sqlDataAdapter2.Fill(dataTable2);
						}
						string str18 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")");
						sqlCommand.CommandText = string.Concat(str14, " ", str18);
						using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter())
						{
							sqlDataAdapter3.SelectCommand = sqlCommand;
							sqlDataAdapter3.Fill(dataTable3);
						}
						for (List<long> i1 = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idcliente")).Distinct<long>().ToList<long>(); i1.Count > 0; i1 = nums)
						{
							List<long> nums1 = i1.Take<long>(1000).ToList<long>();
							List<Condicao> condicaos = new List<Condicao>()
							{
								new Condicao()
								{
									Campo = "idcliente",
									Valores = nums1.CriarValor<long>()
								}
							};
							DataTable dataTable5 = sqlCommand.Select(condicaos.CreateParameters(0), str15, "");
							dataTable4.Merge(dataTable5);
							nums = (nums1.Count < 1000 ? new List<long>() : i1.Except<long>(nums1).ToList<long>());
						}
						goto Label0;
					}
					else
					{
						parcelas = new List<Parcela>();
					}
				}
			}
			return parcelas;
		Label0:
			return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Parcela>((DataRow x) => {
				decimal? nullable3;
				decimal valueOrDefault;
				decimal num;
				Parcela observableCollection = new Parcela()
				{
					Id = x.Field<long>("id"),
					IdEmpresa = x.Field<long>("idempresa"),
					NumeroParcela = int.Parse(x.Field<object>("parcela").ToString())
				};
				DateTime? nullable4 = x.Field<DateTime?>("vencimento");
				observableCollection.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue);
				observableCollection.Comissao = x.Field<decimal>("comiss");
				observableCollection.DataQuitacao = x.Field<DateTime?>("quitacao");
				observableCollection.DataControle = x.Field<DateTime?>("dataparcelacontrole");
				observableCollection.Valor = x.Field<decimal>("valor");
				observableCollection.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field<object>("idsubtipo").ToString());
				observableCollection.StatusPagamento = new StatusPagamento?((x.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field<object>("StatusPagamento").ToString())));
				observableCollection.IdParcelaPendente = x.Field<long?>("IdParcelaPendente").GetValueOrDefault();
				IEnumerable<DataRow> list = 
					from v in dataTable1.AsEnumerable().ToList<DataRow>()
					where v.Field<long>("id") == x.Field<long>("id")
					select v;
				Func<DataRow, VendedorParcela> u003cu003e9_2614 = ParcelaRepository.u003cu003ec.u003cu003e9__26_14;
				if (u003cu003e9_2614 == null)
				{
					u003cu003e9_2614 = (DataRow v) => {
						DateTime? nullable;
						DateTime? nullable1;
						DateTime? nullable2;
						VendedorParcela vendedorParcela = new VendedorParcela()
						{
							Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == v.Field<long>("idvendedor")),
							ValorRepasse = new decimal?((v.Field<object>("valorrepasse") == null ? decimal.Zero : v.Field<decimal>("valorrepasse"))),
							PorcentagemRepasse = new decimal?((v.Field<object>("porcentagemrepasse") == null ? decimal.Zero : v.Field<decimal>("porcentagemrepasse")))
						};
						if (v.Field<object>("datapagamento") == null)
						{
							nullable = null;
							nullable1 = nullable;
						}
						else
						{
							nullable1 = v.Field<DateTime?>("datapagamento");
						}
						vendedorParcela.DataPagamento = nullable1;
						if (v.Field<object>("dataprepagamento") == null)
						{
							nullable = null;
							nullable2 = nullable;
						}
						else
						{
							nullable2 = v.Field<DateTime?>("dataprepagamento");
						}
						vendedorParcela.DataPrePagamento = nullable2;
						return vendedorParcela;
					};
					ParcelaRepository.u003cu003ec.u003cu003e9__26_14 = u003cu003e9_2614;
				}
				observableCollection.Vendedores = new ObservableCollection<VendedorParcela>(list.Select<DataRow, VendedorParcela>(u003cu003e9_2614).ToList<VendedorParcela>());
				Documento documento = new Documento()
				{
					Id = x.Field<long>("iddocumento"),
					FormaPagamento = new FormaPagamento?((x.Field<object>("formapagamento") == null || !(x.Field<object>("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field<object>("formapagamento").ToString())))
				};
				Controle controle = new Controle()
				{
					Id = x.Field<long>("idcontrole"),
					IdEmpresa = x.Field<long>("idempresa")
				};
				Cliente cliente = new Cliente()
				{
					Id = x.Field<long>("idcliente"),
					Nome = x.Field<string>("cliente"),
					Documento = x.Field<string>("cgccpf"),
					IdEmpresa = x.Field<long>("idempresa"),
					Pasta = x.Field<string>("pastacliente")
				};
				EnumerableRowCollection<DataRow> dataRows = dataTable4.AsEnumerable().Where<DataRow>((DataRow t) => t.Field<long>("idcliente") == x.Field<long>("idcliente"));
				Func<DataRow, ClienteTelefone> u003cu003e9_2627 = ParcelaRepository.u003cu003ec.u003cu003e9__26_27;
				if (u003cu003e9_2627 == null)
				{
					u003cu003e9_2627 = (DataRow t) => new ClienteTelefone()
					{
						Id = t.Field<long>("idclitelefone"),
						Prefixo = t.Field<string>("ddd"),
						Numero = t.Field<string>("fone")
					};
					ParcelaRepository.u003cu003ec.u003cu003e9__26_27 = u003cu003e9_2627;
				}
				cliente.Telefones = new ObservableCollection<ClienteTelefone>(dataRows.Select<DataRow, ClienteTelefone>(u003cu003e9_2627));
				cliente.MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true));
				controle.Cliente = cliente;
				controle.Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null);
				controle.Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null);
				controle.Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null);
				documento.Controle = controle;
				documento.Pasta = x.Field<string>("Pasta");
				documento.NumeroParcelas = x.Field<int>("numeroparcelas");
				documento.AdicionalComiss = x.Field<string>("adinacomiss") == "1";
				documento.Apolice = x.Field<string>("apolice");
				documento.Endosso = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<string>("endosso") : string.Concat("F ", x.Field<string>("fatura")));
				documento.Comissao = x.Field<decimal>("comiss");
				documento.Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())));
				if (x.Field<object>("tiporecebimento").ToString() == "1")
				{
					nullable3 = x.Field<decimal?>("liquido");
					valueOrDefault = nullable3.GetValueOrDefault();
				}
				else
				{
					nullable3 = x.Field<decimal?>("valorliquidofatura");
					valueOrDefault = nullable3.GetValueOrDefault();
				}
				documento.PremioLiquido = valueOrDefault;
				if (x.Field<object>("tiporecebimento").ToString() == "1")
				{
					nullable3 = x.Field<decimal?>("total");
					num = nullable3.GetValueOrDefault();
				}
				else
				{
					nullable3 = x.Field<decimal?>("valor");
					num = nullable3.GetValueOrDefault();
				}
				documento.PremioTotal = num;
				nullable3 = x.Field<decimal?>("adicional");
				documento.PremioAdicional = nullable3.GetValueOrDefault();
				documento.Vigencia1 = (x.Field<object>("tiporecebimento").ToString() == "1" ? (x.Field<object>("vigenciainicial") == null ? DateTime.MinValue : x.Field<DateTime>("vigenciainicial")) : (x.Field<object>("vigenciai") != null ? x.Field<DateTime>("vigenciai") : (x.Field<object>("vigenciainicial") == null ? DateTime.MinValue : x.Field<DateTime>("vigenciainicial"))));
				documento.Vigencia2 = (x.Field<object>("tiporecebimento").ToString() == "1" ? (x.Field<object>("vigenciafinal") == null ? new DateTime?(DateTime.MinValue) : x.Field<DateTime?>("vigenciafinal")) : new DateTime?((x.Field<object>("vigenciaf") != null ? x.Field<DateTime>("vigenciaf") : (x.Field<object>("vigenciafinal") == null ? DateTime.MinValue : x.Field<DateTime>("vigenciafinal")))));
				documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
				documento.Proposta = x.Field<string>("proposta");
				documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
				documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
				documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString()));
				documento.PropostaAssinada = (x.Field<object>("propassinada") == null ? false : x.Field<string>("propassinada") == "1");
				documento.Parcelas = new ObservableCollection<Parcela>(dataTable2.AsEnumerable().Where<DataRow>((DataRow p) => p.Field<long>("iddocumento") == x.Field<long>("iddocumento")).Select<DataRow, Parcela>((DataRow p) => {
					Parcela parcela = new Parcela()
					{
						Id = p.Field<long>("id"),
						NumeroParcela = int.Parse(p.Field<object>("parcela").ToString()),
						DataRecebimento = p.Field<DateTime?>("recebimento")
					};
					DateTime? nullable = p.Field<DateTime?>("vencimento");
					parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
					parcela.ValorComissao = (x.Field<object>("valorcomissao") == null ? decimal.Zero : p.Field<decimal>("valorcomissao"));
					parcela.ValorComDesconto = (p.Field<object>("valorcomdesconto") == null || p.Field<decimal>("valorcomdesconto") == decimal.Zero ? (x.Field<object>("valorcomissao") == null ? decimal.Zero : p.Field<decimal>("valorcomissao")) : p.Field<decimal>("valorcomdesconto"));
					parcela.Comissao = p.Field<decimal>("comiss");
					parcela.Valor = p.Field<decimal>("valor");
					parcela.StatusPagamento = new StatusPagamento?((p.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), p.Field<object>("StatusPagamento").ToString())));
					parcela.IdParcelaPendente = p.Field<long?>("IdParcelaPendente").GetValueOrDefault();
					return parcela;
				}).ToList<Parcela>());
				documento.Tipo = x.Field<int>("tipo");
				documento.DataControle = x.Field<DateTime?>("datacontrole");
				documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status p) => p.Id == x.Field<long>("idstatus")) : null);
				IEnumerable<DataRow> list1 = 
					from i in dataTable3.AsEnumerable().ToList<DataRow>()
					where i.Field<long>("idcontrole") == x.Field<long>("idcontrole")
					select i;
				Func<DataRow, Item> u003cu003e9_2622 = ParcelaRepository.u003cu003ec.u003cu003e9__26_22;
				if (u003cu003e9_2622 == null)
				{
					u003cu003e9_2622 = (DataRow i) => new Item()
					{
						Id = i.Field<long>("iditem"),
						Descricao = i.Field<string>("descricao")
					};
					ParcelaRepository.u003cu003ec.u003cu003e9__26_22 = u003cu003e9_2622;
				}
				documento.ItensAtivo = new List<Item>(list1.Select<DataRow, Item>(u003cu003e9_2622).ToList<Item>());
				observableCollection.Documento = documento;
				return observableCollection;
			}).ToList<Parcela>();
		}

		public async Task<List<Parcela>> FindByRecebimento(Filtros filtro)
		{
			NegocioCorretora fieldValue;
			bool flag;
			bool count;
			object connection;
			bool count1;
			bool flag1;
			List<Item> itensAtivo;
			decimal num;
			object produto;
			object estipulante;
			object statu;
			string str;
			decimal num1;
			decimal num2;
			decimal num3;
			DateTime dateTime;
			DateTime? nullable;
			NegocioCorretora negocioCorretora;
			bool count2;
			bool flag2;
			Parcela parcela;
			List<Parcela> parcelas = new List<Parcela>();
			List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, "CAST(p.DATAREC AS DATE)");
			List<Condicao> condicaos1 = new List<Condicao>();
			Condicao condicao = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = null,
				Grupo = 1,
				Operacao = Operacao.Or
			};
			condicaos1.Add(condicao);
			Condicao condicao1 = new Condicao()
			{
				Campo = "d.Excluido",
				Valores = "0".CriarValor<string>(),
				Grupo = 1,
				Operacao = Operacao.Or
			};
			condicaos1.Add(condicao1);
			condicaos.AddRange(condicaos1);
			List<long> vendedores = filtro.Vendedores;
			if (vendedores != null)
			{
				count = vendedores.Count > 0;
			}
			else
			{
				count = false;
			}
			if (count)
			{
				if (await this.VerificaVendedorPropriaCorretora(filtro.Vendedores))
				{
					List<Condicao> condicaos2 = condicaos;
					Condicao condicao2 = new Condicao()
					{
						Campo = "vp.idvendedor",
						Valores = null,
						Grupo = 5,
						Operacao = Operacao.Or
					};
					condicaos2.Add(condicao2);
				}
			}
			SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0);
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandTimeout = 1500;
						string str1 = "SELECT p.IDPARCELA IdParcela,p.PARCELA NumeroParcela,p.DATAREC DataRecebimento,p.dataquit DataQuitacao,p.datacontrole DataControleParcela,p.VENCTO Vencimento,p.VLRCOMISS ValorComissao,p.IRR Irr,p.ISS Iss,p.DESCONTO Desconto,p.OUTROS Outros,p.VLRCOMDESC ValorComDesconto,p.COMISS ComissaoParcela,p.VALORR ValorRealizado,p.VALORLF PremioLiquidoFatura,p.VALOR PremioTotalFatura,p.IDSUBTIPO SubTipo,d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.idcliente IdCliente,clie.NOME NomeCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,r.idramo IdRamo,r.NOME NomeRamo,cia.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocial,pr.idproduto IdProduto,pr.NOME NomeProduto,e.idestipulante IdEstipulante,e.nome NomeEstipulante,s.idstatus IdStatus,s.nome NomeStatus,d.ADINACOMIS AdicionalComiss,d.contrato Apolice,d.ADITAMENTO Endosso,d.COM01 ComissaoDocumento,d.NegocioCorretora,d.idnegocio Negocio,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.vigencia1 VigenciaInicial,d.vigencia2 VigenciaFinal,d.SITUACAO Situacao,d.TIPO Tipo,d.tiporecebimento TipoRecebimento,d.datacontrole DataControleDocumento,d.PASTA PastaDocumento,vp.IDVENDEDORPARCELA IdVendedorParcela,vp.VLRREP ValorRepasse,vp.VREP PorcentagemRepasse,vp.DATAPGT DataPagamento,vp.DATAPREPAGTO DataPrePagamento,vp.idtipovendedor IdTipoVendedor,vp.IDVENDEDOR IdVendedor,v.NOME NomeVendedor,f.vigenciai VigenciaInicialFatura,f.vigenciaf VigenciaFinalFatura,f.NUMFATURA Fatura FROM parcela p INNER JOIN documento d ON d.IDDOCUMENTO = p.IDDOCUMENTO INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDPARCELA = p.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN fatura f ON f.IDPARCELA = p.IDPARCELA WHERE ";
						sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao);
						sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
						using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
						{
							while (true)
							{
								if (!await sqlDataReader.ReadAsync())
								{
									break;
								}
								if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora"))
								{
									fieldValue = sqlDataReader.GetFieldValue<NegocioCorretora>("NegocioCorretora", true, true);
								}
								else
								{
									flag = sqlDataReader.GetFieldValue<TipoSeguro>("Situacao", true, true) == TipoSeguro.Renovacao;
									if (flag)
									{
										flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio");
									}
									negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue<string>("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
									fieldValue = negocioCorretora;
								}
								NegocioCorretora negocioCorretora1 = fieldValue;
								if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora1))
								{
									long fieldValue1 = sqlDataReader.GetFieldValue<long>("IdParcela", true, true);
									Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1);
									if (observableCollection == null)
									{
										long fieldValue2 = sqlDataReader.GetFieldValue<long>("IdControle", true, true);
										Parcela parcela1 = parcelas.Find((Parcela p) => p.Documento.Controle.Id == fieldValue2);
										if (parcela1 != null)
										{
											itensAtivo = parcela1.Documento.ItensAtivo;
										}
										else
										{
											itensAtivo = null;
										}
										List<Item> items = itensAtivo;
										if (items == null)
										{
											items = await this.BuscaItemsPorIdControle(fieldValue2);
										}
										TipoRecebimento tipoRecebimento = sqlDataReader.GetFieldValue<TipoRecebimento>("TipoRecebimento", true, true);
										decimal fieldValue3 = sqlDataReader.GetFieldValue<decimal>("ValorComissao", true, true);
										decimal fieldValue4 = sqlDataReader.GetFieldValue<decimal>("ValorComDesconto", true, true);
										long num4 = sqlDataReader.GetFieldValue<long>("IdEmpresa", true, true);
										parcela = new Parcela()
										{
											Id = fieldValue1,
											NumeroParcela = sqlDataReader.GetFieldValue<int>("NumeroParcela", true, true),
											DataRecebimento = sqlDataReader.GetFieldValue<DateTime?>("DataRecebimento", true, true),
											DataQuitacao = sqlDataReader.GetFieldValue<DateTime?>("DataQuitacao", true, true),
											DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleParcela", true, true),
											Vencimento = sqlDataReader.GetFieldValue<DateTime>("Vencimento", true, true),
											ValorComissao = fieldValue3,
											Irr = sqlDataReader.GetFieldValue<decimal>("Irr", true, true),
											Iss = sqlDataReader.GetFieldValue<decimal>("Iss", true, true),
											Desconto = sqlDataReader.GetFieldValue<decimal>("Desconto", true, true),
											Outros = sqlDataReader.GetFieldValue<decimal>("Outros", true, true)
										};
										Parcela parcela2 = parcela;
										num = (fieldValue4 == decimal.Zero ? fieldValue3 : fieldValue4);
										parcela2.ValorComDesconto = num;
										parcela.Comissao = sqlDataReader.GetFieldValue<decimal>("ComissaoParcela", true, true);
										parcela.ValorRealizado = sqlDataReader.GetFieldValue<decimal>("ValorRealizado", true, true);
										parcela.SubTipo = sqlDataReader.GetFieldValue<SubTipo>("SubTipo", true, true);
										parcela.IdEmpresa = num4;
										Parcela parcela3 = parcela;
										Documento documento = new Documento()
										{
											Id = sqlDataReader.GetFieldValue<long>("IdDocumento", true, true)
										};
										Documento documento1 = documento;
										Controle controle = new Controle()
										{
											Id = fieldValue2,
											IdEmpresa = num4
										};
										Controle controle1 = controle;
										Cliente cliente = new Cliente()
										{
											Id = sqlDataReader.GetFieldValue<long>("IdCliente", true, true),
											Nome = sqlDataReader.GetFieldValue<string>("NomeCliente", true, true),
											Pasta = sqlDataReader.GetFieldValue<string>("PastaCliente", true, true)
										};
										bool? nullable1 = sqlDataReader.GetFieldValue<bool?>("MalaDireta", true, true);
										cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true));
										controle1.Cliente = cliente;
										Controle controle2 = controle;
										Ramo ramo = new Ramo()
										{
											Id = sqlDataReader.GetFieldValue<long>("IdRamo", true, true),
											Nome = sqlDataReader.GetFieldValue<string>("NomeRamo", true, true)
										};
										controle2.Ramo = ramo;
										Controle controle3 = controle;
										Seguradora seguradora = new Seguradora()
										{
											Id = sqlDataReader.GetFieldValue<long>("IdCiaSeg", true, true),
											Nome = sqlDataReader.GetFieldValue<string>("NomeCia", true, true),
											NomeSocial = sqlDataReader.GetFieldValue<string>("NomeSocial", true, true)
										};
										controle3.Seguradora = seguradora;
										Controle controle4 = controle;
										flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto");
										Controle controle5 = controle4;
										if (flag)
										{
											produto = null;
										}
										else
										{
											produto = new Produto();
											((DomainBase)produto).Id = sqlDataReader.GetFieldValue<long>("IdProduto", true, true);
											((Produto)produto).Nome = sqlDataReader.GetFieldValue<string>("NomeProduto", true, true);
										}
										controle5.Produto = (Produto)produto;
										documento1.Controle = controle;
										Documento documento2 = documento;
										bool flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante");
										Documento documento3 = documento2;
										if (flag3)
										{
											estipulante = null;
										}
										else
										{
											estipulante = new Estipulante();
											((DomainBase)estipulante).Id = sqlDataReader.GetFieldValue<long>("IdEstipulante", true, true);
											((Estipulante)estipulante).Nome = sqlDataReader.GetFieldValue<string>("NomeEstipulante", true, true);
										}
										documento3.Estipulante1 = (Estipulante)estipulante;
										Documento documento4 = documento;
										bool flag4 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus");
										Documento documento5 = documento4;
										if (flag4)
										{
											statu = null;
										}
										else
										{
											statu = new Status();
											((DomainBase)statu).Id = sqlDataReader.GetFieldValue<long>("IdStatus", true, true);
											((Status)statu).Nome = sqlDataReader.GetFieldValue<string>("NomeStatus", true, true);
										}
										documento5.Status = (Status)statu;
										documento.AdicionalComiss = sqlDataReader["AdicionalComiss"].ToString() == "1";
										documento.Apolice = sqlDataReader.GetFieldValue<string>("Apolice", true, true);
										Documento documento6 = documento;
										str = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<string>("Endosso", true, true) : string.Concat("F ", sqlDataReader.GetFieldValue<string>("Fatura", true, true)));
										documento6.Endosso = str;
										Documento documento7 = documento;
										num1 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<decimal>("ComissaoDocumento", true, true) : sqlDataReader.GetFieldValue<decimal>("ComissaoParcela", true, true));
										documento7.Comissao = num1;
										documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora1);
										Documento nullable2 = documento;
										Negocio? nullable3 = sqlDataReader.GetFieldValue<Negocio?>("Negocio", true, true);
										nullable2.Negocio = new Negocio?(nullable3.GetValueOrDefault(Negocio.Proprio));
										Documento documento8 = documento;
										num2 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<decimal>("PremioLiquido", true, true) : sqlDataReader.GetFieldValue<decimal>("PremioLiquidoFatura", true, true));
										documento8.PremioLiquido = num2;
										Documento documento9 = documento;
										num3 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<decimal>("PremioTotal", true, true) : sqlDataReader.GetFieldValue<decimal>("PremioTotalFatura", true, true));
										documento9.PremioTotal = num3;
										documento.PremioAdicional = sqlDataReader.GetFieldValue<decimal>("PremioAdicional", true, true);
										Documento documento10 = documento;
										if (tipoRecebimento == TipoRecebimento.Parcela)
										{
											dateTime = sqlDataReader.GetFieldValue<DateTime>("VigenciaInicial", true, true);
										}
										else
										{
											DateTime? nullable4 = sqlDataReader.GetFieldValue<DateTime?>("VigenciaInicialFatura", true, true);
											dateTime = (nullable4.HasValue ? nullable4.GetValueOrDefault() : sqlDataReader.GetFieldValue<DateTime>("Vencimento", true, true));
										}
										documento10.Vigencia1 = dateTime;
										Documento documento11 = documento;
										nullable = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<DateTime?>("VigenciaFinal", true, true) : sqlDataReader.GetFieldValue<DateTime?>("VigenciaFinalFatura", true, true));
										documento11.Vigencia2 = nullable;
										documento.Situacao = sqlDataReader.GetFieldValue<TipoSeguro>("Situacao", true, true);
										documento.Tipo = sqlDataReader.GetFieldValue<int>("Tipo", true, true);
										documento.TipoRecebimento = new TipoRecebimento?(tipoRecebimento);
										documento.DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleDocumento", true, true);
										documento.Pasta = sqlDataReader.GetFieldValue<string>("PastaDocumento", true, true);
										documento.ItensAtivo = items;
										parcela3.Documento = documento;
										observableCollection = parcela;
										parcela3 = null;
										documento1 = null;
										controle4 = null;
										controle = null;
										documento2 = null;
										documento4 = null;
										documento = null;
										parcela = null;
										if (observableCollection.Vendedores == null)
										{
											observableCollection.Vendedores = new ObservableCollection<VendedorParcela>();
										}
										parcelas.Add(observableCollection);
										items = null;
									}
									List<long> tipoVendedor = filtro.TipoVendedor;
									if (tipoVendedor != null)
									{
										count1 = tipoVendedor.Count > 0;
									}
									else
									{
										count1 = false;
									}
									if (!count1)
									{
										List<long> nums = filtro.Vendedores;
										if (nums != null)
										{
											flag1 = nums.Count > 0;
										}
										else
										{
											flag1 = false;
										}
										if (!flag1)
										{
											long fieldValue5 = sqlDataReader.GetFieldValue<long>("IdVendedorParcela", true, true);
											if (fieldValue5 > (long)0)
											{
												ObservableCollection<VendedorParcela> vendedores1 = observableCollection.Vendedores;
												VendedorParcela vendedorParcela = new VendedorParcela()
												{
													Id = fieldValue5,
													ValorRepasse = new decimal?(sqlDataReader.GetFieldValue<decimal>("ValorRepasse", true, true)),
													PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue<decimal>("PorcentagemRepasse", true, true)),
													DataPagamento = sqlDataReader.GetFieldValue<DateTime?>("DataPagamento", true, true),
													DataPrePagamento = sqlDataReader.GetFieldValue<DateTime?>("DataPrePagamento", true, true)
												};
												TipoVendedor tipoVendedor1 = new TipoVendedor()
												{
													Id = sqlDataReader.GetFieldValue<long>("IdTipoVendedor", true, true)
												};
												vendedorParcela.TipoVendedor = tipoVendedor1;
												Vendedor vendedor = new Vendedor()
												{
													Id = sqlDataReader.GetFieldValue<long>("IdVendedor", true, true),
													Nome = sqlDataReader.GetFieldValue<string>("NomeVendedor", true, true)
												};
												vendedorParcela.Vendedor = vendedor;
												vendedores1.Add(vendedorParcela);
											}
										}
									}
								}
							}
						}
						sqlDataReader = null;
						List<long> nums1 = filtro.TipoVendedor;
						if (nums1 != null)
						{
							count2 = nums1.Count > 0;
						}
						else
						{
							count2 = false;
						}
						if (!count2)
						{
							List<long> vendedores2 = filtro.Vendedores;
							if (vendedores2 != null)
							{
								flag2 = vendedores2.Count > 0;
							}
							else
							{
								flag2 = false;
							}
							if (!flag2)
							{
								goto Label0;
							}
						}
						foreach (Parcela parcela4 in parcelas)
						{
							parcela = parcela4;
							List<VendedorParcela> vendedorParcelas = await this.BuscaVendedoresPorIdParcela(parcela4.Id, parcela4.IdEmpresa, (long)0);
							parcela.Vendedores = new ObservableCollection<VendedorParcela>(vendedorParcelas);
							parcela = null;
						}
					Label0:
					}
					sqlCommand = null;
				}
				sqlConnection = null;
			}
			sessionFactory = null;
			List<Parcela> parcelas1 = parcelas;
			parcelas = null;
			condicaos = null;
			return parcelas1;
		}

		public List<Parcela> FindByVencimento(Filtros filtro)
		{
			List<Parcela> parcelas;
			object connection;
			string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",", 
				from v in filtro.Status
				select v), ")"));
			string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",", 
				from v in filtro.Negocio
				select v), ")"));
			string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",", 
				from v in filtro.Seguradoras
				select v), ")"));
			string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",", 
				from v in filtro.Ramos
				select v), ")"));
			string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",", 
				from v in filtro.Produtos
				select v), ")"));
			string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",", 
				from v in filtro.Vendedores
				select v), ")"));
			string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",", 
				from v in filtro.Estipulantes
				select v), ")"));
			string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			DataTable dataTable1 = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					string str8 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0.00) as valorcomissao, p.iddocumento, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01, 0.00) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)";
					string str9 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 ";
					sqlCommand.CommandText = string.Format("{0} {1} AND p.vencto >= '{2:yyyy-MM-dd}' AND p.vencto <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str8, str7, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str6, str5 });
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						string str10 = string.Concat(" AND vp.idparcela IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
						sqlCommand.CommandText = string.Concat(str9, " ", str10);
						using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
						{
							sqlDataAdapter1.SelectCommand = sqlCommand;
							sqlDataAdapter1.Fill(dataTable1);
							goto Label0;
						}
					}
					else
					{
						parcelas = new List<Parcela>();
					}
				}
			}
			return parcelas;
		Label0:
			return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Parcela>((DataRow x) => {
				decimal? nullable3;
				decimal valueOrDefault;
				decimal num;
				Parcela parcela = new Parcela()
				{
					Id = x.Field<long>("id"),
					IdEmpresa = x.Field<long>("idempresa"),
					NumeroParcela = int.Parse(x.Field<object>("parcela").ToString()),
					DataRecebimento = x.Field<DateTime?>("recebimento")
				};
				DateTime? nullable4 = x.Field<DateTime?>("vencimento");
				parcela.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue);
				parcela.ValorComDesconto = (x.Field<object>("valorcomdesconto") == null || x.Field<decimal>("valorcomdesconto") == decimal.Zero ? (x.Field<object>("valorcomissao") == null ? decimal.Zero : x.Field<decimal>("valorcomissao")) : x.Field<decimal>("valorcomdesconto"));
				parcela.Comissao = x.Field<decimal>("comiss");
				parcela.Valor = x.Field<decimal>("valor");
				parcela.StatusPagamento = new StatusPagamento?((x.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field<object>("StatusPagamento").ToString())));
				parcela.IdParcelaPendente = x.Field<long?>("IdParcelaPendente").GetValueOrDefault();
				IEnumerable<DataRow> list = 
					from v in dataTable1.AsEnumerable().ToList<DataRow>()
					where v.Field<long>("id") == x.Field<long>("id")
					select v;
				Func<DataRow, VendedorParcela> u003cu003e9_2810 = ParcelaRepository.u003cu003ec.u003cu003e9__28_10;
				if (u003cu003e9_2810 == null)
				{
					u003cu003e9_2810 = (DataRow v) => {
						DateTime? nullable;
						DateTime? nullable1;
						DateTime? nullable2;
						VendedorParcela vendedorParcela = new VendedorParcela()
						{
							Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == v.Field<long>("idvendedor")),
							ValorRepasse = new decimal?((v.Field<object>("valorrepasse") == null ? decimal.Zero : v.Field<decimal>("valorrepasse"))),
							PorcentagemRepasse = new decimal?((v.Field<object>("porcentagemrepasse") == null ? decimal.Zero : v.Field<decimal>("porcentagemrepasse")))
						};
						if (v.Field<object>("datapagamento") == null)
						{
							nullable = null;
							nullable1 = nullable;
						}
						else
						{
							nullable1 = v.Field<DateTime?>("datapagamento");
						}
						vendedorParcela.DataPagamento = nullable1;
						if (v.Field<object>("dataprepagamento") == null)
						{
							nullable = null;
							nullable2 = nullable;
						}
						else
						{
							nullable2 = v.Field<DateTime?>("dataprepagamento");
						}
						vendedorParcela.DataPrePagamento = nullable2;
						return vendedorParcela;
					};
					ParcelaRepository.u003cu003ec.u003cu003e9__28_10 = u003cu003e9_2810;
				}
				parcela.Vendedores = new ObservableCollection<VendedorParcela>(list.Select<DataRow, VendedorParcela>(u003cu003e9_2810).ToList<VendedorParcela>());
				Documento documento = new Documento()
				{
					Controle = new Controle()
					{
						IdEmpresa = x.Field<long>("idempresa"),
						Cliente = new Cliente()
						{
							Id = x.Field<long>("idcliente"),
							Nome = x.Field<string>("cliente"),
							IdEmpresa = x.Field<long>("idempresa"),
							MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
						},
						Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
						Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
						Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null)
					},
					AdicionalComiss = x.Field<string>("adinacomiss") == "1",
					Apolice = x.Field<string>("apolice"),
					Endosso = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<string>("endosso") : string.Concat("F ", x.Field<string>("fatura"))),
					Comissao = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<decimal>("comissao") : x.Field<decimal>("comiss")),
					Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())))
				};
				if (x.Field<object>("tiporecebimento").ToString() == "1")
				{
					nullable3 = x.Field<decimal?>("liquido");
					valueOrDefault = nullable3.GetValueOrDefault();
				}
				else
				{
					nullable3 = x.Field<decimal?>("valorliquidofatura");
					valueOrDefault = nullable3.GetValueOrDefault();
				}
				documento.PremioLiquido = valueOrDefault;
				if (x.Field<object>("tiporecebimento").ToString() == "1")
				{
					nullable3 = x.Field<decimal?>("total");
					num = nullable3.GetValueOrDefault();
				}
				else
				{
					nullable3 = x.Field<decimal?>("valor");
					num = nullable3.GetValueOrDefault();
				}
				documento.PremioTotal = num;
				nullable3 = x.Field<decimal?>("adicional");
				documento.PremioAdicional = nullable3.GetValueOrDefault();
				documento.Vigencia1 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime>("vigenciainicial") : x.Field<DateTime>("vigenciai"));
				documento.Vigencia2 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime?>("vigenciafinal") : x.Field<DateTime?>("vigenciaf"));
				documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
				documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
				documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
				documento.Tipo = x.Field<int>("tipo");
				parcela.Documento = documento;
				return parcela;
			}).ToList<Parcela>();
		}

		public List<Documento> FindByVigencia(Filtros filtro)
		{
			return new List<Documento>();
		}

		public List<long> FindDocumentId(List<long> ids)
		{
			List<long> nums;
			object connection;
			if (ids == null || ids.Count == 0)
			{
				return ids;
			}
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					string str = string.Concat(" idparcela IN (", string.Join<long>(",", ids), ")");
					sqlCommand.CommandText = string.Concat("SELECT iddocumento FROM parcela p WHERE ", str);
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						return dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("iddocumento")).ToList<long>();
					}
					else
					{
						nums = new List<long>();
					}
				}
			}
			return nums;
		}

		public List<Documento> FindNumFatura(string numero)
		{
			List<Documento> documentos;
			object connection;
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			DataTable dataTable1 = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					sqlCommand.CommandTimeout = 15000;
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					string str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, p.iddocumento, d.contrato as apolice, f.numfatura as fatura, f.emissao, d.idnegocio, d.situacao, f.vigenciai as vigenciainicial, f.vigenciaf as vigenciafinal, ISNULL(p.valor, 0.00) as total, ISNULL(p.valorlf, 0.00) as liquido, 0.00 as adicional, '0' as adinacomiss, ISNULL(p.comiss, 0.00) as comissao, c.idramo, c.idciaseg as idseguradora, c.idproduto, 2 as tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.negociocorretora, d.datacontrole, d.idstatus, p.datacontrole as dataparcelacontrole, p.cri_data, d.banco, d.agencia, d.conta, d.pasta, d.propassinada FROM fatura f INNER JOIN parcela p on p.idparcela = f.idparcela INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0) AND  NUMFATURA ='", numero, "'");
					string str1 = "SELECT DISTINCT idparcela as id, idvendedor FROM vendedorparcela vp WHERE 1=1 ";
					sqlCommand.CommandText = str ?? "";
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					if (dataTable.Rows.Count != 0)
					{
						string str2 = string.Concat(" AND vp.idparcela IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
						sqlCommand.CommandText = string.Concat(str1, " ", str2);
						using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
						{
							sqlDataAdapter1.SelectCommand = sqlCommand;
							sqlDataAdapter1.Fill(dataTable1);
							goto Label0;
						}
					}
					else
					{
						documentos = new List<Documento>();
					}
				}
			}
			return documentos;
		Label0:
			return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Documento>((DataRow x) => {
				Func<DataRow, bool> func2 = null;
				Documento documento = new Documento()
				{
					Id = x.Field<long>("iddocumento"),
					Controle = new Controle()
					{
						Id = x.Field<long>("idcontrole"),
						IdEmpresa = x.Field<long>("idempresa"),
						Cliente = new Cliente()
						{
							Nome = x.Field<string>("cliente"),
							Id = x.Field<long>("idcliente"),
							IdEmpresa = x.Field<long>("idempresa"),
							MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
						},
						Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
						Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
						Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null)
					},
					Pasta = x.Field<string>("Pasta"),
					TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura),
					AdicionalComiss = false,
					Apolice = x.Field<string>("apolice"),
					Endosso = x.Field<string>("fatura"),
					Comissao = x.Field<decimal>("comissao"),
					NegocioCorretora = new NegocioCorretora?((x.Field<object>("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) != TipoSeguro.Renovacao || x.Field<object>("idnegocio") == null || x.Field<long>("idnegocio") != (long)1 ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("negociocorretora").ToString()))),
					Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())))
				};
				decimal? nullable = x.Field<decimal?>("liquido");
				documento.PremioLiquido = nullable.GetValueOrDefault();
				nullable = x.Field<decimal?>("total");
				documento.PremioTotal = nullable.GetValueOrDefault();
				DateTime? nullable1 = x.Field<DateTime?>("vigenciainicial");
				documento.Vigencia1 = (nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue);
				documento.Vigencia2 = x.Field<DateTime?>("vigenciafinal");
				documento.Emissao = x.Field<DateTime?>("emissao");
				documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
				documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
				documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
				documento.Vendedores = Auxiliar.Vendedores.Where<Vendedor>((Vendedor v) => {
					List<DataRow> list = dataTable1.AsEnumerable().ToList<DataRow>();
					Func<DataRow, bool> u003cu003e9_9 = func2;
					if (u003cu003e9_9 == null)
					{
						Func<DataRow, bool> func = (DataRow d) => d.Field<long>("id") == x.Field<long>("id");
						Func<DataRow, bool> func1 = func;
						func2 = func;
						u003cu003e9_9 = func1;
					}
					IEnumerable<DataRow> dataRows = list.Where<DataRow>(u003cu003e9_9);
					Func<DataRow, long> u003cu003e9_2210 = ParcelaRepository.u003cu003ec.u003cu003e9__22_10;
					if (u003cu003e9_2210 == null)
					{
						u003cu003e9_2210 = (DataRow d) => d.Field<long>("idvendedor");
						ParcelaRepository.u003cu003ec.u003cu003e9__22_10 = u003cu003e9_2210;
					}
					return dataRows.Select<DataRow, long>(u003cu003e9_2210).ToList<long>().Contains(v.Id);
				}).ToList<Vendedor>();
				documento.Tipo = x.Field<int>("tipo");
				documento.DataControle = x.Field<DateTime?>("dataparcelacontrole");
				documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status p) => p.Id == x.Field<long>("idstatus")) : null);
				documento.DataCriacao = x.Field<DateTime?>("cri_data");
				documento.Banco = new Banco()
				{
					Nome = x.Field<string>("banco")
				};
				documento.Agencia = x.Field<string>("agencia");
				documento.Conta = x.Field<string>("conta");
				documento.PropostaAssinada = (x.Field<object>("propassinada") == null ? false : x.Field<string>("propassinada") == "1");
				return documento;
			}).ToList<Documento>();
		}

		public bool FindParcel(long id)
		{
			bool flag;
			object connection;
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					string str = "SELECT DISTINCT c.idcliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.tiporecebimento, p.idparcela, pe.idparcela AS idParcelaParcelaExtrato, p.datacred FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN parcela p ON p.iddocumento = d.iddocumento INNER JOIN parcelaextrato pe ON pe.iddocumento = d.iddocumento WHERE (d.excluido IS NULL OR d.excluido = 0) ";
					DateTime networkTime = Funcoes.GetNetworkTime();
					sqlCommand.CommandText = string.Format("{0} AND (d.vigencia2 IS NULL AND d.situacao IN (1,2) OR d.vigencia2 >= '{1:yyyy-MM-dd}') AND DATALENGTH(ISNULL( d.contrato, '' )) > 0 AND d.iddocumento in ({2}) AND pe.idparcela = p.idparcela", str, networkTime.Date, id);
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
					bool flag1 = false;
					foreach (DataRow row in dataTable.Rows)
					{
						string str1 = string.Format("{0}", row["datacred"]);
						flag1 = (string.Format("{0}", row["idparcela"]) != string.Format("{0}", row["idParcelaParcelaExtrato"]) ? false : !string.IsNullOrEmpty(str1));
					}
					flag = flag1;
				}
			}
			return flag;
		}

		public Parcela Merge(Parcela parcela)
		{
			ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map<Parcela, ParcelaDb>(parcela);
			if (parcelaDb.IdEmpresa == 0)
			{
				parcelaDb.IdEmpresa = (long)1;
			}
			base.Merge(parcelaDb);
			if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela)
			{
				return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
			}
			FaturaDb fatura = this._unitOfWork.Query<FaturaDb>().FirstOrDefault<FaturaDb>((FaturaDb x) => x.Parcela.Id == parcelaDb.Id) ?? new FaturaDb();
			fatura.Parcela = parcelaDb;
			fatura.Fatura = parcelaDb.Fatura;
			FaturaDb faturaDb = fatura;
			DateTime? vigenciaIncial = parcelaDb.VigenciaIncial;
			faturaDb.VigenciaInicial = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaInicial);
			FaturaDb faturaDb1 = fatura;
			vigenciaIncial = parcelaDb.VigenciaFinal;
			faturaDb1.VigenciaFinal = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaFinal);
			FaturaDb faturaDb2 = fatura;
			vigenciaIncial = parcelaDb.Emissao;
			faturaDb2.Emissao = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.Emissao);
			if (fatura.Id != 0)
			{
				this._unitOfWork.Repository<FaturaDb>().Merge(fatura);
			}
			else
			{
				this._unitOfWork.Repository<FaturaDb>().SaveOrUpdate(fatura);
			}
			return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
		}

		public List<PrevisaoPagamento> PrevisaoPagamentoComissao(Filtros filtro)
		{
			object connection;
			string str2 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND d.situacao IN (", string.Join<long>(",", 
				from v in filtro.Status
				select v), ")"));
			string str3 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",", 
				from v in filtro.Negocio
				select v), ")"));
			string str4 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",", 
				from v in filtro.Seguradoras
				select v), ")"));
			string str5 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",", 
				from v in filtro.Ramos
				select v), ")"));
			string str6 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",", 
				from v in filtro.Produtos
				select v), ")"));
			string str7 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? " AND vp.idvendedor IS NOT NULL " : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",", 
				from v in filtro.Vendedores
				select v), ")"));
			string str8 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? " AND vp.idtipovendedor = 1 " : string.Concat(" AND vp.idtipovendedor IN (", string.Join<long>(",", 
				from v in filtro.TipoVendedor
				select v), ")"));
			string str9 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",", 
				from v in filtro.Estipulantes
				select v), ")"));
			string str10 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
			SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
			DataTable dataTable = new DataTable();
			if (sessionFactory != null)
			{
				connection = sessionFactory.ConnectionProvider.GetConnection();
			}
			else
			{
				connection = null;
			}
			using (SqlConnection sqlConnection = connection as SqlConnection)
			{
				using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
				{
					sqlCommand.CommandTimeout = 15000;
					Auxiliar.CriarAuxiliar(sqlCommand, false);
					sqlCommand.CommandText = string.Concat("SELECT DISTINCT d.tipo, f.NUMFATURA, f.VIGENCIAI, vp.idvendedorparcela, vp.idvendedor, cl.nome AS cliente, d.situacao, d.contrato, d.VIGENCIA1, d.aditamento, c.idciaseg, c.idramo, p.parcela, ISNULL(v.desconto, 0) as desconto, p.vencto, ISNULL(vp.vlrrep, 0) as vlrliquido, ISNULL(d.pr_liq, 0) as pr_liq, ISNULL(p.VALORLF, 0) as valorlf, ISNULL(p.vlrcomiss, 0) as vlrcomiss, p.idsubtipo, d.n_parc, d.tiporecebimento FROM controle c INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole INNER JOIN parcela p on p.iddocumento = d.iddocumento INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela INNER JOIN vendedor v on v.idvendedor = vp.idvendedor LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela ", string.Format("WHERE (d.excluido IS NULL OR d.excluido != 1) AND v.corretora != '1' AND vp.datapgt IS NULL AND vp.vlrrep != 0 AND (d.tiporecebimento = '1' AND ISNULL(d.com01, 0.00) > 0 OR d.tiporecebimento = '2') {0} {1} {2} {3} {4} {5} {6} {7} {8} AND p.vencto >= '{9:yyyy-MM-dd}' AND p.vencto <= '{10:yyyy-MM-dd}';", new object[] { str10, str7, str2, str3, str4, str5, str6, str8, str9, filtro.Inicio, filtro.Fim }));
					using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
					{
						sqlDataAdapter.SelectCommand = sqlCommand;
						sqlDataAdapter.Fill(dataTable);
					}
				}
			}
			return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, PrevisaoPagamento>((DataRow x) => {
				string nome;
				string str;
				string nome1;
				string str1;
				PrevisaoPagamento previsaoPagamento = new PrevisaoPagamento()
				{
					Nome = x.Campo<string>("cliente"),
					Apolice = (x.IsNull("tiporecebimento") ? "" : (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<string>("contrato") : x.Campo<string>("NUMFATURA"))),
					Endosso = (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<string>("aditamento") : ""),
					Status = x.Campo<TipoSeguro>("situacao").GetDescription<TipoSeguro>(),
					VigenciaInicial = (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<DateTime>("VIGENCIA1") : x.Campo<DateTime>("VIGENCIAI")),
					TipoDocumento = (x.IsNull("tiporecebimento") ? "" : (x.Campo<string>("tiporecebimento") == "2" ? "FATURA" : (x.Campo<string>("tipo") == "0" ? "APÓLICE" : "ENDOSSO")))
				};
				Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo<long>("idciaseg"));
				if (seguradora != null)
				{
					nome = seguradora.Nome;
				}
				else
				{
					nome = null;
				}
				previsaoPagamento.NomeSeguradora = nome;
				Ramo ramo = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo<long>("idramo"));
				if (ramo != null)
				{
					str = ramo.Nome;
				}
				else
				{
					str = null;
				}
				previsaoPagamento.NomeRamo = str;
				previsaoPagamento.PremioLiquido = (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<decimal>("pr_liq") : x.Campo<decimal>("valorlf"));
				previsaoPagamento.Parcela = (x.Campo<long>("idsubtipo") > (long)1 ? "ESPECIAL" : (x.Campo<string>("tiporecebimento") == "1" ? string.Concat(x.Campo<string>("parcela").PadLeft(2, '0'), " DE ", x.Campo<string>("n_parc")) : x.Campo<string>("parcela").PadLeft(2, '0')));
				previsaoPagamento.VencimentoParcela = x.Campo<DateTime>("vencto");
				previsaoPagamento.RepasseLiquido = x.Campo<decimal>("vlrliquido") * (decimal.One - (x.Campo<decimal>("desconto") > decimal.One ? x.Campo<decimal>("desconto") * new decimal(1, 0, 0, false, 2) : x.Campo<decimal>("desconto")));
				previsaoPagamento.Repasse = x.Campo<decimal>("vlrliquido");
				previsaoPagamento.Vendedor = Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Campo<long>("idvendedor"));
				Seguradora seguradora1 = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo<long>("idciaseg"));
				if (seguradora1 != null)
				{
					nome1 = seguradora1.Nome;
				}
				else
				{
					nome1 = null;
				}
				previsaoPagamento.Seguradora = nome1;
				Ramo ramo1 = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo<long>("idramo"));
				if (ramo1 != null)
				{
					str1 = ramo1.Nome;
				}
				else
				{
					str1 = null;
				}
				previsaoPagamento.Ramo = str1;
				return previsaoPagamento;
			}).ToList<PrevisaoPagamento>();
		}

		public Parcela SaveOrUpdate(Parcela parcela)
		{
			ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map<Parcela, ParcelaDb>(parcela);
			if (parcelaDb.IdEmpresa == 0)
			{
				parcelaDb.IdEmpresa = (long)1;
			}
			this.SaveOrUpdate(parcelaDb);
			if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela)
			{
				return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
			}
			FaturaDb faturaDb = new FaturaDb()
			{
				Parcela = parcelaDb,
				Fatura = parcelaDb.Fatura,
				VigenciaInicial = parcelaDb.VigenciaIncial,
				VigenciaFinal = parcelaDb.VigenciaFinal,
				Emissao = parcelaDb.Emissao
			};
			this._unitOfWork.Repository<FaturaDb>().SaveOrUpdate(faturaDb);
			return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
		}

		public int[] SincronizarPendencia(DateTime date, List<long> ids = null)
		{
			// 
			// Current member / type: System.Int32[] Gestor.Infrastructure.Repository.Logic.ParcelaRepository::SincronizarPendencia(System.DateTime,System.Collections.Generic.List`1<System.Int64>)
			// File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll
			// 
			// Product version: 0.0.0.0
			// Exception in: System.Int32[] SincronizarPendencia(System.DateTime,System.Collections.Generic.List<System.Int64>)
			// 
			// An item with the same key has already been added. Key: Label0
			//    at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
			//    at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(KeyValuePair`2 keyValuePair)
			//    at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 332
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 363
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23
			//    at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100
			//    at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72
			//    at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61
			//    at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133
			// 
			// mailto: JustDecompilePublicFeedback@telerik.com

		}

		public bool Update(List<DetalheExtrato> detalhes, bool desabilitaAproximação)
		{
			// 
			// Current member / type: System.Boolean Gestor.Infrastructure.Repository.Logic.ParcelaRepository::Update(System.Collections.Generic.List`1<Gestor.Model.Domain.Seguros.DetalheExtrato>,System.Boolean)
			// File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll
			// 
			// Product version: 0.0.0.0
			// Exception in: System.Boolean Update(System.Collections.Generic.List<Gestor.Model.Domain.Seguros.DetalheExtrato>,System.Boolean)
			// 
			// An item with the same key has already been added. Key: Label0
			//    at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
			//    at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(KeyValuePair`2 keyValuePair)
			//    at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 351
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384
			//    at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33
			//    at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23
			//    at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100
			//    at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72
			//    at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61
			//    at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133
			// 
			// mailto: JustDecompilePublicFeedback@telerik.com

		}

		public List<Parcela> UpdateRange(List<Parcela> parcelas)
		{
			List<ParcelaDb> parcelaDbs = ApplicationMapper.Mapper.Map<List<Parcela>, List<ParcelaDb>>(parcelas);
			parcelaDbs.ForEach((ParcelaDb x) => {
				if (x.IdEmpresa == 0)
				{
					x.IdEmpresa = (long)1;
				}
			});
			ParcelaRepository parcelaRepository = this;
			parcelaDbs.ForEach(new Action<ParcelaDb>(parcelaRepository.Merge));
			return ApplicationMapper.Mapper.Map<List<ParcelaDb>, List<Parcela>>(parcelaDbs);
		}

		private async Task<bool> VerificaVendedorPropriaCorretora(List<long> vendedores)
		{
			bool valueOrDefault;
			object connection;
			List<Condicao> condicaos = new List<Condicao>();
			Condicao condicao = new Condicao()
			{
				Campo = "IdVendedor",
				Valores = vendedores.CriarValor<long>(),
				Grupo = 1,
				Operacao = Operacao.Or
			};
			condicaos.Add(condicao);
			SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0);
			using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
			{
				SessionFactoryImpl sessionFactoryImpl = sessionFactory;
				if (sessionFactoryImpl != null)
				{
					connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
				}
				else
				{
					connection = null;
				}
				using (SqlConnection sqlConnection = connection as SqlConnection)
				{
					using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
					{
						sqlCommand.CommandText = string.Concat("SELECT COUNT(IdVendedor) FROM Vendedor WHERE Corretora = 1 AND ", sqlQueryCondition.Condicao);
						sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
						int? nullable = (int?)await sqlCommand.ExecuteScalarAsync();
						valueOrDefault = nullable.GetValueOrDefault() > 0;
					}
				}
			}
			return valueOrDefault;
		}

		private class VinculoParcela
		{
			public string Apolice
			{
				get;
				set;
			}

			public string Endosso
			{
				get;
				set;
			}

			public long IdDocumento
			{
				get;
				set;
			}

			public long IdParcela
			{
				get;
				set;
			}

			public int Parcela
			{
				get;
				set;
			}

			public Seguradora Seguradora
			{
				get;
				set;
			}

			public int Tipo
			{
				get;
				set;
			}

			public VinculoParcela()
			{
			}
		}
	}
}