package com.qmth.themis.business.templete.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.qmth.themis.business.config.SystemConfig;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.response.TEExamStudentDto;
import com.qmth.themis.business.enums.TaskStatusEnum;
import com.qmth.themis.business.excel.ExportUtils;
import com.qmth.themis.business.service.TEExamStudentService;
import com.qmth.themis.business.templete.TaskExportCommon;
import com.qmth.themis.business.templete.TaskExportTemplete;
import com.qmth.themis.common.util.Result;
import com.qmth.themis.common.util.ResultUtil;

/**
 * @Description: 考场导出任务
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/7/20
 */
@Service
public class TaskExamStudentExportTemplete implements TaskExportTemplete {
    private final static Logger log = LoggerFactory.getLogger(TaskExamStudentExportTemplete.class);

    @Resource
    SystemConfig systemConfig;

    @Resource
    TEExamStudentService teExamStudentService;

    /**
     * 考生导出模版
     *
     * @param map
     * @return
     */
    @Override
    public Result exportTask(Map<String, Object> transMap) throws IOException {
        log.info("开始导出考生数据");
        long start = System.currentTimeMillis();
        TaskExportCommon taskExportCommon = new TaskExportCommon(transMap);
        taskExportCommon.init();
        FileOutputStream fos = null;
        File mkdir=null;
        File file = null;
        
        boolean oss = (boolean) taskExportCommon.getOssEnv().get(SystemConstant.OSS);
        try {
            StringJoiner stringJoiner = new StringJoiner("");
            if (!oss) {
                stringJoiner.add(SystemConstant.FILES_DIR).add(File.separator);
            }
            LocalDateTime nowTime = LocalDateTime.now();
            String uploadType = String.valueOf(taskExportCommon.getOssEnv().get(SystemConstant.UPLOAD_TYPE));
            stringJoiner.add(uploadType).add(File.separator).add(String.valueOf(nowTime.getYear()))
                    .add(File.separator).add(String.valueOf(nowTime.getMonthValue()))
                    .add(File.separator).add(String.valueOf(nowTime.getDayOfMonth()));
            mkdir = new File(stringJoiner.toString());
            if (!mkdir.exists()) {
                mkdir.mkdirs();
            }
            file=new File(mkdir.getPath()+"/"+uuid()+SystemConstant.EXCEL_PREFIX);
            file.createNewFile();
        	fos = new FileOutputStream(file);
            Long examId=(Long)transMap.get("examId");
            Long activityId=(Long)transMap.get("activityId");
            String identity=(String)transMap.get("identity");
            String name=(String)transMap.get("name");
            String roomCode=(String)transMap.get("roomCode");
            String courseCode=(String)transMap.get("courseCode");
            String grade=(String)transMap.get("grade");
            Integer enable=(Integer)transMap.get("enable");
            String classNo=(String)transMap.get("classNo");
            Integer hasPhoto=(Integer)transMap.get("hasPhoto");
    		List<TEExamStudentDto> list = teExamStudentService.examStudentList(examId, activityId, identity, name, roomCode, courseCode, grade,
    				enable, classNo,hasPhoto);
    		ExportUtils.makeExcel(TEExamStudentDto.class, list, fos);
            taskExportCommon.ossUpload(file);
            taskExportCommon.getTbTaskHistory().setSummary("处理成功");
            long end = System.currentTimeMillis();
            log.info("导出考生数据结束,============耗时============:{}秒", (end - start) / 1000);
        } catch (Exception e) {
            log.error("导出报错", e);
            taskExportCommon.setException(true);
			taskExportCommon.getTbTaskHistory().setSummary("处理出错");
        } finally {
            if (Objects.nonNull(fos)) {
                fos.flush();
                fos.close();
            }
            if (oss&&file != null) {
				file.delete();
			}
            taskExportCommon.getTbTaskHistory().setFinishTime(System.currentTimeMillis());
            taskExportCommon.getTbTaskHistory().setStatus(TaskStatusEnum.FINISH);
            taskExportCommon.getTbTaskHistory().setProgress(100.0d);
            //这里写入txt文件
            taskExportCommon.writeExportResultTxt(mkdir.getPath(), "", file);
        }
        return ResultUtil.ok(Collections.singletonMap("success", true));
    }
    
	private String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
}
