package com.qmth.jkserver.common;

import com.qmth.jkserver.constant.SpringContextHolder;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.model.ExamStudentAdditionalTemp;
import com.qmth.jkserver.service.JkExamPlanService;
import com.qmth.jkserver.service.JkExamStudentAdditionalTempService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * CSV 工具类
 *
 * @author tianjun
 */
public class CsvUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(CsvUtils.class);

    public static List<ExamStudentAdditionalTemp> getStudentAdditionalInfoFromCsv(String filePath)
            throws EncryptedDocumentException, InvalidFormatException, IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在," + filePath);
        }
        List<ExamStudentAdditionalTemp> list = new LinkedList<ExamStudentAdditionalTemp>();
        FileData data = new FileData(file, ",");
        String[] columnName = null;
        while (data.nextLine()) {
            // 读取列名
            if (columnName == null) {
                columnName = data.getDatas();
                continue;
            }
            ExamStudentAdditionalTemp info = new ExamStudentAdditionalTemp();
            info.setId(SystemConstant.getDbUuid());
            Map<String, String> others = new HashMap<String, String>();
            for (int i = 0; i < columnName.length; i++) {
                if ("studentID".equals(columnName[i])) {
                    info.setStudentId(Long.parseLong(data.getData(i)));
                } else if ("coursecode".equals(columnName[i])) {
                    info.setCourseCode(StringUtils.trimToEmpty(data.getData(i)));
                } else if ("coursename".equals(columnName[i])) {
                    info.setCourseName(StringUtils.trimToEmpty(data.getData(i)));
                } else {
                    others.put(columnName[i], StringUtils.trimToEmpty(data.getData(i)));
                    info.setData(others);
                }
            }
            list.add(info);
        }
        data.close();
        return list;
    }

    public static void saveStudentAdditionalInfoFromCsv(
            String examCode,
            Long attachmentId,
            String filePath,
            JkExamPlanService examPlanService)
            throws EncryptedDocumentException, InvalidFormatException, IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在," + filePath);
        }
        List<ExamStudentAdditionalTemp> list = new LinkedList<ExamStudentAdditionalTemp>();
        FileData data = new FileData(file, ",");
        String[] columnName = null;
        while (data.nextLine()) {
            // 读取列名
            if (columnName == null) {
                columnName = data.getDatas();
                continue;
            }
            ExamStudentAdditionalTemp info = new ExamStudentAdditionalTemp();
            info.setId(SystemConstant.getDbUuid());
            Map<String, String> others = new HashMap<String, String>();
            for (int i = 0; i < columnName.length; i++) {
                if ("studentID".equals(columnName[i])) {
                    info.setStudentId(Long.parseLong(data.getData(i)));
                } else if ("coursecode".equals(columnName[i])) {
                    info.setCourseCode(StringUtils.trimToEmpty(data.getData(i)));
                } else if ("coursename".equals(columnName[i])) {
                    info.setCourseName(StringUtils.trimToEmpty(data.getData(i)));
                } else {
                    others.put(columnName[i], StringUtils.trimToEmpty(data.getData(i)));
                    info.setData(others);
                }
            }
            info.setCreateTime(System.currentTimeMillis());
            info.setAttachmentId(attachmentId);
            info.setExamCode(examCode);
            list.add(info);
            //没10000条数据写一次数据库
            if (list.size() >= 10000) {
                LOGGER.info("----save saveKwstudentAdditionalTemp size:" + list.size());
                batchSaveKwstudentAdditionalTemp(list);
                list.clear();
                LOGGER.info("----clean KwstudentAdditionalTemp size:" + list.size());
            }
        }
        data.close();
        batchSaveKwstudentAdditionalTemp(list);
    }

    protected static void batchSaveKwstudentAdditionalTemp(List<ExamStudentAdditionalTemp> examStudentTemps) {
        if (examStudentTemps == null || examStudentTemps.size() == 0) {
            return;
        }
//        List<DBObject> list = new ArrayList<DBObject>();
//        for (ExamStudentAdditionalTemp answer : examStudentTemps) {
//            Object object = mongoTemplate.getConverter().convertToMongoType(answer);
//            DBObject dbObject = (DBObject) JSON.parse(object.toString());
//            dbObject.put("_class", ExamStudentAdditionalTemp.class.getName());
//            list.add(dbObject);
//        }
        long time1 = System.currentTimeMillis();
        JkExamStudentAdditionalTempService jkExamStudentAdditionalTempService = SpringContextHolder.getBean(JkExamStudentAdditionalTempService.class);
        jkExamStudentAdditionalTempService.saveOrUpdateBatch(examStudentTemps);
//        mongoTemplate.getCollection("jk_exam_student_additional_temp").insert(list);
        long time2 = System.currentTimeMillis();
        LOGGER.info("----insert jk_exam_student_additional_temp, size:" + examStudentTemps.size() + ",use time:" + ((time2 - time1) / 1000) + "(s)");

    }
}
