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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.ExamStudentImportDto;
import com.qmth.themis.business.dto.RoomCodeImportDto;
import com.qmth.themis.business.enums.TaskStatusEnum;
import com.qmth.themis.business.templete.TaskImportCommon;
import com.qmth.themis.business.templete.TaskImportTemplete;
import com.qmth.themis.business.templete.service.TempleteLogicService;
import com.qmth.themis.business.util.ExcelCallback;
import com.qmth.themis.business.util.ExcelError;
import com.qmth.themis.business.util.ExcelUtil;
import com.qmth.themis.common.contanst.Constants;
import com.qmth.themis.common.exception.BusinessException;
import com.qmth.themis.common.util.Result;
import com.qmth.themis.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

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

    @Resource
    TempleteLogicService templeteLogicService;

    /**
     * 考场导入模版
     *
     * @param map
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public Result importTask(Map<String, Object> map) throws IOException {
        TaskImportCommon taskImportCommon = new TaskImportCommon(map);
        taskImportCommon.init();
        InputStream inputStream = taskImportCommon.getUploadFileInputStream();
        taskImportCommon.setTxtList(new ArrayList());
        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), Constants.DEFAULT_DATE_PATTERN) + "->开始准备处理导入的考场数据");
        try {
            List<LinkedMultiValueMap<Integer, Object>> finalList = ExcelUtil.excelReader(inputStream, Lists.newArrayList(RoomCodeImportDto.class), new ExcelCallback() {
                @Override
                public List<LinkedMultiValueMap<Integer, Object>> callback(List<LinkedMultiValueMap<Integer, Object>> finalList, List<LinkedMultiValueMap<Integer, String>> finalColumnNameList, List<LinkedMultiValueMap<Integer, ExcelError>> finalExcelErrorList) throws IllegalAccessException, IOException {
                    List<ExcelError> excelErrorList = new ArrayList<>();
                    if (finalExcelErrorList.size() > 0) {
                        for (int i = 0; i < finalExcelErrorList.size(); i++) {
                            excelErrorList.addAll(finalExcelErrorList.get(i).get(i));
                        }
                    }
                    for (int i = 0; i < finalList.size(); i++) {
                        LinkedMultiValueMap<Integer, Object> map = finalList.get(i);
                        List<Object> examStudentImportDtoList = map.get(i);
                        for (int y = 0; y < examStudentImportDtoList.size(); y++) {
                            RoomCodeImportDto roomCodeImportDto = (RoomCodeImportDto) examStudentImportDtoList.get(y);
                            excelErrorList.addAll(ExcelUtil.checkExcelField(roomCodeImportDto, y, i));
                        }
                    }
                    if (excelErrorList.size() > 0) {
                        taskImportCommon.setException(true);
                        taskImportCommon.getTbTaskHistory().setFinishTime(System.currentTimeMillis());
                        taskImportCommon.getTbTaskHistory().setProgress(0d);
                        taskImportCommon.getTbTaskHistory().setStatus(TaskStatusEnum.FINISH);
                        taskImportCommon.getTbTaskHistory().setSummary(taskImportCommon.getTxtList().toString());
                        throw new BusinessException(JSONObject.toJSONString(excelErrorList));
                    }
                    return finalList;
                }
            });
            //保存数据到数据库
            if (Objects.nonNull(finalList) && finalList.size() > 0) {
                log.info("开始导入考场数据");
                long start = System.currentTimeMillis();
                map = templeteLogicService.execImportRoomCodeLogic(finalList, map);
                long end = System.currentTimeMillis();
                log.info("导入考场数据结束,============耗时============:{}秒", (end - start) / 1000);
            }
        } catch (Exception e) {
            log.error("导入报错", e);
            int line = Objects.isNull(map.get("line")) ? 0 : Integer.parseInt(String.valueOf(map.get("line")));
            taskImportCommon.exception(line, e, taskImportCommon.getTxtList());
        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
            //这里写入txt文件
            taskImportCommon.writeImportResultTxt(taskImportCommon.getTxtList().toString());
        }
        return ResultUtil.ok(true);
    }
}

