派生自 projectDept/qhighschool

yn147
2023-05-10 96286178ee1c257c130cb2ad964a781f36c4eee5
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
package com.qxueyou.scc.exercise.service.impl;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
 
import com.alibaba.fastjson.JSONArray;
import com.qxueyou.scc.admin.classes.model.ClsClass;
import com.qxueyou.scc.base.dao.CommonDAO;
import com.qxueyou.scc.base.model.Result;
import com.qxueyou.scc.base.model.ResultJson;
import com.qxueyou.scc.base.service.ICacheService;
import com.qxueyou.scc.base.service.IFileUploadService;
import com.qxueyou.scc.base.service.impl.CommonAppService;
import com.qxueyou.scc.base.util.ClientUtils;
import com.qxueyou.scc.base.util.CollectionUtils;
import com.qxueyou.scc.base.util.TraceUtils;
import com.qxueyou.scc.base.util.UUIDUtils;
import com.qxueyou.scc.exercise.dao.ExerciseDAO;
import com.qxueyou.scc.exercise.model.ExerciseDeepAnalysis;
import com.qxueyou.scc.exercise.model.ExerciseGroup;
import com.qxueyou.scc.exercise.model.ExerciseGroupExtend;
import com.qxueyou.scc.exercise.model.ExerciseGroupItemRe;
import com.qxueyou.scc.exercise.model.ExerciseImportResult;
import com.qxueyou.scc.exercise.model.ExerciseItem;
import com.qxueyou.scc.exercise.model.ExerciseItemAnalisi;
import com.qxueyou.scc.exercise.model.ExerciseItemAnswerU;
import com.qxueyou.scc.exercise.model.ExerciseItemOption;
import com.qxueyou.scc.exercise.model.ExerciseItemScore;
import com.qxueyou.scc.exercise.model.ExerciseItemStatistics;
import com.qxueyou.scc.exercise.model.ExerciseObjectImg;
import com.qxueyou.scc.exercise.model.ExerciseOptionStatistics;
import com.qxueyou.scc.exercise.model.ExerciseParse;
import com.qxueyou.scc.exercise.model.ExerciseParseResult;
import com.qxueyou.scc.exercise.model.ExerciseReCourse;
import com.qxueyou.scc.exercise.model.ExerciseRecord;
import com.qxueyou.scc.exercise.model.QExerciseGroup;
import com.qxueyou.scc.exercise.model.QExerciseGroupItemRe;
import com.qxueyou.scc.exercise.model.QExerciseItem;
import com.qxueyou.scc.exercise.model.QExerciseItemAnalisi;
import com.qxueyou.scc.exercise.model.QExerciseItemAnswerU;
import com.qxueyou.scc.exercise.model.QExerciseItemOption;
import com.qxueyou.scc.exercise.model.QExerciseObjectImg;
import com.qxueyou.scc.exercise.service.IExerciseService;
import com.qxueyou.scc.exercise.service.impl.node.Doc;
import com.qxueyou.scc.exercise.util.ExerciseUtils;
import com.qxueyou.scc.org.model.OrgCharger;
import com.qxueyou.scc.school.model.SchClassSubject;
import com.qxueyou.scc.school.model.SchCourseware;
import com.qxueyou.scc.school.model.SchEvaluate;
import com.qxueyou.scc.school.service.ICourseWareService;
import com.qxueyou.scc.sys.model.SysFileUploadTrace;
import com.qxueyou.scc.sys.service.IOssService;
import com.qxueyou.scc.teach.subject.model.SubjectChapter;
import com.qxueyou.scc.user.model.UserRegistration;
 
/**
 * 练习 实现service  练习后台
 * 
 * @author zhiyong
 *
 */
@Service
public class ExerciseService extends CommonAppService implements IExerciseService {
    private ExerciseDAO exerDAO;
 
    @Autowired
    IOssService ossService;
 
    @Autowired
    ICacheService cacheService;
    
    @Autowired
    IFileUploadService fileUploadService;
    
    @Autowired
    private ICourseWareService courseWareService;
    
    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;
    
    
    private final String[] letter = "A B C D E F G H I J K L M N O P Q".split(" ");
 
    private static Logger log = LogManager.getLogger("ExerciseService");
 
    public ExerciseDAO getExerDAO() {
        return exerDAO;
    }
 
    /**
     * 依赖注入
     *
     * @param exerExtendDAO
     */
    @Autowired(required = false)
    public void setExerDAO(@Qualifier("exerciseDAO") ExerciseDAO exerDAO) {
        this.exerDAO = exerDAO;
    }
 
 
 
    /*
     * (non-Javadoc)
     * 
     * @see com.iqtogether.qxueyou.exercise.service.IExerciseService#insertExerciseGroup(java.lang.String, short, java.lang.String, java.lang.String)
     */
    @Override
    public Result insertExerciseGroup(String name, short type, String lessonId, String chapterId) {
 
        int iCount = 0;
        if (type == 3) {
            // 查询当前class存在的存在的顺序、随机练习或者 章节练习 个数
            // 可能结果:0、 新增三种;1,新增两种(顺序随机),2,新增一种(章节),3的话,不增加
            String hsql = "from ExerciseGroup where classId = ? and  case when type = ? then 1 when type = ? then 1 when type = ? and "
                    + " attribute1 = ? and attribute2 = ? then 1 else 0 end  = 1 and deleteFlag is false";
            iCount = findCount(hsql, CollectionUtils.newList(ClientUtils.getClassId(), ExerciseGroup.TYPE_EXERCISE_RANDOM, ExerciseGroup.TYPE_EXERCISE_SEQUENCE, ExerciseGroup.TYPE_CHAPTER_ITEM, lessonId, chapterId));
        }
 
        Result objResult = saveOrUpdateAll(initExerciseGroupList(name, type, lessonId, chapterId, iCount));
 
        // 保存
        return objResult;
    }
 
    /**
     * 新增练习组
     * 
     * @param name
     *            练习组名称
     * @param type
     *            练习组类型
     * @param lessonId
     *            课程id
     * @param chapterId
     *            章节id
     * @param 模拟考试
     *            时间设置
     * @return
     */
    public Result insertExerciseGroup(String groupId,String name, short type, String lessonId, String chapterId, String attribute1, boolean repeatFlag) {
        
        if(StringUtils.isNotBlank(groupId)){ // 更新
            
            return updateExerciseGroup(groupId, name, type, lessonId, chapterId, attribute1, repeatFlag);
        }else{ // 新增
            
            return saveExerciseGroup(name, type, lessonId, chapterId, attribute1, repeatFlag);
        }
    }
    
    public Result updateExerciseGroup(String groupId,String name, short type, String subjectId, String chapterId, String attribute1, boolean repeatFlag) {
        ExerciseGroup group = read(ExerciseGroup.class, groupId);
        
        if(type == ExerciseGroup.TYPE_CHAPTER_ITEM){ // 章节练习
            
            group.setAttribute2(chapterId);
        }
        if (type == ExerciseGroup.TYPE_MOCK_EXAM) {// 模拟考试
            // 添加练习组时间 、是否重做
            addExerciseGroupExtendTime(groupId, attribute1, repeatFlag);
        }
        if (type == ExerciseGroup.TYPE_HOMEWORK) {// 家庭作业
            // 添加是否重做
            addExerciseGroupExtendTime(groupId, null, repeatFlag);
        }
        
        group.setName(name);
        //group.setSubjectId(subjectId);
        TraceUtils.setUpdateTrace(group);
        
        return this.saveExerciseGroup(group);
    }
    
    public Result saveExerciseGroup(String name, short type, String lessonId, String chapterId, String attribute1, boolean repeatFlag) {
        int iCount = 0;
        if (type == ExerciseGroup.TYPE_EXERCISE_SEQUENCE) {
            // 查询当前class存在的存在的顺序、随机练习或者 章节练习 个数
            // 可能结果:0、 新增三种;1,新增两种(顺序随机),2,新增一种(章节),3的话,不增加
            String hsql = "from ExerciseGroup where classId = ? and  case when type = ? then 1 when type = ? then 1 when type = ? and "
                    + " attribute1 = ? and attribute2 = ? then 1 else 0 end  = 1 and deleteFlag is false";
            iCount = findCount(hsql, CollectionUtils.newList(ClientUtils.getClassId(), ExerciseGroup.TYPE_EXERCISE_RANDOM, ExerciseGroup.TYPE_EXERCISE_SEQUENCE, ExerciseGroup.TYPE_CHAPTER_ITEM, lessonId, chapterId));
        }
 
        List<ExerciseGroup> lstExeGroup = initExerciseGroupList(name, type, lessonId, chapterId, iCount);
 
        // 兼容1.0版本 模拟考试时间设置
        for (ExerciseGroup group : lstExeGroup) {
            
            group.setOrderNum(BigInteger.valueOf(SchCourseware.COURSEWARE_MAX_ORDER));
            
            if (ExerciseGroup.TYPE_MOCK_EXAM == group.getType()) {
                group.setAttribute1(attribute1);
            }
            
            this.saveExerciseGroup(group);
        }
 
        //Result objResult = saveOrUpdateAll(lstExeGroup);
 
        if (type == ExerciseGroup.TYPE_MOCK_EXAM) {// 模拟考试
            // 添加练习组时间 、是否重做
            addExerciseGroupExtendTime(lstExeGroup.get(0).getGroupId(), attribute1, repeatFlag);
        }
        if (type == ExerciseGroup.TYPE_HOMEWORK) {// 家庭作业
            // 添加是否重做
            addExerciseGroupExtendTime(lstExeGroup.get(0).getGroupId(), null, repeatFlag);
        }
 
        // 保存
        return new Result(true);
    }
 
    /**
     * 新增题库
     * 
     * @param name
     *            练习组名称
     * @param type
     *            练习组类型
     * @param lessonId
     *            课程id
     * @param chapterId
     *            章节id
     * @param 模拟考试
     *            时间设置
     * @return
     */
    public Result insertOrgExercise(ExerciseGroup group, boolean repeatFlag) {
        
        if(StringUtils.isNotBlank(group.getGroupId())){ // 更新
            
            return updateOrgExerciseGroup(group, repeatFlag);
        }else{ // 新增
            
            return saveOrgExerciseGroup(group, repeatFlag);
        }
    }
    
    public Result updateOrgExerciseGroup(ExerciseGroup group, boolean repeatFlag) {
        
        ExerciseGroup oldGroup = read(ExerciseGroup.class, group.getGroupId());
        
        if (oldGroup.getType() == ExerciseGroup.TYPE_MOCK_EXAM) {// 模拟考试
            // 添加练习组时间 、是否重做
            addExerciseGroupExtendTime(group.getGroupId(), group.getAttribute1(), repeatFlag);
        }
        if (oldGroup.getType() == ExerciseGroup.TYPE_HOMEWORK) {// 家庭作业
            // 添加是否重做
            addExerciseGroupExtendTime(group.getGroupId(), null, repeatFlag);
        }
        
        oldGroup.setName(group.getName());
        TraceUtils.setUpdateTrace(oldGroup);
        
        return this.saveExerciseGroup(oldGroup);
    }
    
    public Result saveOrgExerciseGroup(ExerciseGroup group, boolean repeatFlag) {
        group.setGroupId(null);
        TraceUtils.setCreateTrace(group);
        group.setDeleteFlag(false);
        group.setOrgId(ClientUtils.getOrgId());
        group.setAllCount(BigInteger.ZERO);
        this.saveExerciseGroup(group);
        group.setOriginExerciseId(group.getGroupId());
        this.saveExerciseGroup(group);
 
        if (StringUtils.isNotBlank(group.getAttribute1())) {
            addExerciseGroupExtendTime(group.getGroupId(), group.getAttribute1(), repeatFlag);
        }
        if (group.getType() == ExerciseGroup.TYPE_HOMEWORK) {// 家庭作业
            // 添加是否重做
            addExerciseGroupExtendTime(group.getGroupId(), null, repeatFlag);
        }
        
        this.insertReCourse(group.getCollegeCourseId(), group.getGroupId());
        
        return new Result(true);
    }
    
    /**
     * 拷贝练习
     * 
     * @param id
     * @param subjectId
     * @param collegeCourseId
     * @param chapterId
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    public Result doCopyExerciseGroup(String id, String subjectId, String collegeCourseId, String chapterId) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
        ExerciseGroup oldExercise = this.read(ExerciseGroup.class, id);
        
        ExerciseGroup newGroup = new ExerciseGroup();
        TraceUtils.setCreateTrace(newGroup);
        newGroup.setGroupId(null);
        newGroup.setAllCount(oldExercise.getAllCount());
        newGroup.setClassId(oldExercise.getClassId());
        newGroup.setAttribute1(oldExercise.getAttribute1());
        newGroup.setAttribute2(oldExercise.getAttribute2());
        newGroup.setEditFlag(oldExercise.getEditFlag());
        newGroup.setOriginExerciseId(oldExercise.getGroupId());
        newGroup.setOrderNum(BigInteger.valueOf(SchCourseware.COURSEWARE_MAX_ORDER));
        newGroup.setDoCount("0");
        newGroup.setType(oldExercise.getType());
        newGroup.setOrgId(ClientUtils.getOrgId());
        newGroup.setName(oldExercise.getName());
        newGroup.setSubjectId(subjectId);
        newGroup.setChapterId(chapterId);
        newGroup.setCollegeCourseId(collegeCourseId);
        
        this.saveExerciseGroup(newGroup);
        
        //班级拷贝不需要新增关联表
        if(StringUtils.isEmpty(ClientUtils.getClassId())){
            newGroup.setOriginExerciseId(newGroup.getGroupId());
            this.saveExerciseGroup(newGroup);
            this.insertReCourse(collegeCourseId, newGroup.getGroupId());
        }
        
        // 扩展表: extend
        this.doSaveCopyExtend(oldExercise,newGroup);
        
        this.doCopyExerciseItem(newGroup.getGroupId(), oldExercise.getGroupId(), null, 1);//拷贝
        
        return new Result(true);
    }
    
    /**
     * 拷贝练习题
     * 
     * @param items
     * @param newGroupId
     * @param oldGroupId
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws InstantiationException 
     * @throws IllegalAccessException 
     */
    public void doCopyExerciseItem(String newGroupId, String oldGroupId, List<ExerciseItem> items, int type) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException{
        if(items == null || items.size() == 0){
            items = this.find("select i from ExerciseItem i, ExerciseGroupItemRe r where i.deleteFlag is false AND r.exerciseGroupId = ?"+
                    " and r.exerciseItemId = i.exerciseId AND r.deleteFlag IS FALSE",
                    CollectionUtils.newList(oldGroupId), ExerciseItem.class);
        }
        if(items != null && !items.isEmpty()){
            List<ExerciseItemAnalisi> analysisesNew = new ArrayList<>();
            List<ExerciseGroupItemRe> reNew = new ArrayList<>();
            List<ExerciseObjectImg> exerciseObjectImgNew = new ArrayList<>();
            
            // 得到当前组题目的最大题号
            int maxGroupItemOrder = queryExerciseGroupItemNo(newGroupId);
            
            for(ExerciseItem objExerciseItem : items){
                ExerciseGroupItemRe oldExerciseGroupItemRe = this.findUnique("from ExerciseGroupItemRe where deleteFlag is false and exerciseGroupId = ? and exerciseItemId = ?",
                        CollectionUtils.newList(oldGroupId, objExerciseItem.getExerciseId()), ExerciseGroupItemRe.class);
                
                //临时对象
                ExerciseItem tem = new ExerciseItem();
                tem = (ExerciseItem) BeanUtils.cloneBean(objExerciseItem);
                List<ExerciseObjectImg> exerciseObjectImg = this.find("from ExerciseObjectImg m where m.deleteFlag is false and m.exerciseObjectId = ?",
                        CollectionUtils.newList(objExerciseItem.getExerciseId()), ExerciseObjectImg.class);
                ExerciseItemAnalisi analysises = this.findUnique("from ExerciseItemAnalisi m where m.deleteFlag is false and m.exerciseItemId = ?",
                        CollectionUtils.newList(objExerciseItem.getExerciseId()), ExerciseItemAnalisi.class);
                List<ExerciseItemOption> options = objExerciseItem.getOptions();
                tem.setOptions(null);
                tem.setAnalysises(null);
//                tem.setGroups(null);
                tem.setScores(null);
                
                ExerciseItem objExerciseItemNew = new ExerciseItem();
                BeanUtils.copyProperties(objExerciseItemNew, tem);
                objExerciseItemNew.setExerciseId(null);
                //拷贝的练习不同步
                objExerciseItemNew.setOrgiExerciseId(type == 1?null:StringUtils.isEmpty(objExerciseItem.getOrgiExerciseId())?objExerciseItem.getExerciseId():objExerciseItem.getOrgiExerciseId());
                TraceUtils.setCreateTrace(objExerciseItemNew);
                
                this.save(objExerciseItemNew);
                
                String exerciseIdNew = objExerciseItemNew.getExerciseId();
            
                for(ExerciseItemOption objExerciseItemOption : options){
                    ExerciseItemOption objExerciseItemOptionNew = new ExerciseItemOption();
                    BeanUtils.copyProperties(objExerciseItemOptionNew, objExerciseItemOption);
                    objExerciseItemOptionNew.setExerciseItemId(exerciseIdNew);
                    objExerciseItemOptionNew.setOptionId(null);
                    
                    TraceUtils.setCreateTrace(objExerciseItemOptionNew);
                    
                    this.save(objExerciseItemOptionNew);
                    //optionsNew.add(objExerciseItemOptionNew);
                    
                    List<ExerciseObjectImg> optionObjectImgs = this.find("from ExerciseObjectImg m where m.deleteFlag is false and m.exerciseObjectId = ?",
                            CollectionUtils.newList(objExerciseItemOption.getOptionId()), ExerciseObjectImg.class);
                    if(optionObjectImgs != null && !optionObjectImgs.isEmpty()){
                        for(ExerciseObjectImg optionObjectImg : optionObjectImgs){
                            ExerciseObjectImg objExerciseObjectImgNew = new ExerciseObjectImg();
                            BeanUtils.copyProperties(objExerciseObjectImgNew, optionObjectImg);
                            objExerciseObjectImgNew.setExerciseObjectId(objExerciseItemOptionNew.getOptionId());
                            objExerciseObjectImgNew.setImgId(null);
                            
                            TraceUtils.setCreateTrace(objExerciseObjectImgNew);
                            
                            exerciseObjectImgNew.add(objExerciseObjectImgNew);
                        }
                    }
                }
                if(analysises != null){
                    ExerciseItemAnalisi objExerciseItemAnalisiNew = new ExerciseItemAnalisi();
                    BeanUtils.copyProperties(objExerciseItemAnalisiNew, analysises);
                    objExerciseItemAnalisiNew.setExerciseItemId(exerciseIdNew);
                    objExerciseItemAnalisiNew.setExerciseAnalisisId(null);
                    
                    TraceUtils.setCreateTrace(objExerciseItemAnalisiNew);
                    
                    analysisesNew.add(objExerciseItemAnalisiNew);
                }
                if(exerciseObjectImg != null && !exerciseObjectImg.isEmpty()){
                    for(ExerciseObjectImg objExerciseObjectImg : exerciseObjectImg){
                        ExerciseObjectImg objExerciseObjectImgNew = new ExerciseObjectImg();
                        BeanUtils.copyProperties(objExerciseObjectImgNew, objExerciseObjectImg);
                        objExerciseObjectImgNew.setExerciseObjectId(exerciseIdNew);
                        objExerciseObjectImgNew.setImgId(null);
                        
                        TraceUtils.setCreateTrace(objExerciseObjectImgNew);
                        
                        exerciseObjectImgNew.add(objExerciseObjectImgNew);
                    }
                }
                
                ExerciseGroupItemRe re = new ExerciseGroupItemRe();
                re.setDeleteFlag(false);
                re.setExerciseGroupId(newGroupId);
                re.setExerciseItemId(exerciseIdNew);
                re.setRelationId(null);
                if(oldExerciseGroupItemRe != null){
                    re.setDocOrder(oldExerciseGroupItemRe.getDocOrder());
                }
                re.setItemOrder(++maxGroupItemOrder);
                reNew.add(re);
            }
            
            this.saveOrUpdateAll(reNew);
            //this.saveOrUpdateAll(optionsNew);
            this.saveOrUpdateAll(analysisesNew);
            this.saveOrUpdateAll(exerciseObjectImgNew);
            
            //更新统计
            this.updateGroupUpdateTimeByList(this.find("from ExerciseGroup where groupId = ?", CollectionUtils.newList(newGroupId), ExerciseGroup.class));
        }
    }
    
