派生自 projectDept/qhighschool

胡仁荣
2022-11-24 06d6372b451b964738cbfe2adb37e1da85d856ed
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
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.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
 
import com.qxueyou.scc.base.model.Result;
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.config.SccConfig;
import com.qxueyou.scc.exercise.model.ExerciseGroupItemRe;
import com.qxueyou.scc.exercise.model.ExerciseItem;
import com.qxueyou.scc.exercise.model.ExerciseItemAnalisi;
import com.qxueyou.scc.exercise.model.ExerciseItemData;
import com.qxueyou.scc.exercise.model.ExerciseItemOption;
import com.qxueyou.scc.exercise.model.ExerciseOptionData;
import com.qxueyou.scc.exercise.service.IExercisePyService;
 
@Service
@EnableConfigurationProperties(SccConfig.class)
public class ExercisePyService extends CommonAppService implements
        IExercisePyService {
 
    @Autowired
    SccConfig sccConfig;
 
    @Autowired
    IFileUploadService fileUploadService;
 
    private static Logger log = LogManager.getLogger("ExercisePyService");
 
    /**
     * ÉÏ´«½âÎö
     */
    public Map<String, Object> parserPyExercise(String groupId, String fullPath,
            String module) {
 
        File file = downloadFile(groupId, fullPath, module);
        List<String> lst = generateLstFromFile(file, fullPath);
 
        if (null == lst || lst.isEmpty()) {
            return CollectionUtils.newObjectMap("resultCode",0,"msg","Îĵµ½âÎöÄÚÈÝΪ¿Õ");
        }
 
        return exerciseParsePy(lst, fullPath);
 
    }
 
    /**
     * Ð£Ñé
     * 
     * @param content
     *            Ï°ÌâÎı¾ÄÚÈÝ
     * @return
     */
    public Map<String, Object> validatePyExercise(String content) {
 
        String[] arrLine = content.split("\n");
        List<String> lst = new ArrayList<String>(arrLine.length);
        
        for(int i =0;i<arrLine.length;i++ ){
            if(StringUtils.isBlank(arrLine[i])){
                continue ;
            }
            lst.add(arrLine[i]);
        }
 
        // ÅжϣºÊÇ·ñΪ¿Õ
        if (null == lst || lst.isEmpty()) {
            return CollectionUtils.newObjectMap("resultCode",0,"msg","Îĵµ½âÎöÄÚÈÝΪ¿Õ");
        }
 
        return exerciseParsePy(lst, "" );
        
    }
    
    public Result doImportPyExercise(List<ExerciseItemData> lstItems,String groupId) {
        
        if(null == lstItems || lstItems.isEmpty()){
            return new Result(false, "ûÓмǼ");
        }
        
        ExerciseGroupItemRe re ;
        ExerciseItemAnalisi analysis;
        ExerciseItemOption option ;
        ExerciseItem item ;
        
        int itemOrder = 0; 
        String hql = "from ExerciseGroupItemRe r where r.exerciseGroupId = ? order by r.itemOrder desc ";
        ExerciseGroupItemRe groupRe = this.findUnique(hql, CollectionUtils.newList(groupId), ExerciseGroupItemRe.class);
        if( null != groupRe ){
            itemOrder = groupRe.getItemOrder() ;
        }
        
        
        
        BigInteger iCount = BigInteger.ZERO ;
        try {
            
            for(ExerciseItemData data : lstItems){
                
                item = new ExerciseItem();
                re = new ExerciseGroupItemRe();
                
                BeanUtils.copyProperties(item, data);
                item.setDeleteFlag(false);
                TraceUtils.setCreateTrace(item);
                this.save(item);
                
                iCount = iCount.add(BigInteger.ONE);
                
                BeanUtils.copyProperties(re, data);
                itemOrder++;
                re.setDeleteFlag(false);
                re.setExerciseGroupId(groupId);
                re.setExerciseItemId(item.getExerciseId());
                re.setItemOrder(itemOrder);
                re.setDeleteFlag(false);
                this.save(re);
                
                if(StringUtils.isNotBlank(data.getAnalysis())){
                    analysis = new ExerciseItemAnalisi();
                    BeanUtils.copyProperties(analysis, data);
                    TraceUtils.setCreateTrace(analysis);
                    analysis.setDeleteFlag(false);
                    analysis.setExerciseItemId(item.getExerciseId());
                    this.save(analysis);
                }
                
                if( data.getOptions() != null && !data.getOptions().isEmpty() ){
                    
                    for( ExerciseOptionData opt : data.getOptions() ){
                        option = new ExerciseItemOption();
                        BeanUtils.copyProperties(option, opt);
                        TraceUtils.setCreateTrace(option);
                        option.setDeleteFlag(false);
                        option.setExerciseItemId(item.getExerciseId());
                        this.save(option);
                    }
                    
                }
                
            }
            
            this.bulkUpdate("update ExerciseGroup set allCount = allCount + ? , " +
                    " updateTime = sysdate(), updateId = ? , updator = ? where groupId = ?  " , 
                    new Object[]{ iCount,ClientUtils.getUserId(), ClientUtils.getUserName(), groupId } );
            
        } catch (Exception e) {
            log.error("½âÎöϰÌâcopyProperties Ê§°Ü£º" ,e );
            return new Result(false , "·þÎñÆ÷ÄÚ²¿×ª»»´íÎó");
        }
        
        return new Result(true , "³É¹¦µ¼Èë" + iCount + "µÀϰÌâ");
    }
    
 
    private Map<String, Object> exerciseParsePy(List<String> lst, String fullPath) {
 
        return pyExerciseParseByParam(lst, lst.size());
        //return pyExerciseParseByCache(lst, lst.size());
            
        
    }
    
    /**
     * post´«²Î
     * @param key
     * @param size
     * @return
     * @throws Exception
     */
    private Map<String, Object> pyExerciseParseByParam(List<String> lst0, int size) {
        
        return null;
 
    }
    
 
 
    /**
     * »º´æ°æ±¾
     * @param key
     * @param size
     * @return
     * @throws Exception
     */
    
    @SuppressWarnings("unused")
    private Map<String, Object> pyExerciseParseByCache(List<String> lst, int size){
        
        return null;
 
    }
 
 
    private File downloadFile(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);
 
        return fileUploadService.doGetOssFile(fullPath, filePath, module,
                ClientUtils.getUserId());
 
    }
 
    private List<String> generateLstFromFile(File file, String fullPath) {
 
        String txtFilePath = transformDocToTxt(file);
 
        List<String> lst = new ArrayList<String>(100);
 
        FileReader reader = null;
        BufferedReader br = null;
        try {
            reader = new FileReader(txtFilePath);
            br = new BufferedReader(reader);
 
            String currLine = "";
            while ((currLine = br.readLine()) != null) {
                if (StringUtils.isNotBlank(currLine)) {
                    lst.add(currLine);
                }
            }
        } catch (Exception e) {
            log.error("½âÎöÁ·Ï°txtÎĵµÊ§°Ü£º" + fullPath, e);
        } finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(reader);
        }
 
        File txt = new File(txtFilePath);
        FileUtils.deleteQuietly(txt);
 
        return lst;
 
    }
 
    /**
     * ´Óofficeת»»µ½txt£º2007ת»»£º×Ô´øÐòºÅ¸ñʽ»á¶ªÊ§£»2003»á½âÎö³öÀ´
     * 
     * @param file
     * @return
     */
    private String transformDocToTxt(File file) {
        InputStream is = null;
        FileWriter writer = null;
        String strText = "";
 
        try {
            String fileExtention = fileExtension(file.getName());
            is = new FileInputStream(file.getAbsolutePath());
 
            if ("doc".equals(fileExtention)) {
                WordExtractor extractor = new WordExtractor(is);
                // »ñÈ¡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(is);
        }
    }
 
    /**
     * È«½Çת°ë½Ç
     * 
     * @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());
    }
 
}