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.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.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.File;
import java.io.FileInputStream;
import java.io.IOException;
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();
        File file = taskImportCommon.getUploadFile();
        taskImportCommon.setTxtList(new ArrayList());
        String timeFormat = taskImportCommon.getTimeFormat();
        taskImportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->开始准备处理导入的考场数据");
        List<LinkedMultiValueMap<Integer, Object>> finalList = ExcelUtil.excelReader(new FileInputStream(file), Lists.newArrayList(RoomCodeImportDto.class), new ExcelCallback() {
            @Override
            public List<LinkedMultiValueMap<Integer, Object>> callback(List<LinkedMultiValueMap<Integer, Object>> finalList, List<LinkedMultiValueMap<Integer, String>> finalColumnNameList) throws IllegalAccessException, IOException {
                List<ExcelError> excelErrorList = new ArrayList<>();
                for (int i = 0; i < finalList.size(); i++) {
                    LinkedMultiValueMap<Integer, Object> map = finalList.get(i);
                    List<Object> roomCodeImportDtoList = map.get(i);
                    for (int y = 0; y < roomCodeImportDtoList.size(); y++) {
                        RoomCodeImportDto roomCodeImportDto = (RoomCodeImportDto) roomCodeImportDtoList.get(y);
                        List<ExcelError> excelErrorTemp = ExcelUtil.checkExcelField(roomCodeImportDto, y, i);
                        if (excelErrorTemp.size() > 0) {
                            excelErrorList.addAll(excelErrorTemp);
                        }
                    }
                }
                if (excelErrorList.size() > 0) {
                    taskImportCommon.getTxtList().add(DateUtil.format(new Date(), timeFormat) + "->数据校验异常：" + JSONObject.toJSONString(excelErrorList));
                    taskImportCommon.setException(true);
                    taskImportCommon.getTbTaskHistory().setFinishTime(System.currentTimeMillis());
                    taskImportCommon.getTbTaskHistory().setProgress(0d);
                    taskImportCommon.getTbTaskHistory().setStatus(TaskStatusEnum.FINISH);
                    taskImportCommon.getTbTaskHistory().setSummary(taskImportCommon.getTxtList().toString());
                    taskImportCommon.writeImportResultTxt(taskImportCommon.getTxtList().toString(), file);
                    throw new BusinessException(JSONObject.toJSONString(excelErrorList));
                }
                return finalList;
            }
        });
        //保存数据到数据库
        if (Objects.nonNull(finalList) && finalList.size() > 0) {
            log.info("开始导入考场数据");
            long start = System.currentTimeMillis();
            try {
                map = templeteLogicService.execImportRoomCodeLogic(finalList, map);
                long end = System.currentTimeMillis();
                log.info("导入考场数据结束,============耗时============:{}秒", (end - start) / 1000);
            } catch (Exception e) {
                log.error("导入报错", e);
                int min = Objects.isNull(map.get("min")) ? 0 : Integer.parseInt(String.valueOf(map.get("min")));
                int y = Objects.isNull(map.get("y")) ? 0 : Integer.parseInt(String.valueOf(map.get("y")));
                taskImportCommon.exception(min, y, e, taskImportCommon.getTxtList());
            } finally {
                //这里写入txt文件
                taskImportCommon.writeImportResultTxt(taskImportCommon.getTxtList().toString(), file);
            }
        }
        return ResultUtil.ok(Collections.singletonMap("success", true));
    }
}