    /**
     * 插入练习和科目关联
     * 
     * @param collegeCourseId
     * @param handoutId
     */
    private void insertReCourse(String collegeCourseId, String groupId){
        // 序号
        String hql = "select MAX(c.orderNum) from ExerciseReCourse c where c.deleteFlag is false and c.collegeCourseId = ? and orgId = ? ";
        Integer iMax = this.findUnique(hql, CollectionUtils.newList(collegeCourseId, ClientUtils.getOrgId()), Integer.class);
    
        if (iMax == null || iMax == 0) {
            iMax = 1;
        } else {
            iMax = iMax + 1;
        }
    
        ExerciseReCourse course = new ExerciseReCourse();
        TraceUtils.setCreateTrace(course);
        course.setCollegeCourseId(collegeCourseId);
        course.setDeleteFlag(false);
        course.setGroupId(groupId);
        course.setOrgId(ClientUtils.getOrgId());
        course.setOrderNum(iMax);
        save(course);
    }
 
    public Result insertAppointExercise(String groupIds[], String orgIds[], String classIds[]) {
 
        if (null == groupIds || groupIds.length == 0) {
            return new Result(false, "参数错误");
        }
        // 一次性查询groupId对应的collegeCourseId
        String hql = " from ExerciseReCourse where groupId in (:groupIds) and deleteFlag is false";
        Map<String, Object> argsMap = new HashMap<String, Object>();
        argsMap.put("groupIds", groupIds);
        List<ExerciseReCourse> courseList = findByComplexHql(hql, argsMap, ExerciseReCourse.class);
 
        // 放入map中 KEY:groupId VALUE:collegeCourseId
        Map<String, String> groupReCourse = new HashMap<String, String>();
        for (ExerciseReCourse exerciseReCourse : courseList) {
            groupReCourse.put(exerciseReCourse.getGroupId(), exerciseReCourse.getCollegeCourseId());
        }
 
        // 一次性查询classId对应的orgId
        Map<String, String> classMap = new HashMap<String, String>();
        if (classIds.length > 0) {
            hql = " from ClsClass where classId in (:classIds) and deleteFlag is false";
            argsMap = new HashMap<String, Object>();
            argsMap.put("classIds", classIds);
            List<ClsClass> classList = findByComplexHql(hql, argsMap, ClsClass.class);
 
            // 放入map中 KEY:classId VALUE:orgId
 
            for (ClsClass orgClass : classList) {
                classMap.put(orgClass.getClassId(), orgClass.getOrgId());
            }
        }
        
        // 一次性查询groupId对应的orderNum
        Map<String, Integer> orderMap = new HashMap<String, Integer>();
        
        hql = " from ExerciseReCourse where groupId in (:groupIds) and deleteFlag is false and orgId = :currOrgId";
        argsMap = new HashMap<String, Object>();
        argsMap.put("groupIds", groupIds);
        argsMap.put("currOrgId", ClientUtils.getOrgId());
        List<ExerciseReCourse> courseLst = findByComplexHql(hql, argsMap, ExerciseReCourse.class);
 
        // 放入map中 KEY:classId VALUE:orgId
        for (ExerciseReCourse c : courseLst) {
            orderMap.put(c.getGroupId(), c.getOrderNum());
        }
        
        for (String groupId : groupIds) {
            if (orgIds.length > 0) { // 指定给机构
                insertOrgGroup(groupId, orgIds, groupReCourse.get(groupId),orderMap);
            }
            if (classIds.length > 0) { // 指定给班级
                ExerciseGroup group = read(ExerciseGroup.class, groupId);
                insertClassGroup(groupId, classIds, group, groupReCourse.get(groupId), classMap,orderMap);
            }
        }
        return new Result(true);
    }
 
    /**
     * 指定给机构
     * 
     * @param groupId
     * @param orgIds
     * @param groupReCourse
     * @return
     */
    public void insertOrgGroup(String groupId, String orgIds[], String collegeCourseId,Map<String, Integer> orderMap) {
        // 查询出所有不符合条件的数据
        String hql = "select orgId from ExerciseReCourse where groupId = :groupId and deleteFlag is false and orgId in (:orgIds)";
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("groupId", groupId);
        args.put("orgIds", orgIds);
        List<String> strings = findByComplexHql(hql, args, String.class);
        List<String> orgList = new ArrayList<String>();
        for (String orgId : orgIds) {
            orgList.add(orgId);
        }
        // 剔除掉不符合条件的orgId
        orgList.removeAll(strings);
        if(orgList.isEmpty()){
            return;
        }
 
        for (String orgId : orgList) {
            ExerciseReCourse exerCourse = new ExerciseReCourse();
            exerCourse.setExerciseCourseId(null);
            exerCourse.setOrgId(orgId);
            exerCourse.setGroupId(groupId);
            exerCourse.setCollegeCourseId(collegeCourseId);
            exerCourse.setDeleteFlag(false);
            exerCourse.setOrderNum(orderMap.get(groupId));
            TraceUtils.setCreateTrace(exerCourse);
            save(exerCourse);
            
            this.courseWareService.insertOrgCourseware(groupId, ClientUtils.getOrgId(), orgId, collegeCourseId);
        }
 
    }
    /**
     * 指定给班级
     * @param groupId
     * @param classIds
     * @param group
     * @param collegeCourseId
     * @param classMap
     */
    public void insertClassGroup(String groupId, String classIds[], ExerciseGroup group, String collegeCourseId, Map<String, String> classMap,Map<String, Integer> orderMap) {
        //章节id
        Map<String,SubjectChapter> origChapterMap = new HashMap<String, SubjectChapter>();
        Map<String, String> subjectMap = new HashMap<String, String>();
        String hql = "from ExerciseGroupExtend where deleteFlag is false and groupId=? ";
        // 查询练习组扩展表
        ExerciseGroupExtend extend = this.findUnique(hql, CollectionUtils.newList(groupId), ExerciseGroupExtend.class);
 
        //hql = " from ExerciseGroupItemRe where exerciseGroupId = ? and deleteFlag is false ";
        //List<ExerciseGroupItemRe> lstItem = find(hql, CollectionUtils.newList(groupId), ExerciseGroupItemRe.class);
 
        // 查询出所有不符合条件的数据
        hql = "select classId from ExerciseGroup where classId in (:classIds) and originExerciseId = :groupId and deleteFlag is false";
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("classIds", classIds);
        args.put("groupId", groupId);
        List<String> strings = findByComplexHql(hql, args, String.class);
        List<String> classList = new ArrayList<String>();
        for (String classId : classIds) {
            classList.add(classId);
        }
        // 剔除不符合的classId
        classList.removeAll(strings);
        if(classList.isEmpty()){
            return;
        }
        if(StringUtils.isNotEmpty(group.getSubjectId())){
            // 一次性查询班级ID对应的classSubjectId
            hql = " from SchClassSubject where classId in(:classIds) and origSubjectId = :subjectId and deleteFlag is false";
            args = new HashMap<String, Object>();
            args.put("classIds", classList.toArray());
            args.put("subjectId", group.getSubjectId());
            List<SchClassSubject> lstClassSubject = findByComplexHql(hql, args, SchClassSubject.class);
            for (SchClassSubject schClassSubject : lstClassSubject) {
                subjectMap.put(schClassSubject.getClassId(), schClassSubject.getClassSubjectId());
            }
        }
        for (String classId : classList) {
 
            ExerciseGroup newGroup = new ExerciseGroup();
            newGroup.setAllCount(group.getAllCount());
            newGroup.setAttribute1(group.getAttribute1());
            newGroup.setAttribute2(group.getAttribute2());
            newGroup.setCollegeCourseId(collegeCourseId);
            newGroup.setDeleteFlag(false);
            newGroup.setDoCount(group.getDoCount());
            newGroup.setName(group.getName());
            newGroup.setOrgId(classMap.get(classId));
            newGroup.setType(group.getType());
            newGroup.setClassId(classId);
            newGroup.setOriginExerciseId(groupId);
            newGroup.setOrderNum(group.getOrderNum());
            newGroup.setSubjectId(subjectMap.get(classId));
            if(null != origChapterMap.get(classId)){
                newGroup.setChapterId(origChapterMap.get(classId).getChapterId());
            }else{
                newGroup.setChapterId(null);
            }
            TraceUtils.setCreateTrace(newGroup);
            this.saveExerciseGroup(newGroup);
 
            if (extend != null) {
                if (StringUtils.isNotBlank(extend.getExerciseTime())) {
                    addExerciseGroupExtendTime(newGroup.getGroupId(), extend.getExerciseTime(), extend.getRepeatFlag());
                }
                if (newGroup.getType() == ExerciseGroup.TYPE_HOMEWORK) {// 家庭作业
                    // 添加是否重做
                    addExerciseGroupExtendTime(newGroup.getGroupId(), null, extend.getRepeatFlag());
                }
            }
            try {
                
                this.doCopyExerciseItem(newGroup.getGroupId(), groupId, null, 2);
                
            }catch (IllegalAccessException e) {
                log.error("下发练习出错", e);
            } catch (InvocationTargetException e) {
                log.error("下发练习出错", e);
            } catch (InstantiationException e) {
                log.error("下发练习出错", e);
            } catch (NoSuchMethodException e) {
                log.error("下发练习出错", e);
            }
        }
    }
 
 
 
    /**
     * 添加练习时间
     * 
     * @param groupId
     * @param exerciseTime
     * @return
     */
    public Result addExerciseGroupExtendTime(String groupId, String exerciseTime, boolean repeatFlag) {
 
        String hql = "from ExerciseGroupExtend where deleteFlag is false and groupId=? ";
 
        // 查询练习组扩展表
        ExerciseGroupExtend extend = this.findUnique(hql, CollectionUtils.newList(groupId), ExerciseGroupExtend.class);
 
        if (null == extend) {
            extend = new ExerciseGroupExtend();
            extend.setGroupId(groupId);
            extend.setExerciseTime(exerciseTime);
            extend.setRepeatFlag(repeatFlag);
 
            insertExerciseGroupExtend(extend);
        } else {
            extend.setExerciseTime(exerciseTime);
            extend.setRepeatFlag(repeatFlag);
            updateExerciseGroupExtend(extend);
        }
 
        return new Result(true);
    }
 
    /**
     * 新增练习扩展表
     * 
     * @param extend
     * @return
     */
    public Result insertExerciseGroupExtend(ExerciseGroupExtend extend) {
 
        extend.setDeleteFlag(false);
        TraceUtils.setCreateTrace(extend);
        this.save(extend);
 
        return new Result(true);
    }
 
    /**
     * 更新练习扩展表
     * 
     * @param extend
     * @return
     */
    public Result updateExerciseGroupExtend(ExerciseGroupExtend extend) {
 
        TraceUtils.setUpdateTrace(extend);
        this.save(extend);
 
        return new Result(true);
    }
 
    /*
     * (non-Javadoc)
     * 
     * @see com.iqtogether.qxueyou.exercise.service.IExerciseService#readExerciseItems(java.lang.String)
     */
    @Override
    public List<ExerciseItem> readExerciseItems(String groupId) {
        ExerciseGroup group = read(ExerciseGroup.class, groupId);
        List<ExerciseItem> lst = group.getItems();
        TraceUtils.removeDelete(lst);
        return lst;
    }
 
    /*
     * (non-Javadoc)
     * 
     * @see com.iqtogether.qxueyou.exercise.service.IExerciseService#readExerciseItems(java.lang.String) 20150901:增加排序,习题数据和前台app顺序默认一致,题号保持一致。随机练习处理
     */
    @Override
    public List<ExerciseItem> readExerciseItemsWithNo(String groupId) {
 
        ExerciseGroup group = read(ExerciseGroup.class, groupId);
        if (null == group) {
            return null;
        }
 
        // 默认章节练习
        String hql = "select item,re.docOrder,re.relationId " + "from ExerciseItem item,ExerciseGroupItemRe re " + "where re.exerciseGroupId=? " + "and re.exerciseItemId=item.exerciseId " + "and item.deleteFlag is false " + "and re.deleteFlag is false " + "order by re.itemOrder ";
 
        // 随机练习,顺序练习
        if (ExerciseGroup.TYPE_EXERCISE_RANDOM == group.getType() || ExerciseGroup.TYPE_EXERCISE_SEQUENCE == group.getType()) {
            hql = "select item,re.docOrder,re.relationId " + "from ExerciseItem item,ExerciseGroupItemRe re " + "where re.exerciseGroupId=? and " + "re.exerciseItemId=item.exerciseId " + "and item.deleteFlag is false " + "and re.deleteFlag is false " + "order by item.chapterId, re.itemOrder ";
        }
 
        List<Object[]> objs = this.exerDAO.findwithRawResult(hql, CollectionUtils.newList(groupId));
 
        List<ExerciseItem> items = new ArrayList<ExerciseItem>(objs.size());
 
        ExerciseItem item;
        ExerciseItem newitem;
        if (null != objs && !objs.isEmpty()) {
            for (int iNum = 0; iNum < objs.size(); iNum++) {
                if (null == objs.get(iNum)) {
                    continue;
                }
 
                item = new ExerciseItem();
                try {
                    newitem = (ExerciseItem) objs.get(iNum)[0];
                    newitem.setOptions(null);
                    newitem.setScores(null);
                    newitem.setAnalysises(null);
                    BeanUtils.copyProperties(item, newitem);
                } catch (IllegalAccessException e) {
                    log.error(e, e);
                } catch (InvocationTargetException e) {
                    log.error(e, e);
                }
 
                // 此序号和app一致
                item.setItemNo(iNum + 1);
 
                // 此序号和导入的doc文档一致,如果是导入的习题
                if (null != objs.get(iNum)[1]) {
                    item.setDocNo((int) objs.get(iNum)[1]);
                }
 
                // 关联表ID
                if (null != objs.get(iNum)[2]) {
                    item.setReId((String) objs.get(iNum)[2]);
                }
 
                items.add(item);
 
            }
        }
 
        return items;
    }
 
    /**
     * 查看问卷详情
     * 
     * @param groupId
     *            问题组id
     * @param evaluateTemId
     *            模板id
     * @return
     */
    @Override
    public List<ExerciseItem> readExerciseItems4Evaluate(String groupId) {
 
        ExerciseGroup group = this.read(ExerciseGroup.class, groupId);
        if (null == group) {
            new ResultJson(false, "习题组不存在");
        }
 
        QExerciseItem qItem = QExerciseItem.exerciseItem;
        QExerciseGroupItemRe qRe = QExerciseGroupItemRe.exerciseGroupItemRe;
        
        List<ExerciseItem> lstItems = this.getQueryFactory()
        .select(qItem)
        .from(qItem,qRe)
        .where(qItem.exerciseId.eq(qRe.exerciseItemId)
                .and(qRe.exerciseGroupId.eq(groupId))
                .and(qItem.deleteFlag.eq(false))
                .and(qRe.deleteFlag.eq(false)))
                .orderBy(qRe.itemOrder.asc())
                .fetch();
        
        if(lstItems.isEmpty()){
            return lstItems;
        }
        
        // 0.组装参数
        Map<String, Object> argsMap = new HashMap<String, Object>();
        Object[] args = new Object[lstItems.size()];
        for(int i=0; i<lstItems.size(); i++){
            args[i] = lstItems.get(i).getExerciseId();
        }
        argsMap.put("exerciseIds", args);
        
        // 1.查询练习题目全站分析
        String hql_analisis = "from ExerciseItemAnalisi  where exerciseItemId in (:exerciseIds)  and deleteFlag is false ";
        List<ExerciseItemAnalisi> lstAnalisis = this.findByComplexHql(hql_analisis, argsMap, ExerciseItemAnalisi.class);
        Map<String, ExerciseItemAnalisi> analisiMap = new HashMap<String, ExerciseItemAnalisi>(lstAnalisis.size());
        for(ExerciseItemAnalisi analisis:lstAnalisis){
            analisiMap.put(analisis.getExerciseItemId(), analisis);
        }
        
        // 2.查询练习题目答案选项
        Map<String, List<ExerciseItemOption>> optionsMap = new HashMap<String, List<ExerciseItemOption>>(lstItems.size());
        Map<String, String> answerMap = new HashMap<String, String>();
        String hql_options = "from ExerciseItemOption where exerciseItemId in (:exerciseIds) and deleteFlag is false order by exerciseItemId, optionOrder ";
        List<ExerciseItemOption> lstAllOptions = this.findByComplexHql(hql_options, argsMap, ExerciseItemOption.class);
        // 2.1.组装参数 用于查询练习选项图片
        Map<String, Object> argsImgMap = new HashMap<String, Object>();
        Object[] argImgs = new Object[lstAllOptions.size()];
        for(int i=0; i<lstAllOptions.size(); i++){
            argImgs[i] = lstAllOptions.get(i).getOptionId();
        }
        argsImgMap.put("optionIds", argImgs);
        
        // 2-3-1查询题目是否关联图片
        String hql_itemImgs = "from ExerciseObjectImg where exerciseObjectId in (:exerciseIds) and deleteFlag is false and objectType=1 order by exerciseObjectId,imgOrder ";
        List<ExerciseObjectImg> lstItemImgs = this.findByComplexHql(hql_itemImgs, argsMap, ExerciseObjectImg.class);
        Map<String, List<ExerciseObjectImg>> imgItemMap = ExerciseUtils.packageExerciseItemImg(lstItemImgs);
        
        Map<String, List<ExerciseObjectImg>> imgOptionMap = null;
        if(argImgs.length > 0) {
            // 2-3-2查询题目选项是否关联图片
            String hql_optionImgs = "from ExerciseObjectImg where exerciseObjectId in (:optionIds) and deleteFlag is false and objectType=2";
            List<ExerciseObjectImg> lstOptionImgs = this.findByComplexHql(hql_optionImgs, argsImgMap, ExerciseObjectImg.class);
            imgOptionMap = ExerciseUtils.packageExerciseItemImg(lstOptionImgs);
        }
        
        // 重新组装练习
        ExerciseUtils.packageExerciseItem(optionsMap, answerMap, lstAllOptions, imgOptionMap);
        
        
        // 4.重新组装返回结果
        String exerciseId = null;
        for(ExerciseItem item:lstItems){
            // 4.0  分析结果
            exerciseId = item.getExerciseId();
            
            // 得到练习组id
            if(StringUtils.isNotBlank(groupId)){
                item.setExerciseGroupId(groupId);
            }
            
            // 4.3 题目选项
            item.setOptions(optionsMap.get(exerciseId));
            
            // 4.5题目中是否有图片
            if(imgItemMap.get(exerciseId) != null){
                item.setImgs(imgItemMap.get(exerciseId));
            }
            
            if(analisiMap.get(exerciseId) != null){
                item.setAnalisis(analisiMap.get(exerciseId));
            }
        }
        
        return lstItems;
    }
 
    /*
     * (non-Javadoc)
     * 
     * @see com.iqtogether.qxueyou.exercise.service.IExerciseService#insertExerciseItem(java.lang.String, com.iqtogether.qxueyou.exercise.model.ExerciseItem, java.util.List)
     */
    @Override
    public Result insertExerciseItem(String groupId, ExerciseItem item, List<ExerciseItemOption> lstOptions, String analysis) {
 
        TraceUtils.setCreateTrace(lstOptions);
        // 1. 保存习题
        ExerciseGroup group = this.read(ExerciseGroup.class, groupId);
        handlerExerciseItem(group, item);
        save(item);
 
        // 2. 保存习题和习题组关系
        // 获取一个习题需要跟新的关系条数
        List<ExerciseGroup> result = initExerciseGroup(groupId);
 
        // 得到当前组题目的最大题号
        int maxGroupItemOrder = queryExerciseGroupItemNo(groupId);
 
        List<ExerciseGroupItemRe> groupRes = initExerciseGroupItemRe(result, item.getExerciseId(), getGroupReMaxOrder(groupId), ++maxGroupItemOrder );
 
        // 得到最大的ORDER
        saveOrUpdateAll(groupRes);
        
        // 20150618:配合前台app,所有修改同时修改group表最后修改时间
        updateGroupUpdateTimeByList(result);
 
        // 3. 保存习题解析
        ExerciseItemAnalisi analysisVO = new ExerciseItemAnalisi();
        analysisVO.setAnalysis(analysis);
        analysisVO.setAccuracy(BigDecimal.ZERO);
        analysisVO.setSubmitCorrectNumber(BigInteger.ZERO);
        analysisVO.setSubmitNumber(BigInteger.ZERO);
        item.setAnalisis(analysisVO);
        saveAnalysis(item);
        
 
        // 4. 保存习题选项
        for (ExerciseItemOption option : lstOptions) {
            option.setExerciseItemId(item.getExerciseId());
            save(option);
            // 新增习题选项图片
            updateExerOptionObjImgId(option);
        }
        item.setOptions(lstOptions);
 
        // 新增习题图片
        updateExerciseObjImgId(item);
        
        //保存题目分数
        List<ExerciseItemScore>  lstExerciseItemScore = item.getScores();
        if(lstExerciseItemScore!=null && lstExerciseItemScore.size()>0){
            for (ExerciseItemScore score : lstExerciseItemScore) {
                TraceUtils.setCreateTrace(score);
                score.setGroupId(groupId);
                score.setExerciseItemId(item.getExerciseId());
                save(score);
            }
        }
        
//        if(StringUtils.isEmpty(group.getClassId())){
//            // 同步习题
//            String hql = " from ExerciseGroup where originExerciseId = ?  and deleteFlag is false and groupId != ?";
//            List<ExerciseGroup> lstGroup = find(hql, CollectionUtils.newList(group.getOriginExerciseId(), groupId), ExerciseGroup.class);
//            List<ExerciseItem> items = find("from ExerciseItem where exerciseId = ?", CollectionUtils.newList(item.getExerciseId()), ExerciseItem.class);
//            for (ExerciseGroup exerciseGroup : lstGroup) {
//                exerciseGroup.setAllCount(group.getAllCount());
//                TraceUtils.setUpdateTrace(exerciseGroup);
//                this.saveExerciseGroup(exerciseGroup);
//                try {
//                    this.doCopyExerciseItem(exerciseGroup.getGroupId(), groupId, items, 2);
//                } catch (IllegalAccessException | InstantiationException | InvocationTargetException
//                        | NoSuchMethodException e) {
//                    log.error("新增练习同步到班级错误", e);
//                }
//            }
//        }
 
        return new Result(true, item.getExerciseId());
    }
 
    /*
     * (non-Javadoc)
     * 
     * @see com.iqtogether.qxueyou.exercise.service.IExerciseService#insertExerciseItem(java.lang.String, com.iqtogether.qxueyou.exercise.model.ExerciseItem, java.util.List)
     */
    @Override
    public ResultJson insertExerciseItem4Evaluate(String groupId, ExerciseItem item,
            List<ExerciseItemOption> lstOptions,String analysis,JSONArray titleImgs) {
        // 1. 保存习题
        TraceUtils.setCreateTrace(item);
        this.save(item);
 
        // 2、保存习题关联组
        QExerciseGroupItemRe qRe =QExerciseGroupItemRe.exerciseGroupItemRe;
        Integer maxGroupItemOrder = 
                this.getQueryFactory().select(qRe.itemOrder.max())
                .from(qRe).where(qRe.deleteFlag.eq(false).and(qRe.exerciseGroupId.eq(groupId)))
                .fetchOne();
 
        if (maxGroupItemOrder == null) {
            maxGroupItemOrder = 0;
        }
 
        ExerciseGroupItemRe re = new ExerciseGroupItemRe();
        re.setExerciseGroupId(groupId);
        re.setExerciseItemId(item.getExerciseId());
        re.setItemOrder(maxGroupItemOrder);
        re.setDeleteFlag(false);
        this.save(re);
        
        // 题目组题目个数+1
        QExerciseGroup g = QExerciseGroup.exerciseGroup;
        this.getQueryFactory()
        .update(g)
        .set(g.allCount, g.allCount.add(BigInteger.ONE))
        .where(g.groupId.eq(groupId))
        .execute();
        
        
        // 3. 保存习题选项
        for (int i = 0; i < lstOptions.size(); i++) {
            ExerciseItemOption option = lstOptions.get(i);
            option.setExerciseItemId(item.getExerciseId());
            option.setOptionId(null);
            option.setOptionOrder(letter[i]);
            TraceUtils.setCreateTrace(option);
            this.save(option);
            
            // 更新选项图片
            updateEvaExerOptionObjImgId(option);
            
            ExerciseItemScore objExerciseItemScore = new ExerciseItemScore();
            TraceUtils.setCreateTrace(objExerciseItemScore);
            objExerciseItemScore.setAttribute1(option.getOptionId());
            objExerciseItemScore.setExerciseItemId(item.getExerciseId());
            objExerciseItemScore.setExerciseItemAnswer(letter[i]);
            objExerciseItemScore.setScore(String.valueOf(option.getScore()));
            this.save(objExerciseItemScore);
        }
        
        // 更新题目图片
        this.updateEvaExerciseObjImgId(titleImgs,item.getExerciseId());
 
        // 4. 保存习题解析
        ExerciseItemAnalisi analysisVO = new ExerciseItemAnalisi();
        analysisVO.setAnalysis(analysis);
        analysisVO.setAccuracy(BigDecimal.ZERO);
        analysisVO.setSubmitCorrectNumber(BigInteger.ZERO);
        analysisVO.setSubmitNumber(BigInteger.ZERO);
        TraceUtils.setCreateTrace(analysisVO);
        analysisVO.setDeleteFlag(false);
        analysisVO.setExerciseItemId(item.getExerciseId());
        save(analysisVO);
        
        return new ResultJson(true);
    }
 
    /**
     * 更新习题选项图片对象结果
     * 
     * @param optionId
     * @param imgIds
     * @return
     */
    private Result updateExerciseObjImgId(ExerciseItem item) {
 
        List<ExerciseObjectImg> imgs = item.getImgs();
        if (imgs == null || imgs.isEmpty()) {
            return new Result(false);
        }
        Object[] imgIds = new Object[imgs.size()];
        for (int i = 0; i < imgs.size(); i++) {
            imgIds[i] = imgs.get(i).getImgId();
        }
        String hql = "update ExerciseObjectImg set exerciseObjectId='" + item.getExerciseId() + "' where imgId=? and deleteFlag is false";
 
        this.bulkUpdateInLoop(hql, imgIds);
 
        return new Result(true);
    }
 
    /**
     * 更新习题选项图片对象结果
     * 
     * @param optionId
     * @param imgIds
     * @return
     */
    private Result updateExerOptionObjImgId(ExerciseItemOption option) {
 
        List<ExerciseObjectImg> imgs = option.getImgs();
        if (imgs == null || imgs.isEmpty()) {
            return new Result(false);
        }
        Object[] imgIds = new Object[imgs.size()];
        for (int i = 0; i < imgs.size(); i++) {
            imgIds[i] = imgs.get(i).getImgId();
        }
        String hql = "update ExerciseObjectImg set exerciseObjectId='" + option.getOptionId() + "' where imgId=? and deleteFlag is false";
 
        this.bulkUpdateInLoop(hql, imgIds);
 
        return new Result(true);
    }
 
    /**
     * 处理exerciseItem
     * 
     * @param groupId
     * @param item
     */
    private void handlerExerciseItem(ExerciseGroup group, ExerciseItem item) {
        // 如果是章节练习,将章节写到exerciseItem
        if (ExerciseGroup.TYPE_CHAPTER_ITEM == group.getType()) {
            item.setChapterId(group.getAttribute2());
        }
        TraceUtils.setCreateTrace(item);
    }
 
    private int getGroupReMaxOrder(String groupId) {
        String hql = "select max(itemOrder) from ExerciseGroupItemRe where deleteFlag is false and exerciseGroupId = ? ";
        Integer maxOrder = this.findUnique(hql, CollectionUtils.newList(groupId), Integer.class);
        if (null == maxOrder) {
            maxOrder = 0;
        }
        return maxOrder + 1;
    }
 
    /**
     * 刪除练习关联表数据
     * 
     * @param reIds
     * @return
     */
    private Result deleteExerciseGroupRe(String[] reIds) {
 
        String hql = "update ExerciseGroupItemRe set deleteFlag=1 where relationId=? ";
 
        this.bulkUpdateInLoop(hql, reIds);
 
        return new Result(true);
    }
 
    /**
     * 删除练习题:只删除关系 (统一班级下,顺序随机 同步删除)
     * 
     * @param exerciceIds
     * @param reIds
     * @param groupId
     * @return
     */
    @SuppressWarnings("unchecked")
    public Result deleteExerciseItems(String[] exerciceIds, String[] reIds, String groupId) {
        ExerciseGroup group = this.read(ExerciseGroup.class, groupId);
 
        // 1.更新组练习数量值 总量减去本次删除个数
        group.setAllCount(group.getAllCount().subtract(new BigInteger(String.valueOf(exerciceIds.length))));
        TraceUtils.setUpdateTrace(group);
        this.save(group);
 
        // 2.删除练习组关联表数据
        deleteExerciseGroupRe(reIds);
 
        // 3.重新排序此组的字段
        updateExerciseItemNewNo(groupId);
        
        //清除缓存
        redisTemplate.delete(groupId);
        return new Result(true);
    }
 
    /**
     * 重新排序
     * 
     * @param groupId
     * @return
     */
    private Result updateExerciseItemNewNo(String groupId) {
        // 升序排序
        String hql = "from ExerciseGroupItemRe re " + "where re.exerciseGroupId=? " + "and re.deleteFlag is false " + "order by re.itemOrder asc ";
 
        List<ExerciseGroupItemRe> lstRe = this.find(hql, CollectionUtils.newList(groupId), ExerciseGroupItemRe.class);
 
        if (lstRe.isEmpty()) {
            return null;
        }
 
        // 重新排序
        for (int i = 0; i < lstRe.size(); i++) {
            lstRe.get(i).setItemOrder(i + 1);
        }
 
        this.saveOrUpdateAll(lstRe);
 
        return new Result(true);
    }
 
    /**
     * 根据groupId 和 itemId 读取 ExerciseGroupItemRe
     * 
     * @param groupId
     * @param itemId
     * @return
     */
    /*
     * private ExerciseGroupItemRe readItemRe(String groupId,String itemId){
     * 
     * String hql = "from ExerciseGroupItemRe where exerciseGroupId = ? and exerciseItemId = ? "; ExerciseGroupItemRe itemRe = this.findUnique(hql, CollectionUtils.newList( groupId,itemId), ExerciseGroupItemRe.class);
     * 
     * return itemRe; }
     */
 
    /**
     * 查询最近的记录
     * 
     * @param hql
     * @param page
     * @param args
     * @return
     */
    /*
     * (non-Javadoc)
     * 
     * @see com.iqtogether.qxueyou.exercise.service.IExerciseService#importItems(java.lang.String, java.lang.String)
     */
    @Override
    public Result doImportItems(String groupId, File file) {
 
        List<ExerciseItem> items = null;
 
        try {
            items = parseFile(file);
        } catch (Exception e) {
            log.error(e, e);
            return new Result(false, "读取文档失败");
        }
 
        insertItems(groupId, items);
 
        // 4.20150618:配合前台app,所有修改同时修改group表最后修改时间
        List<ExerciseGroup> result = initExerciseGroup(groupId);
        updateGroupUpdateTimeByList(result);
        FileUtils.deleteQuietly(file.getParentFile());
        return new Result(true, "已导入" + items.size() + "道习题");
    }
 
    /**
     * 插入习题
     * 
     * @param items
     */
    private void insertItems(String groupId, List<ExerciseItem> items) {
 
        int i = 0;
 
        // 获取一个习题需要跟新的关系条数
        List<ExerciseGroup> result = initExerciseGroup(groupId);
 
        ExerciseGroup group = this.read(ExerciseGroup.class, groupId);
 
        // 得到当前组题目的最大题号
        int maxGroupItemOrder = queryExerciseGroupItemNo(groupId);
 
        /*String hql = " from ExerciseGroup where originExerciseId = ?  and deleteFlag is false and groupId != ?";
        List<ExerciseGroup> lstGroup = find(hql, CollectionUtils.newList(group.getOriginExerciseId(), groupId), ExerciseGroup.class);*/
 
        for (ExerciseItem item : items) {
 
            TraceUtils.setCreateTrace(item);
            item.setDeleteFlag(false);
            // 1. 习题
            handlerExerciseItem(group, item);
            save(item);
 
            // 2. 保存习题组-习题关系(练习和非练习)
            List<ExerciseGroupItemRe> groupRes = initExerciseGroupItemRe(result, item.getExerciseId(), item.getItemNo() == null ? i++ : item.getItemNo(), ++maxGroupItemOrder );
            saveOrUpdateAll(groupRes);
 
            if(StringUtils.isEmpty(group.getClassId())){
                // 同步习题
                String hql = " from ExerciseGroup where originExerciseId = ?  and deleteFlag is false and groupId != ?";
                List<ExerciseGroup> lstGroup = find(hql, CollectionUtils.newList(group.getOriginExerciseId(), groupId), ExerciseGroup.class);
                List<ExerciseItem> lstItems = find("from ExerciseItem where exerciseId = ?", CollectionUtils.newList(item.getExerciseId()), ExerciseItem.class);
                for (ExerciseGroup exerciseGroup : lstGroup) {
                    exerciseGroup.setAllCount(group.getAllCount());
                    TraceUtils.setUpdateTrace(exerciseGroup);
                    this.saveExerciseGroup(exerciseGroup);
                    try {
                        this.doCopyExerciseItem(exerciseGroup.getGroupId(), groupId, lstItems, 2);
                    } catch (IllegalAccessException | InstantiationException | InvocationTargetException
                            | NoSuchMethodException e) {
                        log.error("新增练习同步到班级错误", e);
                    }
                }
            }
            // 3. 保存习题解析
            if (item.getAnalisis() != null) {
                saveAnalysis(item);
            }
 
            // 4. 保存习题选项
            for (ExerciseItemOption option : item.getOptions()) {
                TraceUtils.setCreateTrace(option);
                option.setDeleteFlag(false);
                option.setExerciseItemId(item.getExerciseId());
                save(option);
            }
        }
 
    }
 
    /**
     * 保存习题解析
     * 
     * @param item
     */
    private void saveAnalysis(ExerciseItem item) {
        ExerciseItemAnalisi analysis = item.getAnalisis();
        if(StringUtils.isEmpty(analysis.getExerciseAnalisisId())){
            TraceUtils.setCreateTrace(analysis);
            analysis.setDeleteFlag(false);
            analysis.setExerciseItemId(item.getExerciseId());
            save(analysis);
        }else{
            TraceUtils.setUpdateTrace(analysis);
            this.save(analysis);
        }
    }
 
    /**
     * 解析word
     * 
     * @param groupId
     *            习题组id
     * @param file
     *            word文件绝对路径
     * @return
     * @throws RuntimeException
     */
    private List<ExerciseItem> parseFile(File file) throws Exception {
 
        Handler handler = new Handler();
 
        // from office to txt,docx:自带序号无法解析出来,doc可以
 
        String txtFilePath = transformDocToTxt(file);
 
        FileReader reader = null;
        BufferedReader br = null;
        try {
            reader = new FileReader(txtFilePath);
            br = new BufferedReader(reader);
 
            String currLine = "";
            while ((currLine = br.readLine()) != null) {
                handler.parse(currLine);
            }
        } catch (Exception e) {
            throw new Exception("读取文档失败", e);
        }  finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(reader);
        }
 
        Doc doc = handler.result();
        return doc.convertExerciseItems();
    }
 
    /**
     * 从office转换到txt:2007转换:自带序号格式会丢失;2003会解析出来
     * 
     * @param file
     *            office文档
     * @return
     */
    private String transformDocToTxt(File file) {
        FileInputStream fis = null;
        FileWriter writer = null;
        String strText = "";
 
        try {
            String fileExtention = fileExtension(file.getName());
            fis = new FileInputStream(file.getAbsolutePath());
 
            if ("doc".equals(fileExtention)) {
                WordExtractor extractor = new WordExtractor(fis);
                // 获取Word文件中的文本+自带序号
                strText = extractor.getText();
                extractor.close();
            } else if ("docx".equals(fileExtention)) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(file.getAbsolutePath());
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                // 只能获取Word文件中的文本,不能取到office序号
                strText = extractor.getText();
                extractor.close();
            } else {
                throw new RuntimeException("文件格式错误, 请上传word文档(.doc及.docx)格式", null);
            }
 
            // 将得到的文本全角转半角
            strText = formatFullToHalf(strText);
 
            // 解决空格保存为txt的时候,乱码为?
            byte bytes[] = { (byte) 0xC2, (byte) 0xA0 };
            String UTFSpace = new String(bytes, "UTF-8");
            strText = strText.replaceAll(UTFSpace, " ");
 
            File txtFile = new File(file.getParentFile().getAbsolutePath() + "/" + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".txt");
            writer = new FileWriter(txtFile, true);
            writer.write(strText);
 
            return txtFile.getAbsolutePath();
 
        } catch (FileNotFoundException e) {
            throw new RuntimeException("office文档未找到", e);
        } catch (IOException e) {
            throw new RuntimeException("office文档读取失败", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(writer);
            IOUtils.closeQuietly(fis);
        }
    }
 
    /**
     * 全角转半角
     * 
     * @param oriText
     * @return
     */
    private String formatFullToHalf(String oriText) {
        if (null == oriText || oriText.length() <= 0) {
            return "";
        }
 
        char[] charArray = oriText.toCharArray();
        // 对全角字符转换的char数组遍历
        for (int i = 0; i < charArray.length; ++i) {
            int charIntValue = (int) charArray[i];
 
            // 如果符合转换关系,将对应下标之间减掉偏移量65248;如果是空格的话,直接做转换
            if (charIntValue >= 65281 && charIntValue <= 65374) {
                charArray[i] = (char) (charIntValue - 65248);
            } else if (charIntValue == 12288) {
                charArray[i] = (char) 32;
            } else if (charIntValue == 58033) {
                // 空格
                charArray[i] = (char) 32;
            } else if (charIntValue == 65380) {
                // 顿号
                charArray[i] = (char) 12289;
            } else if (charIntValue == 65377) {
                // 句号
                charArray[i] = (char) 12290;
            }
        }
        return new String(charArray);
 
    }
 
    /**
     * 解析文件后缀
     * 
     * @param filename
     * @return
     */
    private String fileExtension(String filename) {
 
        return filename.substring(filename.lastIndexOf('.') + 1, filename.length());
    }
 
    /*
     * (non-Javadoc)
     * 
     * @see com.iqtogether.qxueyou.exercise.service.IExerciseService#updateExerciseItem(com.iqtogether.qxueyou.exercise.model.ExerciseItem, java.util.List)
     */
    @Override
    public Result updateExerciseItem(ExerciseItem item, List<ExerciseItemOption> lstOptions, String analysis) {
        //先删除所有的option,然后恢复已有的option
        this.bulkUpdate("update ExerciseItemOption  set deleteFlag = true where exerciseItemId=?", new String[]{item.getExerciseId()});
        // 保存Option
        String answer = "";
        if(lstOptions!=null){
            for (ExerciseItemOption option : lstOptions) {
                if(option.getChecked()){
                    if(item.getType()==ExerciseItem.TYPE_TRUE_OR_FALSE){
                        answer = answer.concat(option.getContent()).concat(",");
                    }else{
                        answer = answer.concat(option.getOptionOrder()).concat(",");
                    }
                }
                option.setExerciseItemId(item.getExerciseId());
                
                if(StringUtils.isNotEmpty(option.getOptionId())){
                    option.setDeleteFlag(false);
                    TraceUtils.setCreateTrace(option);
                }else{
                    TraceUtils.setCreateTrace(option);
                }
                save(option);
            }
        }
        
        
        // 保存item
        if(StringUtils.isNotBlank(answer)){
            item.setAnswer(answer.substring(0,answer.length()-1));
        }
        TraceUtils.setCreateTrace(item);
        save(item);
 
        // 保存解析
        updateItemAnalysis(item, analysis);
 
        // 配合前台app,所有修改同时修改group表最后修改时间
//        updateGroupUpdateTimeByList(initUpdateExerciseGroup(item.getExerciseId()));
        
        //保存题目分数
        List<ExerciseItemScore>  lstExerciseItemScore = item.getScores();
        if(lstExerciseItemScore!=null && lstExerciseItemScore.size()>0){
            for (ExerciseItemScore score : lstExerciseItemScore) {
                TraceUtils.setCreateTrace(score);
                score.setGroupId(item.getExerciseGroupId());
                save(score);
            }
        }
        return new Result(true, item.getExerciseId());
    }
 
    /*
     * 评价模块修改题目
     */
    @Override
    public ResultJson updateExerciseItem4Evaluate(ExerciseItem item, 
            List<ExerciseItemOption> lstOptions, String analysis) {
        
        TraceUtils.setUpdateTrace(item);
        
        
/*        // 先移除全部习题
        QExerciseItemOption qOption = QExerciseItemOption.exerciseItemOption;
        this.getQueryFactory()
        .update(qOption)
        .set(qOption.deleteFlag, true)
        .where(qOption.exerciseItemId.eq(item.getExerciseId()))
        .execute();
        
        // 移除全部分数
        QExerciseItemScore qScore = QExerciseItemScore.exerciseItemScore;
        this.getQueryFactory()
        .update(qScore)
        .set(qScore.deleteFlag, true)
        .where(qScore.exerciseItemId.eq(item.getExerciseId()))
        .execute();*/
        
        // 先移除全部习题
        String hql = "update ExerciseItemOption set DELETE_FLAG = 1 where EXERCISE_ITEM_ID = ?";
        super.bulkUpdateInLoop(hql, new String[] { item.getExerciseId() });
        // 移除全部分数
        String hql2 = "update ExerciseItemScore set DELETE_FLAG = 1 where EXERCISE_ITEM_ID = ?";
        super.bulkUpdateInLoop(hql2, new String[] { item.getExerciseId() });
        
        // 1.保存item
        this.save(item);
        if(lstOptions != null && lstOptions.size() > 0) {
            TraceUtils.setCreateTrace(lstOptions);
            for (int i = 0; i < lstOptions.size(); i++) {
                ExerciseItemOption option = lstOptions.get(i);
                option.setExerciseItemId(item.getExerciseId());
                if (StringUtils.isNotBlank(option.getOptionId()) && option.getOptionId().startsWith("#")) {
                    option.setOptionId(null);
                }
                option.setOptionOrder(letter[i]);
                save(option);
                
                ExerciseItemScore objExerciseItemScore = new ExerciseItemScore();
                TraceUtils.setCreateTrace(objExerciseItemScore);
                objExerciseItemScore.setAttribute1(option.getOptionId());
                objExerciseItemScore.setExerciseItemId(item.getExerciseId());
                objExerciseItemScore.setExerciseItemAnswer(letter[i]);
                objExerciseItemScore.setScore(String.valueOf(option.getScore()));
                objExerciseItemScore.setExerciseItemScoreId(option.getExerciseItemScoreId());
                save(objExerciseItemScore);
            }
        }
        
        // 4. 更新习题解析
        QExerciseItemAnalisi analysisVO = QExerciseItemAnalisi.exerciseItemAnalisi;
        this.getQueryFactory()
        .update(analysisVO)
        .set(analysisVO.analysis, analysis)
        .set(analysisVO.updateTime, new Date(System.currentTimeMillis()))
        .where(analysisVO.exerciseItemId.eq(item.getExerciseId()))
        .execute();
        
        return new ResultJson(true);
    }
 
    /**
     * 更新解析
     * 
     * @param item
     * @param analysis
     */
    private void updateItemAnalysis(ExerciseItem item, String analysis) {
        if (item.getAnalisis() == null) {
            ExerciseItemAnalisi analysisVO = new ExerciseItemAnalisi();
 
            TraceUtils.setCreateTrace(analysisVO);
            analysisVO.setDeleteFlag(false);
 
            analysisVO.setAnalysis(analysis);
            analysisVO.setAccuracy(BigDecimal.ZERO);
            analysisVO.setSubmitCorrectNumber(BigInteger.ZERO);
            analysisVO.setSubmitNumber(BigInteger.ZERO);
 
            item.setAnalisis(analysisVO);
 
            saveAnalysis(item);
        } else {
            ExerciseItemAnalisi analysisVO = item.getAnalisis();
            TraceUtils.setCreateTrace(analysisVO);
            analysisVO.setAnalysis(analysis);
 
            save(analysisVO);
        }
    }
 
    /**
     * 组装ExerciseGroup的list,传入一个groupid,得到同时需要修改的一个或者多个group对象
     * 
     * @param groupId
     *            主键
     * @return
     */
    @Override
    public List<ExerciseGroup> initExerciseGroup(String groupId) {
        // 0.获取groupID对应的type,如果是习题(顺机序、随和章节,需要按不同情况同时更新)
        // 1.如果是章节练习,需要同步修改顺序随机练习
        // 2.如果是顺序,需同步修改随机;如果是随机练习亦然
        ExerciseGroup group = read(ExerciseGroup.class, groupId);
        List<ExerciseGroup> result = new ArrayList<ExerciseGroup>();
        short sType = 0;
        if (group != null) {
            sType = group.getType();
            String hsql = "";
            if (sType == ExerciseGroup.TYPE_CHAPTER_ITEM || sType == ExerciseGroup.TYPE_EXERCISE_RANDOM || sType == ExerciseGroup.TYPE_EXERCISE_SEQUENCE) {
                hsql = "from ExerciseGroup where classId = ? and (type = ? or type = ?) and deleteFlag  is false ";
                result = find(hsql, CollectionUtils.newList(ClientUtils.getClassId(), ExerciseGroup.TYPE_EXERCISE_SEQUENCE, ExerciseGroup.TYPE_EXERCISE_RANDOM), ExerciseGroup.class);
            }
            if (sType != ExerciseGroup.TYPE_EXERCISE_SEQUENCE && sType != ExerciseGroup.TYPE_EXERCISE_RANDOM) {
                result.add(group);
            }
        }
        return result;
    }
 
    /**
     * 组装ExerciseGroup的list,传入一个groupid,得到同时需要修改的一个或者多个group对象
     * 
     * @param groupId
     *            主键
     * @return
     */
    public List<ExerciseGroup> initUpdateExerciseGroup(String exerciseId) {
        // 修改关联的exerciseId,deleteflag is false(暂时全部处理)
        List<ExerciseGroup> lstGroup = new ArrayList<ExerciseGroup>();
 
        String hql = "select e.exerciseGroupId from ExerciseGroupItemRe e where deleteFlag is false and e.exerciseItemId = ? ";
        List<Object> groupId = find(hql, CollectionUtils.newList(exerciseId), Object.class);
 
        if (null != groupId && !groupId.isEmpty()) {
            String hql0 = " from ExerciseGroup e where e.deleteFlag is false and e.groupId in  (  ";
            for (int i = 0; i < groupId.size(); i++) {
                if (i == groupId.size() - 1) {
                    hql0 = hql0.concat(" ? ) ");
                } else {
                    hql0 = hql0.concat(" ?, ");
                }
            }
            lstGroup = find(hql0, groupId, ExerciseGroup.class);
        }
 
        return lstGroup;
    }
 
    /**
     * 批量删除ExerciseGroup,删除逻辑:如果是练习,顺序和随机练习时同步删除的(此处代码)
     * 
     * @param groupId
     *            主键,多个id时以","分隔
     * @return
     */
    public Result deleteExerciseGroup(String groupId) {
 
        // 逻辑删除,只需要修改exercise_group、exercise_item的删除标识即可
        if (StringUtils.isNotBlank(groupId)) {
            // 需要删除的练习组
            Object[] arrGroupId = groupId.split(",");
            // 存储顺序练习或者随机练习
            List<ExerciseGroup> lstResults = initDeleteExerciseGroup(arrGroupId);
 
            // 需要删除的练习类型下的练习题
            //List<ExerciseItem> lstItem = initDeleteExerciseItem(lstResults);
 
            // 删除习题组,修改习题组最后修改时间
            if (lstResults != null) {
                for (ExerciseGroup group : lstResults) {
                    group.setDeleteFlag(true);
                    
                    TraceUtils.setUpdateTrace(group);
                    this.saveExerciseGroup(group);
                    // group.setUpdateTime(new Date(System.currentTimeMillis()));
                }
            }
 
            /*// 删除习题
            if (lstItem != null) {
                for (ExerciseItem item : lstItem) {
                    item.setDeleteFlag(true);
                }
                saveOrUpdateAll(lstItem);
            }*/
            // 20150618:配合前台app,所有修改同时修改group表最后修改时间
            //updateGroupUpdateTimeByList(lstResults);
        }
        return new Result(true);
    }
 
    /**
     * 组装练习组
     * 
     * @param name
     *            练习名称
     * @param type
     *            练习组类型
     * @param lessonId
     *            课程
     * @param chapterId
     *            章节
     * @return
     */
    private List<ExerciseGroup> initExerciseGroupList(String name, short type, String lessonId, String chapterId, int iCount) {
        List<ExerciseGroup> lstExerciseGroup = new ArrayList<ExerciseGroup>();
        List<Short> lstType = new ArrayList<Short>();
 
        // iCount:0、 新增三种(选择了章节),增加两种:没有选择章节;1,新增两种(顺序随机),2,新增一种(章节),3的话,不增加
        if (type == ExerciseGroup.TYPE_EXERCISE_SEQUENCE) {
            if (iCount == 0) {
                lstType.add(type);
                lstType.add(ExerciseGroup.TYPE_EXERCISE_RANDOM);
                if (StringUtils.isNotBlank(lessonId) && StringUtils.isNotBlank(chapterId)) {
                    lstType.add(ExerciseGroup.TYPE_CHAPTER_ITEM);
                }
            } else if (iCount == 1) {
                lstType.add(type);
                lstType.add(ExerciseGroup.TYPE_EXERCISE_RANDOM);
            } else if (iCount == 2) {
                lstType.add(ExerciseGroup.TYPE_CHAPTER_ITEM);
            } else if (iCount == 3 && StringUtils.isNotBlank(chapterId)) {// 等于3,章节练习,顺序练习,随机练习都有,增加章节练习
                lstType.add(ExerciseGroup.TYPE_CHAPTER_ITEM);
            }
        } else {
            lstType.add(type);
        }
 
        for (short iType : lstType) {
            lstExerciseGroup.add(initExerciseGroup(name, iType, lessonId, chapterId));
        }
        return lstExerciseGroup;
    }
 
    /**
     * 组装练习
     * 
     * @param name
     *            练习名称
     * @param type
     *            练习类型
     * @param lessonId
     *            课程
     * @param chapterId
     *            章节
     * @return
     */
    private ExerciseGroup initExerciseGroup(String name, short type, String lessonId, String chapterId) {
        // 构建实体
        ExerciseGroup objExerciseGroup = new ExerciseGroup();
 
        TraceUtils.setCreateTrace(objExerciseGroup);
        objExerciseGroup.setDeleteFlag(false);
        objExerciseGroup.setAllCount(BigInteger.ZERO);
        objExerciseGroup.setSubjectId(lessonId);
        objExerciseGroup.setChapterId(chapterId);
        if (ExerciseGroup.TYPE_EXERCISE_RANDOM == type) {
            objExerciseGroup.setName("随机练习");
        } else if (ExerciseGroup.TYPE_EXERCISE_SEQUENCE == type) {
            objExerciseGroup.setName("顺序练习");
        } else {
            objExerciseGroup.setName(name);
        }
 
        objExerciseGroup.setType(type);
        objExerciseGroup.setClassId(ClientUtils.getClassId());
        objExerciseGroup.setOrgId(ClientUtils.getOrgId());
        objExerciseGroup.setCollegeCourseId(ClientUtils.getCourseId());
        // 章节练习需要存储
        if (type == ExerciseGroup.TYPE_CHAPTER_ITEM) {
            // 章节练习存放lessonId
            //objExerciseGroup.setAttribute1(lessonId);
            // 章节练习存放chapterID
            objExerciseGroup.setAttribute2(chapterId);
        }
        return objExerciseGroup;
    }
 
    /**
     * 组装关联信息
     * 
     * @param lstGroup
     *            练习组
     * @param itemId
     *            练习题id
     * @param itemOrder
     *            练习题序号
     * @return
     */
    private List<ExerciseGroupItemRe> initExerciseGroupItemRe(List<ExerciseGroup> lstGroup, String itemId, int docOrder,int maxGroupItemOrder) {
 
        List<ExerciseGroupItemRe> lstExerciseGroupItemRe = new ArrayList<ExerciseGroupItemRe>();
 
        for (ExerciseGroup group : lstGroup) {
            ExerciseGroupItemRe re = new ExerciseGroupItemRe();
            re.setExerciseGroupId(group.getGroupId());
            re.setExerciseItemId(itemId);
            re.setItemOrder(maxGroupItemOrder);
            re.setDeleteFlag(false);
            if (docOrder > -1) {
                re.setDocOrder(docOrder);
            }
            lstExerciseGroupItemRe.add(re);
        }
        return lstExerciseGroupItemRe;
    }
 
    /**
     * 查询当前组的最大题号
     * 
     * @param groupId
     * @return
     */
    private int queryExerciseGroupItemNo(String groupId) {
 
        String hql = "select max(itemOrder) from ExerciseGroupItemRe t where deleteFlag is false and  exerciseGroupId=?";
 
        Integer itemOrder = this.findUnique(hql, CollectionUtils.newList(groupId), Integer.class);
 
        if (itemOrder == null) {
            return 0;
        }
 
        return itemOrder;
    }
 
    /**
     * 组装需要删除的练习组
     * 
     * @param lstResult
     *            存储非顺序 练习非随机练习
     * @param lstResults
     *            存储顺序练习或者随机练习
     * @param arrGroupId
     *            groupid的数组
     */
    private List<ExerciseGroup> initDeleteExerciseGroup(Object[] arrGroupId) {
        List<ExerciseGroup> lstResults = new ArrayList<ExerciseGroup>();
        List<ExerciseGroup> lstResult = new ArrayList<ExerciseGroup>();
        String hsql = " from ExerciseGroup where groupId in ( ";
        for (int i = 0; i < arrGroupId.length - 1; i++) {
            hsql = hsql.concat("? , ");
        }
        hsql =  hsql.concat("? ) ");
        List<ExerciseGroup> result = find(hsql, CollectionUtils.newList(arrGroupId), ExerciseGroup.class);
        // 一个班级只有一个顺序练习和一个随机练习
        int iNumber = 0;
        for (ExerciseGroup group : result) {
            if (group.getType() == ExerciseGroup.TYPE_EXERCISE_SEQUENCE || group.getType() == ExerciseGroup.TYPE_EXERCISE_RANDOM) {
                iNumber++;
                lstResults.add(group);
            } else {
                lstResult.add(group);
            }
        }
        // 一个班级只选择了顺序或者只选择了随机,两个类型都需要删除
        if (iNumber == 1) {
            hsql = "from ExerciseGroup where type in (?,?) and classId = ? and deleteFlag is false ";
            lstResults = find(hsql, CollectionUtils.newList(ExerciseGroup.TYPE_EXERCISE_SEQUENCE, ExerciseGroup.TYPE_EXERCISE_RANDOM, lstResults.get(0).getClassId()), ExerciseGroup.class);
        }
        lstResults.addAll(lstResult);
 
        return lstResults;
    }
 
    /**
     * 获取需要删除的练习题(删除习题组时调用)
     * 
     * @param lstResults
     *            需要删除的练习组
     *//*
    private List<ExerciseItem> initDeleteExerciseItem(List<ExerciseGroup> lstResults) {
        String hsql = "from ExerciseItem where exerciseId in ( select exerciseItemId from ExerciseGroupItemRe " + "  where deleteFlag is false and  exerciseGroupId in ( ";
        List<Object> arrGroupId = new ArrayList<Object>();
        for (int i = 0; i < lstResults.size(); i++) {
            if (i != lstResults.size() - 1) {
                hsql = hsql.concat("? , ");
            }
            arrGroupId.add(lstResults.get(i).getGroupId());
        }
 
        // 需要删除的练习题(为练习类型时)
        hsql = hsql.concat("? )  group by exerciseItemId having count(1) = 3 )");
 
        // 这个SQL特别慢
        List<ExerciseItem> lstItem = find(hsql, arrGroupId, ExerciseItem.class);
        List<ExerciseItem> lstItems = new ArrayList<ExerciseItem>();
 
        // 剔除顺序,随机、章节练习
        List<Object> lstParams = new ArrayList<Object>();
        for (ExerciseGroup group : lstResults) {
            if (group.getType() != ExerciseGroup.TYPE_EXERCISE_SEQUENCE && group.getType() != ExerciseGroup.TYPE_CHAPTER_ITEM && group.getType() != ExerciseGroup.TYPE_EXERCISE_RANDOM) {
                lstParams.add(group.getGroupId());
            }
        }
        if (!lstParams.isEmpty()) {
            hsql = "from ExerciseItem where exerciseId in ( select exerciseItemId from ExerciseGroupItemRe where deleteFlag is false and exerciseGroupId in ( ";
            for (int i = 0; i < lstParams.size() - 1; i++) {
                hsql = hsql.concat("? , ");
            }
            hsql =hsql.concat( "? )  )");
            lstItems = find(hsql, lstParams, ExerciseItem.class);
        }
        // 需要删除的习题
        if (lstItem != null) {
            lstItem.addAll(lstItems);
        }
        return lstItem;
    }*/
 
    /**
     * :后台 插入评估模板时调用
     * 
     * @param name
     * @param type
     * @return
     */
    public ExerciseGroup insertExerciseGroup(String name, short type) {
 
        ExerciseGroup obj = new ExerciseGroup();
        TraceUtils.setCreateTrace(obj);
        obj.setName(name);
        obj.setType(type);
        obj.setClassId(ClientUtils.getClassId());
        obj.setOrgId(ClientUtils.getOrgId());
        save(obj);
 
        // 保存
        return obj;
    }
 
    /**
     * 查询练习列表,还需查询联系下面习题个数
     * 
     * @param hql
     * @param args
     * @return
     */
    public List<ExerciseGroup> queryExerciceGroupList(String hql, List<Object> args) {
        return exerDAO.queryExerciceGroupList(hql, args);
    }
 
    /**
     * 所有练习修改操作需要同时修改group的updateTime
     * 
     * @param lstGroup
     */
    private void updateGroupUpdateTimeByList(List<ExerciseGroup> lstGroup) {
        if (null != lstGroup && !lstGroup.isEmpty()) {
            for (ExerciseGroup obj : lstGroup) {
                int iExerciseCount = this.findCount("select count(1) from ExerciseGroupItemRe where deleteFlag is false and exerciseGroupId = ?",
                        CollectionUtils.newList(obj.getGroupId()));
                obj.setAllCount(BigInteger.valueOf(iExerciseCount));
                obj.setUpdateTime(new Date());
                this.saveExerciseGroup(obj);
            }
            //saveOrUpdateAll(lstGroup);
        }
    }
 
    /**
     * 后台:批量删除ExerciseGroup
     * 
     * @param groupId
     *            主键,多个id时以","分隔
     * @param type
     *            多个type时以","分隔
     * @return
     */
    public Result deleteExerciseGroup(String groupId, String type, String deleteType,Integer delAll, String orgIds[], String classIds[]) {
        if (StringUtils.isBlank(groupId) || StringUtils.isBlank(type)) {
            return new Result(true);
        }
        String[] groupIds = groupId.split(",");
        String[] types = type.split(",");
        if (groupIds.length != types.length) {
            return new Result(false);
        }
        if ("org".equals(deleteType)) {
            //管理员删除练习
            deleteOrgGroup(groupIds,delAll,orgIds,classIds);
            return new Result(true);
        }
        // 删除逻辑:练习和其他分开处理(SQL执行简单)
        // 删除练习:随机和顺序是一致的;如果只删除随机或者顺序,只删除章节,则只删除习题组;如果只删除章节:同样只删除组
        // 删除时:顺序或者随机+章节:删除组+章节对应的习题
        boolean randomFlag = false;
        boolean chapterFlag = false;
 
        if (type.indexOf(String.valueOf(ExerciseGroup.TYPE_EXERCISE_RANDOM)) != -1
                || type.indexOf(String.valueOf(ExerciseGroup.TYPE_EXERCISE_SEQUENCE)) != -1) {
            randomFlag = true;
        }
        if (type.indexOf(String.valueOf(ExerciseGroup.TYPE_CHAPTER_ITEM)) != -1) {
            chapterFlag = true;
        }
 
        //  拆除子方法
        Result  result = deleteChildExerciseGroup(groupIds, types, randomFlag, chapterFlag);
        
        if(!result.isSuccess()){
            return result;    
        }
        
        return new Result(true);
 
    }
    
    /**
     * 拆除子方法
     * @param groupIds
     * @param types
     * @param randomFlag
     * @param chapterFlag
     * @return
     */
    private Result deleteChildExerciseGroup(String[] groupIds, String[] types,
            boolean randomFlag, boolean chapterFlag) {
        // 1. 无练习
        if (!randomFlag && !chapterFlag) {
            return deleteExercise(groupIds, groupIds);
        }
        // 2. 有随机有章节
        if (randomFlag && chapterFlag) {
            return deleteExerciseAll(groupIds);
        }
        // 3.1. 随机、章节只有一种,删除组:第一种情况:保证顺序随机一致;第二种:删除章节
        if (randomFlag) {
            return deleteExerciseSequence(groupIds, types);
        }
        return deleteExerciseChapter(groupIds, types);
    }
    
    private void deleteOrgGroup(String groupIds[],Integer delAll, String orgIds[], String classIds[]){
        for (String string : groupIds) {
            if ((orgIds != null && orgIds.length != 0)  || (classIds != null && classIds.length != 0)) {
                //删除要回撤的练习
                deleteAppoint(string,orgIds,classIds);
            }else{
                String hql = " from ExerciseReCourse where groupId = ? and deleteFlag is false and orgId = ?";
                ExerciseReCourse erc = findUnique(hql, CollectionUtils.newList(string, ClientUtils.getOrgId()), ExerciseReCourse.class);
                if (erc != null) {
                    erc.setDeleteFlag(true);
                    TraceUtils.setUpdateTrace(erc);
                    save(erc);
                    
                    this.courseWareService.deleteOrgCourseware(erc.getGroupId(), erc.getOrgId());
                }
                /*ExerciseGroup group = this.read(ExerciseGroup.class, string);
                if(group != null){
                    TraceUtils.setUpdateTrace(group);
                    group.setDeleteFlag(true);
                    this.saveExerciseGroup(group);
                }*/
                if(delAll==1){
                    //删除下级
                    deleteSub(string,ClientUtils.getOrgId());
                }
            }
            
        }
    }
    
    
    @SuppressWarnings("unchecked")
    private void deleteSub(String groupId,String currOrgId){
        // 机构层级视频是没有重新new ,查询出机构下级ID再删关联表
                String sql = " select oa.organization_id from organization as oa,organization ob " +
                        " where " +
                        " ob.ORGANIZATION_ID = ? " +
                        " and  " +
                        " oa.org_code like  CONCAT(ob.org_code,'%' ) " +
                        " and oa.delete_flag is false and ob.delete_flag is false "+
                        " order by oa.level,oa.org_code asc " ;
                
            List<String> orgIds = this.findBySql(sql, CollectionUtils.newList(currOrgId));
            
            String hql = " from ExerciseReCourse where groupId = :groupId and deleteFlag is false and orgId in (:orgIds)";
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("groupId", groupId);
            map.put("orgIds", orgIds.toArray());
            List<ExerciseReCourse> groupCourses = findByComplexHql(hql, map, ExerciseReCourse.class);
            for (ExerciseReCourse groupCourse : groupCourses) {
                groupCourse.setDeleteFlag(true);
                TraceUtils.setUpdateTrace(groupCourse);
                this.save(groupCourse);
            }
            
            // 班主任层面视频指定过后都是new 出来的,通过originVideoId 可以查出所有指定过去的视频
            hql = "select classId from ClsClass where orgId in (:orgIds) and deleteFlag is false";
            map = new HashMap<String, Object>();
            map.put("orgIds", orgIds.toArray());
            List<String> clsIds = findByComplexHql(hql, map, String.class);
            if(!clsIds.isEmpty()){
                hql = " from ExerciseGroup where originExerciseId = :groupId and deleteFlag is false and groupId!=originExerciseId and classId in (:classIds)";
                map = new HashMap<String, Object>();
                map.put("groupId", groupId);
                map.put("classIds", clsIds.toArray());
                List<ExerciseGroup> lstExerciseGroup = findByComplexHql(hql, map, ExerciseGroup.class);
                for (ExerciseGroup group : lstExerciseGroup) {
                    group.setDeleteFlag(true);
                    TraceUtils.setUpdateTrace(group);
                    this.saveExerciseGroup(group);
                }
            }
    }
    
    private Result deleteAppoint(String groupId,String orgIds[],String classIds[]){
        Map<String, Object> args = new HashMap<String, Object>();
        // 删除需要回撤的机构视频
        if (orgIds.length != 0) {
            
            String hql = " from ExerciseReCourse where groupId = :groupId and deleteFlag is false and orgId in (:orgIds) and orgId != :currOrgId";
            args = new HashMap<String, Object>();
            args.put("groupId", groupId);
            args.put("orgIds", orgIds);
            args.put("currOrgId", ClientUtils.getOrgId());
            List<ExerciseReCourse> courses = findByComplexHql(hql, args, ExerciseReCourse.class);
            for (ExerciseReCourse exercise : courses) {
                TraceUtils.setUpdateTrace(exercise);
                exercise.setDeleteFlag(true);
                save(exercise);
                
                this.courseWareService.deleteOrgCourseware(exercise.getGroupId(), exercise.getOrgId());
            }
        }
 
        // 删除需要回撤的班主任视频
        if (classIds.length != 0) {
            args = new HashMap<String, Object>();
            args.put("groupId", groupId);
            args.put("classIds", classIds);
            String hql = " from ExerciseGroup where originExerciseId = :groupId and deleteFlag is false and classId in (:classIds)";
            List<ExerciseGroup> groups = findByComplexHql(hql, args, ExerciseGroup.class);
            for (ExerciseGroup group : groups) {
                TraceUtils.setUpdateTrace(group);
                group.setDeleteFlag(true);
                this.saveExerciseGroup(group);
            }
            
        }
        
        return new Result(true);
    }
 
    /**
     * 有顺序和章节练习时的删除逻辑
     * 
     * @param groupIds
     * @param types
     * @return
     */
    private Result deleteExerciseAll(String[] groupIds) {
        String hql = "select groupId from ExerciseGroup where deleteFlag is false and classId = ? and type in (?,?) ";
        List<String> exeGroupId = find(hql, CollectionUtils.newList(ClientUtils.getClassId(), ExerciseGroup.TYPE_EXERCISE_RANDOM, ExerciseGroup.TYPE_EXERCISE_SEQUENCE), String.class);
        // 组
        exeGroupId.addAll(Arrays.asList(groupIds));
 
        return deleteExercise((String[]) exeGroupId.toArray(new String[exeGroupId.size()]), groupIds);
    }
 
    /**
     * 只有順序或者随机时删除逻辑
     * 
     * @param groupIds
     * @param types
     * @return
     */
    private Result deleteExerciseSequence(String[] groupIds, String[] types) {
        String hql = "select groupId from ExerciseGroup where deleteFlag is false and classId = ? and type in (?,?) ";
        List<String> exeGroupId = find(hql, CollectionUtils.newList(ClientUtils.getClassId(), ExerciseGroup.TYPE_EXERCISE_RANDOM, ExerciseGroup.TYPE_EXERCISE_SEQUENCE), String.class);
        // 1.组
        exeGroupId.addAll(Arrays.asList(groupIds));
 
        // 2.删除题,不处理练习
        for (int i = 0; i < types.length; i++) {
            if (types[i] == String.valueOf(ExerciseGroup.TYPE_EXERCISE_RANDOM) || types[i] == String.valueOf(ExerciseGroup.TYPE_EXERCISE_SEQUENCE)) {
                groupIds[i] = "";
            }
        }
        return deleteExercise((String[]) exeGroupId.toArray(new String[exeGroupId.size()]), groupIds);
    }
 
    /**
     * 只有章节练习是的删除逻辑
     * 
     * @param groupIds
     * @param types
     * @return
     */
    private Result deleteExerciseChapter(String[] groupIds, String[] types) {
        // 1.组 groupIds
        // 2.删除题,不处理练习
        String[] groupItemIds = new String[groupIds.length];
        for (int i = 0; i < types.length; i++) {
            if (types[i] == String.valueOf(ExerciseGroup.TYPE_CHAPTER_ITEM)) {
                groupItemIds[i] = "";
            } else {
                groupItemIds[i] = groupIds[i];
            }
        }
        return deleteExercise(groupIds, groupItemIds);
    }
 
    /**
     * 后台:执行删除习题组操作
     * 
     * @param groupIds
     *            删除组的组id
     * @param groupItemIds
     *            需要删除题的组id
     * @return
     */
    private Result deleteExercise(String[] groupIds, String[] groupItemIds) {
        // 1.删除组
        bulkUpdateInLoop("update ExerciseGroup set deleteFlag = true where groupId = ? ", groupIds);
        // 1.删除课件
        bulkUpdateInLoop("update SchCourseware set deleteFlag = true where id = ? ", groupIds);
        
        // 2.删除题
        bulkUpdateInLoop("update ExerciseGroupItemRe set deleteFlag = true "
                + " where exerciseGroupId = ? and deleteFlag = false ", groupItemIds);
        
        return new Result(true);
    }
 
    /**
     * 发送练习系统通知
     * 
     * @param notice
     * @return
     * 
     *         private Result sendSysMsg(ExerciseGroup group){
     * 
     *         ONSMsg msg = new ONSMsg(onsProducer.getTopic());
     * 
     *         msg.put("msgType", "SYS_EXER_SAVE"); msg.put("groupId", group.getGroupId()); msg.put("classId", ClientUtils.getClassId());
     * 
     *         try {
     * 
     *         onsProducer.sendMsg(msg);
     * 
     *         return new Result(true);
     * 
     *         } catch (Exception e) { log.error("call DocdealMsgSendService fail.userId: " + group.getGroupId(), e); }
     * 
     *         return new Result(false); }
     */
 
    /**
     * 添加练习图片
     * 
     * @param imgPath
     * @param imgObjId
     * @param imgObjType
     * @return
     */
    public List<Map<String, Object>> doAddExerciseObjImg(String[] imgPath, String imgObjId, int imgObjType) {
 
        String hql = "from ExerciseObjectImg where deleteFlag is false and exerciseObjectId=? and objectType=? order by imgOrder desc";
        // 查询此练习是否已经存在记录
        List<ExerciseObjectImg> lstObjImg = this.find(hql, CollectionUtils.newList(imgObjId, imgObjType), ExerciseObjectImg.class);
 
        int imgOrder = 1;
        if (!lstObjImg.isEmpty()) {
            imgOrder = lstObjImg.get(0).getImgOrder() + 1;
        }
 
        List<ExerciseObjectImg> lstImg = new ArrayList<ExerciseObjectImg>(imgPath.length);
        ExerciseObjectImg img = new ExerciseObjectImg();
        img.setObjectType(imgObjType);
        img.setImgPath(imgPath[0]);
        img.setExerciseObjectId(imgObjId);
        img.setImgOrder(imgOrder);
        img.setDeleteFlag(false);
        TraceUtils.setCreateTrace(img);
        lstImg.add(img);
 
        for (int i = 1; i < imgPath.length; i++) {
            img.setImgPath(imgPath[i]);
            img.setImgOrder(imgOrder++);
            lstImg.add(img);
        }
 
        this.saveOrUpdateAll(lstImg);
 
        List<Map<String, Object>> lstResult = new ArrayList<Map<String, Object>>(lstImg.size());
        Map<String, Object> resultMap = null;
        for (ExerciseObjectImg obj : lstImg) {
            resultMap = new HashMap<String, Object>(2);
            resultMap.put("imgId", obj.getImgId());
            resultMap.put("imgPath", obj.getImgPath());
            lstResult.add(resultMap);
        }
        return lstResult;
    }
 
    /**
     * 删除图片
     */
    public Result dodelExerciseObjImg(String imgId) {
 
        ExerciseObjectImg img = this.read(ExerciseObjectImg.class, imgId);
        img.setDeleteFlag(true);
        TraceUtils.setUpdateTrace(img);
        this.save(img);
 
        return new Result(true);
    }
 
    /**
     * 导入习题:深度解析word文档
     * 
     * @param groupId
     *            习题组Id
     * @param file
     * @param uuid
     * @return
     */
    public Result doDeepAnalysisDoc(String groupId,String fullPath){
        
        return insertDeepAnalysis(fullPath,groupId);
        
    }
 
    /**
     * 新增深度解析记录
     * 
     * @param destPath
     *            文件路径
     * @param groupId
     *            习题组ID
     * @return
     */
    private Result insertDeepAnalysis(String destPath, String groupId) {
        ExerciseDeepAnalysis objDeepAna = new ExerciseDeepAnalysis();
        TraceUtils.setCreateTrace(objDeepAna);
        objDeepAna.setDocPath(destPath);
 
        objDeepAna.setUserId(ClientUtils.getUserId());
        objDeepAna.setUserAccount(ClientUtils.getUserAccount());
        objDeepAna.setOrgId(ClientUtils.getOrgId());
        objDeepAna.setOrgName(ClientUtils.getOrgName());
        objDeepAna.setClassId(ClientUtils.getClassId());
        objDeepAna.setClassName(ClientUtils.getClassName());
 
        String hql = " from OrgCharger o where o.deleteFlag  is false and o.userId = ?  ";
        OrgCharger charger = this.findUnique(hql, CollectionUtils.newList(ClientUtils.getUserId()), OrgCharger.class);
 
        objDeepAna.setChargerId(charger.getChargerId());
        objDeepAna.setChargerName(charger.getName());
 
        objDeepAna.setStatus(ExerciseDeepAnalysis.STATUS_TODO);
 
        objDeepAna.setExerciseGroupId(groupId);
        objDeepAna.setExerciseGroupName(this.read(ExerciseGroup.class, groupId).getName());
 
        objDeepAna.setSubmitTime(new Date(System.currentTimeMillis()));
 
        this.insert(objDeepAna);
 
        return new Result(true);
    }
 
    /**
     * 导入习题,将解析结果返回到前台
     * 
     * @param groupId
     *            习题组ID
     * @param file
     * @return
     */
    public ExerciseParseResult doParseItems(String groupId, String fullPath , String module ) {
        
        //取得当前上传文件类型
        String filePart[] = fullPath.split("\\.");
        String fileType = filePart[filePart.length -1];
        String uuid =  UUIDUtils.generateUUID();
        String filePath = ExerciseService.class.getClassLoader().getResource("../uploads").getPath().concat("exercise/"+ uuid + "/" + uuid + "."+fileType);
        File file = fileUploadService.doGetOssFile(fullPath, filePath, module,ClientUtils.getUserId());
        
        ExerciseParseResult objResult = null ;
        
        try {
            objResult = parseWordFile(file);
        } catch (Exception e) {
            log.error(e, e);
            if ("文件格式错误, 请上传word文档(.doc及.docx)格式".equals(e.getMessage())) {
                return new ExerciseParseResult(false, e.getMessage());
            }
            return new ExerciseParseResult(false, "读取文档失败");
        }
        
        //更新上传文件使用轨迹
        fileUploadService.updateUploadTrace(fullPath, module, SysFileUploadTrace.FILE_USE, groupId);
        
        objResult.setItemCount(objResult.getLstItems().size());
        objResult.setLstItems(null);
        objResult.setParseFlag(true);
 
        if( null != file ){
            fileUploadService.doDeleteTempOssFile(file.getParentFile(), module, ClientUtils.getUserId());
        }
        
        return objResult;
    }
 
    /**
     * 解析word
     * 
     * @param groupId
     *            习题组id
     * @param file
     *            word文件绝对路径
     * @return
     * @throws RuntimeException
     */
    private ExerciseParseResult parseWordFile(File file) throws Exception {
 
        ExerciseParseResult parseResult = new ExerciseParseResult();
 
        ArrayList<ExerciseImportResult> lstResult = new ArrayList<ExerciseImportResult>();
 
        Handler handler = new Handler();
 
        // from office to txt,docx:自带序号无法解析出来,doc可以
        String txtFilePath = transformDocToTxt(file);
 
        FileReader reader = null;
        BufferedReader br = null;
        try {
            reader = new FileReader(txtFilePath);
            br = new BufferedReader(reader);
 
            String currLine = "";
            ExerciseImportResult objResult;
            while ((currLine = br.readLine()) != null) {
 
                ExerciseParse objParser = handler.parse(currLine);
 
                int iResultType = objParser.getParseResult();
 
                objResult = new ExerciseImportResult();
                objResult.setLineText(objParser.getParseLine());
                objResult.setType(iResultType);
                if (Handler.HANDLER_RESULT_CONTINUE == iResultType) {
                    objResult.setLastParse(objParser.getParseType());
                }
                lstResult.add(objResult);
 
            }
        } catch (Exception e) {
            throw new Exception("读取文档失败", e);
        } finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(reader);
        }
 
        Doc doc = handler.result();
 
        parseResult.setLstItems(doc.convertExerciseItems());
        parseResult.setLstResult(lstResult);
 
        return parseResult;
    }
 
    /**
     * 导入习题 校验习题,将解析结果返回到前台
     * 
     * @param content
     *            习题文本内容
     * @return
     */
    public ExerciseParseResult validateExercise(String content) {
 
        ExerciseParseResult parseResult = parsePlainText(content);
        parseResult.setLstItems(null);
 
        return parseResult;
 
    }
 
    /**
     * 导入习题:将传回的文本内容解析出来
     * 
     * @param content
     *            习题文本内容
     * @return
     */
    private ExerciseParseResult parsePlainText(String content) {
 
        ExerciseParseResult parseResult = new ExerciseParseResult();
        Handler handler = new Handler();
        ArrayList<ExerciseImportResult> lstResult = new ArrayList<ExerciseImportResult>();
        List<ExerciseItem> items = null;
 
        String[] arrLine = content.split("\n");
 
        ExerciseImportResult objResult;
        for (String line : arrLine) {
            ExerciseParse objParser = handler.parse(line);
 
            int iResultType = objParser.getParseResult();
 
            objResult = new ExerciseImportResult();
            objResult.setLineText(objParser.getParseLine());
            objResult.setType(iResultType);
            if (Handler.HANDLER_RESULT_CONTINUE == iResultType) {
                objResult.setLastParse(objParser.getParseType());
            }
            lstResult.add(objResult);
        }
 
        Doc doc = handler.result();
 
        items = doc.convertExerciseItems();
 
        parseResult.setLstItems(items);
        parseResult.setLstResult(lstResult);
        parseResult.setItemCount(items.size());
        parseResult.setParseFlag(true);
 
        return parseResult;
    }
 
    /**
     * 导入习题模块 :导入习题,将解析结果返回到前台
     * 
     * @param content
     *            文本内容
     * @param groupId
     *            习题组ID
     * @return
     */
//    public ExerciseParseResult doImportExercise(String content, String groupId) {
//
//        ExerciseParseResult parseResult = parsePlainText(content);
//
//        List<ExerciseItem> lstItems = parseResult.getLstItems();
//
//        if (null == lstItems || lstItems.isEmpty()) {
//            return parseResult;
//        }
//
//        insertItems(groupId, lstItems);
//
//        // 修改习题组最后修改时间
//        List<ExerciseGroup> result = initExerciseGroup(groupId);
//        updateGroupUpdateTimeByList(result);
//
//        // 减少返回数据
//        parseResult.setLstItems(null);
//        ONSMsg msg = new ONSMsg(onsProducer.getTopic());
//        msg.put("msgType", "SYS_EXER_SAVE"); 
//        msg.put("groupId", groupId); 
//        msg.put("classId", ClientUtils.getClassId());
//        msg.put("actionType", "new");
//        try {
//            onsProducer.sendMsg(msg);
//        } catch (Exception e) {
//            log.error("exercise.sendMsg.groupId: " + groupId, e);
//        }
//        return parseResult;
//    }
 
    /**
     * 拷贝练习题
     * 
     * @param newGroupId
     * @param oldGroupId
     */
    public void doCopyExerciseItem(String newGroupId, String oldGroupId) {
        //改用存储过程 
        Session session = getCommonDAO().getSessionFactory().getCurrentSession();
        SQLQuery query = session.createSQLQuery("{call copy_exercise_item(?,?)}");
        query.setString(0, newGroupId);
        query.setString(1, oldGroupId);
        
        //执行
        query.executeUpdate();
    }
    
    /**
     * 复制历史练习
     * 
     * @param fromClassId
     * @return
     */
    public Result executeCopyExercise(String groupId, String subjectId, String subjectName, String chapterId) {
 
        try {
            ExerciseGroup source = this.read(ExerciseGroup.class, groupId);
            
            doCopyExercise(source, subjectId, subjectName, chapterId);
        } catch (IllegalAccessException e) {
            log.error(e, e);
            return new Result(false);
        } catch (InvocationTargetException e) {
            log.error(e, e);
            return new Result(false);
        }
 
        return new Result(true);
    }
 
    /**
     * 复制习题
     * 
     * @param sourceGroup
     * @param sequenceGroup
     * @param randomGroup
     * @return
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private Result doCopyExercise(ExerciseGroup sourceGroup, String subjectId, String subjectName, String chapterId) throws IllegalAccessException, InvocationTargetException {
 
        ExerciseGroup targetGroup = new ExerciseGroup();
 
        // 主表:组
        doSaveCopyGroup(sourceGroup, targetGroup, subjectId, subjectName, chapterId);
 
        // 关联表: 组   习题
        doSaveCopyRe(sourceGroup, targetGroup);
        
        // 扩展表: extend
        doSaveCopyExtend(sourceGroup,targetGroup);
 
        return new Result(true);
 
    }
    
    private Result doSaveCopyExtend(ExerciseGroup sourceGroup, ExerciseGroup targetGroup) throws IllegalAccessException, InvocationTargetException{
        
        String hql = "from ExerciseGroupExtend where deleteFlag is false and groupId = ? ";
        List<ExerciseGroupExtend> lstSourceExtends = this.find(hql, CollectionUtils.newList(sourceGroup.getGroupId()), ExerciseGroupExtend.class);
        int iCount = this.findCount(hql, CollectionUtils.newList(targetGroup.getGroupId()));
        if(iCount > 0){
            return new Result(true);
        }        
        List<ExerciseGroupExtend> lstTargetExtends = new ArrayList<ExerciseGroupExtend>(lstSourceExtends.size());
        for (ExerciseGroupExtend et : lstSourceExtends) {
 
            ExerciseGroupExtend objExtend = new ExerciseGroupExtend();
            BeanUtils.copyProperties(objExtend, et);
            TraceUtils.setCreateTrace(objExtend);
            objExtend.setGroupExtendId(null);
            objExtend.setDoCount(BigInteger.ZERO);
            objExtend.setClassAccuracy(BigDecimal.ZERO);
            objExtend.setCorrectCount(BigInteger.ZERO);
            objExtend.setSubmitNumber(BigInteger.ZERO);
            
            objExtend.setGroupId(targetGroup.getGroupId());
 
            lstTargetExtends.add(objExtend);
 
        }
 
        this.saveOrUpdateAll(lstTargetExtends);
        
        return new Result(true);
    }
 
    /**
     * 复制习题时,保存习题组
     * 
     * @param sourceGroup
     * @param targetGroup
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private Result doSaveCopyGroup(ExerciseGroup sourceGroup, ExerciseGroup targetGroup, String subjectId, String subjectName, String chapterId) throws IllegalAccessException, InvocationTargetException {
 
        BeanUtils.copyProperties(targetGroup, sourceGroup);
 
        targetGroup.setGroupId(null);
        targetGroup.setItems(null);
        targetGroup.setRecords(null);
        targetGroup.setClassId(ClientUtils.getClassId());
        targetGroup.setSubjectId(subjectId);
        targetGroup.setChapterId(chapterId);
        targetGroup.setStatus(ExerciseGroup.STATUS_DRAFT);
        targetGroup.setCollegeCourseId(ClientUtils.getCourseId());
        TraceUtils.setCreateTrace(targetGroup);
        targetGroup.setOrderNum(BigInteger.valueOf(SchCourseware.COURSEWARE_MAX_ORDER));
 
        this.saveExerciseGroup(targetGroup);
 
        return new Result(true);
    }
 
    /**
     * 复制练习时 保存习题关联
     * 
     * @param sourceGroup
     * @param targetGroup
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private Result doSaveCopyRe(ExerciseGroup sourceGroup, ExerciseGroup targetGroup) throws IllegalAccessException, InvocationTargetException {
 
        String hql = " from ExerciseGroupItemRe where deleteFlag is false and exerciseGroupId = ? ";
        List<ExerciseGroupItemRe> lstSourceGroupRe = this.find(hql, CollectionUtils.newList(sourceGroup.getGroupId()), ExerciseGroupItemRe.class);
 
        List<ExerciseGroupItemRe> lstTargetItemRe = new ArrayList<ExerciseGroupItemRe>(lstSourceGroupRe.size());
        for (ExerciseGroupItemRe it : lstSourceGroupRe) {
 
            ExerciseGroupItemRe ojbItemRe = new ExerciseGroupItemRe();
            BeanUtils.copyProperties(ojbItemRe, it);
 
            ojbItemRe.setRelationId(null);
            ojbItemRe.setExerciseGroupId(targetGroup.getGroupId());
            lstTargetItemRe.add(ojbItemRe);
 
        }
 
        this.saveOrUpdateAll(lstTargetItemRe);
 
        return new Result(true);
    }
 
    /**
     * 学员得分详情列表
     * 
     * @param groupId
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, Object>> resultList(String groupId) {
        ExerciseGroup exeGroup = read(ExerciseGroup.class, groupId);
 
        String hql_u = " from UserRegistration where deleteFlag is false and classId = ? and status = ? ";
        List<UserRegistration> userRegLst = find(hql_u, CollectionUtils.newList(ClientUtils.getClassId(),UserRegistration.STATUS_ACTIVE),UserRegistration.class);
        Map<String, UserRegistration> userMap = new HashMap<String, UserRegistration>();
        for (UserRegistration u : userRegLst) {
            userMap.put(u.getUserId(), u);
        }
        
        String hql_re = "select r.accuracy,r.update_Time,r.user_Id from (select * from Exercise_Record "
                + "where delete_Flag is false and accuracy <= 100 and exercise_Group_Id = ?";
 
        if (exeGroup.getType() == ExerciseGroup.TYPE_HOMEWORK || exeGroup.getType() == ExerciseGroup.TYPE_MOCK_EXAM) {
            hql_re = hql_re.concat(" and status=" + ExerciseRecord.STATUS_SUBMIT);
        }
 
        hql_re = hql_re.concat(" order by  accuracy desc ) r group by r.user_Id ");
        
        if (exeGroup.getType() == ExerciseGroup.TYPE_CHAPTER_ITEM || exeGroup.getType() == ExerciseGroup.TYPE_EXERCISE_TOPIC) {
 
            hql_re = hql_re.concat( " order by r.accuracy desc,r.status desc");
        } else {
 
            hql_re = hql_re.concat(" order by r.status desc,r.accuracy desc");
        }
        
        List<Object[]> reLst = findBySql(hql_re, CollectionUtils.newList(groupId));
        Map<String, Object[]> recordMap = new HashMap<String, Object[]>();
        for (Object[] obj : reLst) {
            recordMap.put(String.valueOf(obj[2]) , obj);
        }
        
        // 组装为Map
        List<Map<String, Object>> lstMap = new ArrayList<Map<String, Object>>(userRegLst.size());
        Map<String, Object> map = null;
 
        int rank = 1;
 
        for (Object[] record : reLst) {
            map = new HashMap<String, Object>(5);
            UserRegistration re = userMap.get(record[2]);
            if(null != re){
                map.put("accuracy",record[0]);
                map.put("time", record[1]);
                map.put("name", re.getUserName());
                map.put("mobilePhone", re.getMobilePhone());
                map.put("salesCode", re.getSalesCode());
                map.put("createTime", re.getUpdateTime());
                map.put("rank", rank);
                rank++;
                lstMap.add(map);
            }
        }
        for (UserRegistration user : userRegLst) {
            map = new HashMap<String, Object>(5);
            Object[] re = recordMap.get(user.getUserId());
            if(null == re){
                map.put("accuracy",0);
                map.put("time", null);
                map.put("name", user.getUserName());
                map.put("mobilePhone", user.getMobilePhone());
                map.put("salesCode", user.getSalesCode());
                map.put("createTime", user.getUpdateTime());
                map.put("rank", rank);
                rank++;
                lstMap.add(map);
            }
        }
        
        return lstMap;
    }
 
    /**
     * 初始化平均成绩和最高成绩
     * 
     * @param groupId
     * @return
     */
    @Override
    public Map<String, Object> initScore(String groupId) {
 
        ExerciseGroup exeGroup = read(ExerciseGroup.class, groupId);
 
        String hql_u = " from UserRegistration where deleteFlag is false and classId = ? and status = ? ";
        List<UserRegistration> userRegLst = find(hql_u, CollectionUtils.newList(ClientUtils.getClassId(),UserRegistration.STATUS_ACTIVE),UserRegistration.class);
        
        String hql_re = "select max(accuracy) as accuracy from ExerciseRecord "
                + "where deleteFlag is false and accuracy <= 100 and exerciseGroupId = ?";
        
        if (exeGroup.getType() == ExerciseGroup.TYPE_HOMEWORK || exeGroup.getType() == ExerciseGroup.TYPE_MOCK_EXAM) {
            hql_re = hql_re.concat( " and status=" + ExerciseRecord.STATUS_SUBMIT);
        }
 
        hql_re = hql_re.concat(" GROUP BY userId order by status desc,accuracy desc,updateTime");
 
        List<BigDecimal> reLst = find(hql_re, CollectionUtils.newList(groupId), BigDecimal.class);
        
        Map<String, Object> map = new HashMap<String, Object>(3);
        map.put("groupName", exeGroup.getName());
 
        if (reLst.isEmpty()) {    
            map.put("avg", 0.00);
            map.put("max", 0.00);
            return map;
        }
 
        BigDecimal score = BigDecimal.ZERO;
 
        // 计算已做学员总分数
        for (BigDecimal obj : reLst) {
            score = score.add(obj);
        }
 
        // 计算班级平均成绩
        Double scoreNew = Double.valueOf(String.valueOf(score)) / userRegLst.size();
 
        DecimalFormat df = new DecimalFormat("0.00");
        map.put("avg", df.format(scoreNew));
        map.put("max", df.format(reLst.get(0)));
 
        return map;
    }
 
    /**
     * 题目得分详情
     * 
     * @param groupId
     * @return
     */
    @Override
    public List<ExerciseItemStatistics> itemDetailList(String groupId) {
 
        String hql_itemStatis = "from ExerciseItemStatistics where deleteFlag is false and groupId = ?";
        List<ExerciseItemStatistics> itemStatisLst = this.find(hql_itemStatis, CollectionUtils.newList(groupId), ExerciseItemStatistics.class);
 
        if (itemStatisLst.isEmpty()) {
            return new ArrayList<ExerciseItemStatistics>();
        }
 
        // 获取组
        ExerciseGroup group = read(ExerciseGroup.class, groupId);
        if (null == group) {
            return new ArrayList<ExerciseItemStatistics>();
        }
 
        // 默认章节练习
        String hql = "select item from ExerciseItem item,ExerciseGroupItemRe re " + "where re.exerciseGroupId=? " + "and re.exerciseItemId=item.exerciseId " + "and item.deleteFlag is false " + "and re.deleteFlag is false " + "order by re.itemOrder ";
 
        // 随机练习,顺序练习
        if (ExerciseGroup.TYPE_EXERCISE_RANDOM == group.getType() || ExerciseGroup.TYPE_EXERCISE_SEQUENCE == group.getType()) {
            hql = "select item from ExerciseItem item,ExerciseGroupItemRe re " + "where re.exerciseGroupId=? and " + "re.exerciseItemId=item.exerciseId " + "and item.deleteFlag is false " + "and re.deleteFlag is false " + "order by item.chapterId, re.itemOrder ";
        }
 
        // 查询当前组的所有题目
        List<ExerciseItem> itemAllLst = this.exerDAO.find(hql, CollectionUtils.newList(groupId), ExerciseItem.class);
 
        if (itemAllLst.isEmpty()) {
            return new ArrayList<ExerciseItemStatistics>();
        }
 
        // 同步编号
        List<ExerciseItemStatistics> exeItemStatisLst = new ArrayList<ExerciseItemStatistics>(itemStatisLst.size());
        ExerciseItemStatistics obj = null;
        for (int j = 0; j < itemAllLst.size(); j++) {
            for (int i = 0; i < itemStatisLst.size(); i++) {
 
                obj = itemStatisLst.get(i);
                if (obj.getExerciseItemId().equals(itemAllLst.get(j).getExerciseId())) {
 
                    obj.setItemNo(j + 1);
                    obj.setClassAccuracyShow(obj.getClassAccuracy() + "%");
                    obj.setOrgAccuracyShow(obj.getOrgAccuracy() + "%");
 
                    // 给类型赋值
                    setExerItemTypeNewName(obj);
 
                    exeItemStatisLst.add(obj);
                    break;
                }
            }
        }
 
        return exeItemStatisLst;
    }
 
    private void setExerItemTypeNewName(ExerciseItemStatistics obj) {
        // 判断类型文字显示
        if (obj.getExerciseItemType() == ExerciseItem.TYPE_SINGLE_SELECT) {
            obj.setItemTypeName("单选题");
        } else if (obj.getExerciseItemType() == ExerciseItem.TYPE_MULTI_SELECT) {
            obj.setItemTypeName("多选题");
        } else if (obj.getExerciseItemType() == ExerciseItem.TYPE_TRUE_OR_FALSE) {
            obj.setItemTypeName("判断题");
        } else if (obj.getExerciseItemType() == ExerciseItem.TYPE_ESSAY_QUESTION) {
            obj.setItemTypeName("问答题");
        }
    }
 
    /**
     * 加载题目选项详情 - 班级、机构
     * 
     * @param groupId
     * @return
     */
    @Override
    public List<Map<String, Object>> loadOptionsList(String exerciseItemId) {
 
        String hql_option = "from ExerciseOptionStatistics where deleteFlag is false and exerciseItemId = ? and classId = ? and orgId = ? group by optionId";
        List<ExerciseOptionStatistics> optionLst = this.find(hql_option, CollectionUtils.newList(exerciseItemId, ClientUtils.getClassId(), ClientUtils.getOrgId()), ExerciseOptionStatistics.class);
 
        ExerciseItem item = this.read(ExerciseItem.class, exerciseItemId);
 
        List<Map<String, Object>> lstResult = new ArrayList<Map<String, Object>>(optionLst.size());
        Map<String, Object> map = null;
 
        for (ExerciseOptionStatistics optionStatis : optionLst) {
 
            map = new HashMap<String, Object>(12);
            map.put("content", optionStatis.getContent());
            map.put("checked", optionStatis.getChecked());
            map.put("classCorrectNum", optionStatis.getClassCorrectNum());
            map.put("classTotalNum", optionStatis.getClassTotalNum());
            map.put("classAccuracy", optionStatis.getClassAccuracy());
            map.put("orgCorrectNum", optionStatis.getOrgCorrectNum());
            map.put("orgTotalNum", optionStatis.getOrgTotalNum());
            map.put("orgAccuracy", optionStatis.getOrgAccuracy());
            map.put("exerciseItemTitel", item.getTitle());
            map.put("correctAnswer", item.getAnswer());
 
            if (optionStatis.getOptionOrder().equals("True")) {// 为True - 正确
                map.put("optionOrder", "正确");
            } else if (optionStatis.getOptionOrder().equals("False")) {// 为False - 错误
                map.put("optionOrder", "错误");
            } else {
                map.put("optionOrder", optionStatis.getOptionOrder());
            }
 
            // 判断题目的类型
            if ((short) item.getType() == ExerciseItem.TYPE_SINGLE_SELECT) {
                map.put("exerciseItemType", "单选题");
            } else if ((short) item.getType() == ExerciseItem.TYPE_MULTI_SELECT) {
                map.put("exerciseItemType", "多选题");
            } else if ((short) item.getType() == ExerciseItem.TYPE_TRUE_OR_FALSE) {
                map.put("exerciseItemType", "判断题");
            } else if ((short) item.getType() == ExerciseItem.TYPE_ESSAY_QUESTION) {
                map.put("exerciseItemType", "问答题");
            }
 
            lstResult.add(map);
        }
        return lstResult;
    }
 
    /**
     * 编辑练习保存
     */
    @Override
    public Result doSaveEditGroup(String groupId,String groupName) {
        ExerciseGroup group = read(ExerciseGroup.class, groupId);
        group.setName(groupName);
        TraceUtils.setUpdateTrace(group);
        
        this.bulkUpdate("update ExerciseGroup set name = ? where originExerciseId = ?", new Object[]{groupName, group.getGroupId()});
        this.bulkUpdate("update SchCourseware set name = ? where id in(select groupId from ExerciseGroup where originExerciseId = ?)", new Object[]{groupName, group.getGroupId()});
        
        return this.saveExerciseGroup(group);
    }
    
    /**
     * 排序
     * 
     * @param ids 排序id
     * @param index 序号
     * @return
     */
    public Result doOrder(List<String> ids,  List<Integer> index){
        // 循环修改order
        CommonDAO commonDAO = this.getCommonDAO();
        for( int i=0;i< ids.size();i++){
            String id = ids.get(i);
            commonDAO.bulkUpdate("update ExerciseGroup set orderNum = " + index.get(i) + " where groupId = ?", new Object[] { id });
            commonDAO.bulkUpdate("update SchCourseware set orderNum = " + index.get(i) + " where id = ?", new Object[] { id });
        }
        return new Result(true);
    }
    
    /**
     * 排序
     * 
     * @param ids 排序id
     * @param index 序号
     * @return
     */
    public Result doitemOrder(List<String> ids,  List<Integer> index,String groupId){
        // 循环修改order
        CommonDAO commonDAO = this.getCommonDAO();
        for( int i=0;i< ids.size();i++){
            String id = ids.get(i);
            commonDAO.bulkUpdate("update ExerciseGroupItemRe set itemOrder = " + index.get(i) + " where exerciseItemId = ? and exerciseGroupId = ?", new Object[] { id, groupId });
        }
        return new Result(true);
    }
    
    /**
     * 保存练习接口
     * 
     * @param group
     * @return
     */
    public Result saveExerciseGroup(ExerciseGroup group){
//        boolean isClass = StringUtils.isNotEmpty(ClientUtils.getClassId()) || StringUtils.isNotEmpty(group.getClassId());
        boolean isClass = false;
        Result result = new Result(false);
        TraceUtils.setUpdateTrace(group);
        
        Map<String, Integer> order = courseWareService.getOrder(!isClass, group.getSubjectId(), group.getChapterId());
        
        //同步排序
        int subjectOrder = order.get("subjectOrder");
        int chapterOrder = order.get("chapterOrder");
        int partOrder = order.get("partOrder");
        
        group.setSubjectOrder(subjectOrder);
        group.setChapterOrder(chapterOrder);
        group.setPartOrder(partOrder);
        
        result = this.save(group);
        
        short type = group.getType();
        if(type != ExerciseGroup.TYPE_EXERCISE_RANDOM && type != ExerciseGroup.TYPE_INTERACT
                && type != ExerciseGroup.TYPE_EXERCISE_TEACH_EVALUATE && type != ExerciseGroup.TYPE_EXERCISE_SEQUENCE
                && type != ExerciseGroup.TYPE_EXERCISE_FREE){
            SchCourseware courseware = null;
            if(isClass){
                courseware = this.findUnique("from SchCourseware where id = ? and classId = ? and deleteFlag is false",
                        CollectionUtils.newList(group.getGroupId(), group.getClassId()), SchCourseware.class);
            }else{
                courseware = this.findUnique("from SchCourseware where id = ? and orgId = ? and classId is null and deleteFlag is false",
                        CollectionUtils.newList(group.getGroupId(), ClientUtils.getOrgId()), SchCourseware.class);
                
                this.bulkUpdate("update SchCourseware set name = ?,remark = ? where id = ?", new Object[]{group.getName(),String.valueOf(group.getAllCount()), group.getGroupId()});
            }
            String parentChapterId = null;
            if(StringUtils.isNotEmpty(group.getChapterId())){
                SubjectChapter chapter = this.read(SubjectChapter.class, group.getChapterId());
                parentChapterId = chapter == null?null : chapter.getParentChapterId();
            }
            if(courseware == null){
                courseware = new SchCourseware();
                courseware.setChapterId(group.getChapterId());
                courseware.setId(group.getGroupId());
                courseware.setCollegeCourseId(group.getCollegeCourseId());
                courseware.setcType(group.getType());
                courseware.setType(SchCourseware.COURSEWARE_TYPE_EXERCISE);
                courseware.setName(group.getName());
                courseware.setRemark(String.valueOf(group.getAllCount()));
                courseware.setDeleteFlag(group.getDeleteFlag());
                courseware.setOrderNum(group.getOrderNum() == null?SchCourseware.COURSEWARE_MAX_ORDER:group.getOrderNum().intValue());
                courseware.setSubjectId(group.getSubjectId());
                courseware.setStatus(group.getStatus());
                courseware.setOrgId(StringUtils.isEmpty(group.getOrgId())?ClientUtils.getOrgId():group.getOrgId());
                courseware.setClassId(group.getClassId());
                courseware.setParentChapterId(parentChapterId);
                courseware.setSubjectOrder(group.getSubjectOrder());
                courseware.setChapterOrder(group.getChapterOrder());
                courseware.setPartOrder(group.getPartOrder());
                TraceUtils.setCreateTrace(courseware);
                
            }else{
                courseware.setChapterId(group.getChapterId());
                //courseware.setCollegeCourseId(group.getCollegeCourseId());
                courseware.setcType(group.getType());
                courseware.setName(group.getName());
                courseware.setRemark(String.valueOf(group.getAllCount()));
                courseware.setDeleteFlag(group.getDeleteFlag());
                courseware.setOrderNum(group.getOrderNum() == null?SchCourseware.COURSEWARE_MAX_ORDER:group.getOrderNum().intValue());
                courseware.setSubjectId(group.getSubjectId());
                courseware.setStatus(group.getStatus());
                courseware.setParentChapterId(parentChapterId);
                courseware.setSubjectOrder(group.getSubjectOrder());
                courseware.setChapterOrder(group.getChapterOrder());
                courseware.setPartOrder(group.getPartOrder());
                
                TraceUtils.setUpdateTrace(courseware);
            }
            this.save(courseware);
        }
        return result;
    }
    
    /**
     * (后台管理系统)
     *  管理员同步习题到班级
     * 
     * @param exerciseItemId
     * @return
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     */
    public Result doSynExercise(String[] exerciseItemIds) throws IllegalAccessException, InvocationTargetException{
        if(exerciseItemIds == null || exerciseItemIds.length == 0){
            return new Result(false, "参数错误");
        }
        List<Object> lstSaveObject = new ArrayList<>();
        for(String exerciseItemId : exerciseItemIds){
            //待同步的练习
            ExerciseItem sourceItem = this.read(ExerciseItem.class, exerciseItemId);
            if(sourceItem == null){
                continue;
            }
            
            List<ExerciseItemOption> lstSourceOption = sourceItem.getOptions();
            List<ExerciseItemAnalisi> lstSourceAnalisi = sourceItem.getAnalysises();
            List<ExerciseObjectImg> lstSourceImg = this.find("from ExerciseObjectImg where exerciseObjectId = ? and deleteFlag is false and objectType = ?",
                    CollectionUtils.newList(exerciseItemId, ExerciseObjectImg.OBJECT_TYPE_ITEM), ExerciseObjectImg.class);
            
            //下发的练习
            List<ExerciseItem> lstExerciseItem = this.find("from ExerciseItem where deleteFlag is false and orgiExerciseId = ?",
                    CollectionUtils.newList(exerciseItemId), ExerciseItem.class);
            if(lstExerciseItem == null || lstExerciseItem.size() == 0){
                continue;
            }
            //同步题目
            for(ExerciseItem exerciseItem :lstExerciseItem){
                exerciseItem.setTitle(sourceItem.getTitle());
                exerciseItem.setAnswer(sourceItem.getAnswer());
                TraceUtils.setUpdateTrace(exerciseItem);
                
                //同步更新练习组的时间
                this.bulkUpdate("update ExerciseGroup p set p.updateTime = sysdate() where EXISTS "+
                        " (select 1 from ExerciseGroupItemRe i where i.exerciseItemId = ? and i.deleteFlag is false and i.exerciseGroupId = p.groupId)", new Object[]{exerciseItem.getExerciseId()});
                
                List<ExerciseItemAnalisi> lstExerciseItemAnalisi = exerciseItem.getAnalysises();
                List<ExerciseObjectImg> lstExerciseObjectImg = this.find("from ExerciseObjectImg where exerciseObjectId = ? and deleteFlag is false and objectType = ?",
                        CollectionUtils.newList(exerciseItem.getExerciseId(), ExerciseObjectImg.OBJECT_TYPE_ITEM), ExerciseObjectImg.class);
                //同步选项
                if(lstSourceOption != null && lstSourceOption.size() > 0){
                    ExerciseItemOption option;
                    //删除选项的题目
                    this.bulkUpdate("update ExerciseItemOption p set p.deleteFlag = true where  exerciseItemId = ?", new Object[]{exerciseItem.getExerciseId()});
                    for(ExerciseItemOption sourceOption : lstSourceOption){
                        ExerciseObjectImg objExerciseObjectImg;
                        option = this.findUnique("from ExerciseItemOption where exerciseItemId = ? and optionOrder = ?",
                                CollectionUtils.newList(exerciseItem.getExerciseId(), sourceOption.getOptionOrder()), ExerciseItemOption.class);
                        
                        ExerciseObjectImg objSourceImg = this.findUnique("from ExerciseObjectImg where exerciseObjectId = ? and deleteFlag is false and objectType = ?",
                                CollectionUtils.newList(sourceOption.getOptionId(), ExerciseObjectImg.OBJECT_TYPE_ITEM_OPTION), ExerciseObjectImg.class);
                        if(option == null){
                            option = new ExerciseItemOption();
                            BeanUtils.copyProperties(option, sourceOption);
                            option.setExerciseItemId(exerciseItem.getExerciseId());
                            option.setOptionId(null);
                            
                            TraceUtils.setCreateTrace(option);
                            
                            if(objSourceImg != null){//选项图片
                                objExerciseObjectImg = new ExerciseObjectImg();
                                BeanUtils.copyProperties(objExerciseObjectImg, objSourceImg);
                                objExerciseObjectImg.setExerciseObjectId(option.getOptionId());
                                objExerciseObjectImg.setImgId(null);
                                
                                TraceUtils.setCreateTrace(objExerciseObjectImg);
                                
                                lstSaveObject.add(objExerciseObjectImg);
                            }
                        }else{
                            option.setContent(sourceOption.getContent());
                            option.setChecked(sourceOption.getChecked());
                            option.setDeleteFlag(false);
                            
                            TraceUtils.setUpdateTrace(option);
                            
                            objExerciseObjectImg = this.findUnique("from ExerciseObjectImg where exerciseObjectId = ? and deleteFlag is false and objectType = ?",
                                    CollectionUtils.newList(option.getOptionId(), ExerciseObjectImg.OBJECT_TYPE_ITEM_OPTION), ExerciseObjectImg.class);
                            if(objSourceImg != null){
                                if(objExerciseObjectImg != null){
                                    objExerciseObjectImg.setImgPath(objSourceImg.getImgPath());
                                    
                                    TraceUtils.setUpdateTrace(objExerciseObjectImg);
                                }else{
                                    objExerciseObjectImg = new ExerciseObjectImg();
                                    BeanUtils.copyProperties(objExerciseObjectImg, objSourceImg);
                                    objExerciseObjectImg.setExerciseObjectId(option.getOptionId());
                                    objExerciseObjectImg.setImgId(null);
                                    
                                    TraceUtils.setCreateTrace(objExerciseObjectImg);
                                }
                                
                                lstSaveObject.add(objExerciseObjectImg);
                            }
                        }
                        lstSaveObject.add(option);
                    }
                }
                //同步解析
                if(lstSourceAnalisi != null && lstSourceAnalisi.size() > 0){
                    ExerciseItemAnalisi objExerciseItemAnalisi;
                    if(lstExerciseItemAnalisi == null || lstExerciseItemAnalisi.size() == 0){
                        objExerciseItemAnalisi = new ExerciseItemAnalisi();
                        BeanUtils.copyProperties(objExerciseItemAnalisi, lstSourceAnalisi.get(0));
                        objExerciseItemAnalisi.setExerciseItemId(exerciseItem.getExerciseId());
                        objExerciseItemAnalisi.setExerciseAnalisisId(null);
                    
                        TraceUtils.setCreateTrace(objExerciseItemAnalisi);
                    }else{
                        objExerciseItemAnalisi = lstExerciseItemAnalisi.get(0);
                        TraceUtils.setUpdateTrace(objExerciseItemAnalisi);
                        objExerciseItemAnalisi.setAnalysis(lstSourceAnalisi.get(0).getAnalysis());
                    }
                    lstSaveObject.add(objExerciseItemAnalisi);
                }
                //同步题目图片
                if(lstSourceImg != null && lstSourceImg.size() > 0){
                    ExerciseObjectImg objExerciseObjectImg;
                    if(lstExerciseObjectImg == null || lstExerciseObjectImg.size() == 0){
                        objExerciseObjectImg = new ExerciseObjectImg();
                        BeanUtils.copyProperties(objExerciseObjectImg, lstSourceImg.get(0));
                        objExerciseObjectImg.setExerciseObjectId(exerciseItem.getExerciseId());
                        objExerciseObjectImg.setImgId(null);
                        
                        TraceUtils.setCreateTrace(objExerciseObjectImg);
                    }else{
                        objExerciseObjectImg = lstExerciseObjectImg.get(0);
                        objExerciseObjectImg.setImgPath(lstSourceImg.get(0).getImgPath());
                        TraceUtils.setUpdateTrace(objExerciseObjectImg);
                    }
                    
                    lstSaveObject.add(objExerciseObjectImg);
                }
                lstSaveObject.add(exerciseItem);
            }
        }
        this.saveOrUpdateAll(lstSaveObject);
        return new Result(true);
    }
    
    /**
     * 数据同步接口,同步下发到班级的数据
     * 
     * @param orgId
     * @param groupId
     * @return
     */
    public Result doSynExerciseItem(String orgId, String groupId){
        List<ExerciseGroup> lstGroup = null;
        if(StringUtils.isNoneBlank(orgId)){
            String hql = "select e from ExerciseGroup e ,OrgCollegeCourse o ,ExerciseReCourse c "
                    + " where e.groupId = c.groupId"
                    + " and o.collegeCourseId = c.collegeCourseId "
                    + " and c.orgId=? "
                    + " and o.deleteFlag is false "
                    + " and c.deleteFlag is false "
                    + " and e.deleteFlag is false ";
            lstGroup = this.find(hql, CollectionUtils.newList(orgId), ExerciseGroup.class);
        }else if(StringUtils.isNotBlank(groupId)){
            lstGroup = this.find("from ExerciseGroup g where g.groupId = ?", CollectionUtils.newList(groupId), ExerciseGroup.class);
        }else{
            return new Result(false, "参数错误");
        }
        
        if(lstGroup == null || lstGroup.size() == 0){
            return new Result(false, "数据为空");
        }
        
        for(ExerciseGroup group : lstGroup){
            String id = group.getGroupId();
            List<ExerciseGroup> subListGroup = this.find("from ExerciseGroup e where e.originExerciseId = ? and deleteFlag is false and e.groupId <> ?",
                    CollectionUtils.newList(id, id), ExerciseGroup.class);
            
            if(subListGroup == null || subListGroup.size() == 0){
                continue;
            }
            List<ExerciseItem> orgiExerciseItem = group.getItems();
            
            for(ExerciseGroup subGroup : subListGroup){
                List<ExerciseItem> subExerciseItem = subGroup.getItems();
                for(ExerciseItem item : subExerciseItem){
                    int index = orgiExerciseItem.indexOf(item);
                    if(index > -1){
                        item.setOrgiExerciseId(orgiExerciseItem.get(index).getExerciseId());
                        
                        TraceUtils.setUpdateTrace(item);
                        this.save(item);
                    }
                }
                
            }
        }
        return new Result(true, "成功");
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public Result saveExerciseItemBatch(String groupId,List<ExerciseItem> items) {
        if (items == null || items.size() == 0) {
            return new Result(false, "没有要保存或更新的题目数据!");
        }
    
        ExerciseGroup group = this.read(ExerciseGroup.class, groupId);
        int allCount= group.getAllCount()==null?0:group.getAllCount().intValue();
        
        List<String> lstExerciseItemIds = new ArrayList<String>();
        for (ExerciseItem item : items) {
            if (StringUtils.isEmpty(item.getExerciseId())) {
                this.insertExerciseItem(groupId, item, item.getOptions(),
                        item.getAnalisis().getAnalysis());
                group.setAllCount(BigInteger.valueOf(++allCount));
                lstExerciseItemIds.add(item.getExerciseId());
            } else {
                this.updateExerciseItem(item, item.getOptions(), item.getAnalisis()==null?null:item.getAnalisis().getAnalysis());
                lstExerciseItemIds.add(item.getExerciseId());
            }
        }
        
        this.save(group);
        redisTemplate.delete(groupId);
        return new Result(true, "成功",lstExerciseItemIds.toArray());
    }
    
 
    /**
     * 问卷评估  复制练习
     * @param groupId
     * @return
     */
    @Override
    public String doCopyExerciseByEvaluate(String groupId) {
        
        // 1、复制练习组
        ExerciseGroup group = this.read(ExerciseGroup.class, groupId);
        ExerciseGroup newGroup = new ExerciseGroup();
        try {
            BeanUtils.copyProperties(newGroup, group);
            newGroup.setGroupId(null);
            newGroup.setRecords(null);
        } catch (Exception e) {
            log.error("问卷复制:复制练习BeanUtils.copyProperties()方法copy失败", e);
        } 
        TraceUtils.setCreateTrace(newGroup);
        this.save(newGroup);
        
        // 2、复制题目
        this.doCopyEvaExerciseItem(newGroup.getGroupId(), groupId);
        
        return newGroup.getGroupId();
    }
    
    /**
     * 拷贝练习题
     * 
     * @param newGroupId
     * @param oldGroupId
     */
    public void doCopyEvaExerciseItem(String newGroupId, String oldGroupId) {
        //改用存储过程 
        //执行
        this.executeProduce("{call copy_exercise_item(?,?)}", new Object[]{newGroupId, oldGroupId});
    }
 
    /**
     * 查询问卷用户练习详情
     * @param recordId
     * @param evaluateId
     * @return
     */
    @Override
    public ResultJson queryUserEvaExerciseDetail(String recordId, String evaluateId) {
        ExerciseRecord objExerciseRecord = this.read(ExerciseRecord.class, recordId);
        
        QExerciseItem item = QExerciseItem.exerciseItem;
        QExerciseGroupItemRe re = QExerciseGroupItemRe.exerciseGroupItemRe;
        // 查询题目list
        List<ExerciseItem> itemLst = this.getQueryFactory().select(item).from(item,re)
                .where(item.exerciseId.eq(re.exerciseItemId)
                        .and(item.deleteFlag.eq(false))
                        .and(re.deleteFlag.eq(false))
                        .and(re.exerciseGroupId.eq(objExerciseRecord.getExerciseGroupId()))).fetch();
        
        QExerciseItemAnswerU answerU = QExerciseItemAnswerU.exerciseItemAnswerU;
        QExerciseObjectImg objImg = QExerciseObjectImg.exerciseObjectImg;
        QExerciseItemOption option = QExerciseItemOption.exerciseItemOption;
        SchEvaluate objSchEvaluate = this.read(SchEvaluate.class, evaluateId);
        List<ExerciseObjectImg> lstExerciseObjectImg = null;
        for (ExerciseItem objExerciseItem : itemLst) {
            if(objExerciseItem.getType() == ExerciseItem.TYPE_ATTACHMENT){//附件题读取题目的图片信息
                
                lstExerciseObjectImg = this.getQueryFactory().selectFrom(objImg)
                        .where(objImg.exerciseObjectId.in(
                                    this.getQueryFactory().select(option.optionId).from(option)
                                    .where(option.exerciseItemId.eq(objExerciseItem.getExerciseId()).and(option.deleteFlag.eq(false))))
                                .and(objImg.deleteFlag.eq(false))
                                .and(objImg.createId.eq(objExerciseRecord.getUserId()))
                                )
                        .fetch();
                
            }
            
            //查询用户答题
            List<ExerciseItemAnswerU> lstExerciseItemAnswerU = this.getQueryFactory().selectFrom(answerU)
                    .where(answerU.deleteFlag.eq(false)
                        .and(answerU.exerciseRecordId.eq(objExerciseRecord.getRecordId()))
                        .and(answerU.exerciseItemId.eq(objExerciseItem.getExerciseId())))
                        .fetch();
            
            objExerciseItem.setExerciseItemAnswerU(lstExerciseItemAnswerU);
        }
        
        //拼装前端所需要的数据
        Map<String, Object> resultMap =  ExerciseUtils.packageUserExerciseDetail(itemLst, objSchEvaluate, lstExerciseObjectImg);
        
        return new ResultJson(true,"success",resultMap);
    }
    
    /**
     * 删除问卷图片
     */
    @Override
    public ResultJson dodelEvaExerciseObjImg(String imgObjId) {
        ExerciseObjectImg img = this.read(ExerciseObjectImg.class, imgObjId);
        img.setDeleteFlag(true);
        TraceUtils.setUpdateTrace(img);
        
        this.save(img);
 
        return new ResultJson(true,"操作成功");
    }
 
    /**
     * 新增问卷图片
     */
    @Override
    public List<Map<String, Object>> doAddEvaExerciseObjImg(String[] imgPath, String imgObjId, int imgObjType) {
        // 查询此练习是否已经存在记录
        QExerciseObjectImg objImg = QExerciseObjectImg.exerciseObjectImg;
        List<ExerciseObjectImg> lstObjImg = this.getQueryFactory()
                .selectFrom(objImg)
                .where(objImg.exerciseObjectId.eq(imgObjId)
                        .and(objImg.objectType.eq(imgObjType)
                        .and(objImg.deleteFlag.eq(false))))
                .orderBy(objImg.imgOrder.desc())
                .fetch();
        
        int imgOrder = 1;
        if (!lstObjImg.isEmpty()) {
            imgOrder = lstObjImg.get(0).getImgOrder() + 1;
        }
 
        List<ExerciseObjectImg> lstImg = new ArrayList<ExerciseObjectImg>(imgPath.length);
        ExerciseObjectImg img = new ExerciseObjectImg();
        img.setObjectType(imgObjType);
        img.setImgPath(imgPath[0]);
        img.setExerciseObjectId(imgObjId);
        img.setImgOrder(imgOrder);
        img.setDeleteFlag(false);
        TraceUtils.setCreateTrace(img);
        lstImg.add(img);
 
        for (int i = 1; i < imgPath.length; i++) {
            img.setImgPath(imgPath[i]);
            img.setImgOrder(imgOrder++);
            lstImg.add(img);
        }
 
        this.saveOrUpdateAll(lstImg);
 
        List<Map<String, Object>> lstResult = new ArrayList<Map<String, Object>>(lstImg.size());
        Map<String, Object> resultMap = null;
        for (ExerciseObjectImg obj : lstImg) {
            resultMap = new HashMap<String, Object>(2);
            resultMap.put("imgId", obj.getImgId());
            resultMap.put("imgPath", obj.getImgPath());
            lstResult.add(resultMap);
        }
        return lstResult;
    }
 
    /**
     * 查询问卷图片
     */
    @Override
    public List<Map<String, Object>> queryEvaExerciseObjImg(String imgObjId, int imgObjType) {
        // 查询此练习是否已经存在记录
        QExerciseObjectImg objImg = QExerciseObjectImg.exerciseObjectImg;
        List<ExerciseObjectImg> lstObjImg = this.getQueryFactory()
                .selectFrom(objImg)
                .where(objImg.exerciseObjectId.eq(imgObjId)
                        .and(objImg.objectType.eq(imgObjType)
                        .eq(objImg.deleteFlag.eq(false))))
                .orderBy(objImg.imgOrder.asc())
                .fetch();
        
        if(lstObjImg.isEmpty()){
            return null;
        }
        List<Map<String,Object>> lstResult = new ArrayList<Map<String,Object>>(lstObjImg.size());
        Map<String,Object> resultMap = null;
        for(ExerciseObjectImg obj:lstObjImg){
            resultMap = new HashMap<String,Object>(2);
            resultMap.put("imgId", obj.getImgId());
            resultMap.put("imgPath", obj.getImgPath());
            lstResult.add(resultMap);
        }
        return lstResult;
    }
    
    /**
     * 更新习题选项图片对象结果
     * 
     * @param optionId
     * @param imgIds
     * @return
     */
    private Result updateEvaExerciseObjImgId(JSONArray titleImgs,String exerciseId) {
 
        if (titleImgs == null || titleImgs.isEmpty()) {
            return new Result(false);
        }
        
        List<String> imgIds = new ArrayList<String>(titleImgs.size());
        for(int i=0;i<titleImgs.size();i++){
            imgIds.add(String.valueOf(titleImgs.getJSONObject(i).get("imgId")));
        }
        
        QExerciseObjectImg objImg = QExerciseObjectImg.exerciseObjectImg;
        this.getQueryFactory().update(objImg).set(objImg.exerciseObjectId, exerciseId)
        .where(objImg.imgId.in(imgIds)
                .and(objImg.deleteFlag.eq(false))).execute();
 
        return new Result(true);
    }
    
    /**
     * 更新习题选项图片对象结果
     * 
     * @param optionId
     * @param imgIds
     * @return
     */
    private Result updateEvaExerOptionObjImgId(ExerciseItemOption option) {
 
        List<ExerciseObjectImg> imgs = option.getImgs();
        if (imgs == null || imgs.isEmpty()) {
            return new Result(false);
        }
        List<String> imgIds = new ArrayList<String>(imgs.size());
        for (int i = 0; i < imgs.size(); i++) {
            imgIds.add(imgs.get(i).getImgId());
        }
        
        QExerciseObjectImg objImg = QExerciseObjectImg.exerciseObjectImg;
        this.getQueryFactory().update(objImg).set(objImg.exerciseObjectId, option.getOptionId())
        .where(objImg.imgId.in(imgIds)
                .and(objImg.deleteFlag.eq(false))).execute();
 
        return new Result(true);
    }
}