package com.qmth.jkserver.templete.execute;

import cn.hutool.core.date.DateUtil;
import com.qmth.jkserver.constant.SpringContextHolder;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.core.SystemResult;
import com.qmth.jkserver.core.exception.JkServerException;
import com.qmth.jkserver.enums.TaskResultEnum;
import com.qmth.jkserver.model.ExamTask;
import com.qmth.jkserver.model.User;
import com.qmth.jkserver.service.ExamTaskService;
import com.qmth.jkserver.templete.callback.CallbackSyncCloudMark;
import com.qmth.jkserver.templete.service.TaskLogicService;
import com.qmth.jkserver.templete.syncCloudMarkData.AsyncCloudMarkTaskTemplete;
import com.qmth.jkserver.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.*;

/**
 * @Description: 同步云阅卷数据
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/5/11
 */
@Service
public class AsyncCloudMarkTempleteService extends AsyncCloudMarkTaskTemplete {

    private final static Logger log = LoggerFactory.getLogger(AsyncCloudMarkTempleteService.class);

    static final String OBJ_TITLE = "云阅卷的数据";

    /**
     * 同步云阅卷数据
     *
     * @param map
     * @param callbackSyncCloudMark
     * @return
     * @throws IOException
     */
    @Async
    @Override
    public SystemResult cloudMarkTask(Map<String, Object> map, CallbackSyncCloudMark callbackSyncCloudMark) throws Exception {
        ExamTask examTask = (ExamTask) map.get(SystemConstant.TASK);
        User user = (User) map.get(SystemConstant.USER);
        ExamTaskService examTaskService = SpringContextHolder.getBean(ExamTaskService.class);
        examTaskService.updateExamTask(examTask, user);
        StringJoiner stringJoinerSummary = new StringJoiner("\n").add(MessageFormat.format("{0}{1}{2}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), BEGIN_TITLE, OBJ_TITLE));
        try {
            TaskLogicService taskLogicService = SpringContextHolder.getBean(TaskLogicService.class);
            taskLogicService.executeCloudMarkLogic(map);
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), FINISH_TITLE, examTask.getTotalProgress().intValue(), FINISH_SIZE));
            examTask.setResult(TaskResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), EXCEPTION_TITLE, EXCEPTION_DATA, e.getMessage()));
            examTask.setResult(TaskResultEnum.ERROR);
            if (Objects.nonNull(examTask.getTotalProgress()) && Objects.nonNull(examTask.getCompleteProgress())) {
                //计算已完成的进度
                BigDecimal completeProgress = new BigDecimal(examTask.getCompleteProgress()).divide(examTask.getTotalProgress(), 2, BigDecimal.ROUND_HALF_UP);
                examTask.setProgress(completeProgress.multiply(SystemConstant.RATE_BIG_DECIMAL));
            }
            if (e instanceof JkServerException) {
                ResultUtil.error((JkServerException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        } finally {
            // 删除本地临时文件
            List<String> willDeletePath;
            if (Objects.nonNull(map.get(SystemConstant.WILL_DELETE_PATH))){
                willDeletePath = (List<String>) map.get(SystemConstant.WILL_DELETE_PATH);
                for (String path : willDeletePath) {
                    File dir = new File(path);
                    if (dir.exists()){
                        SystemConstant.deleteFolder(dir);
                    }
                }
            }
            //生成txt文件
            examTask.setSummary(stringJoinerSummary.toString());
            super.createTxt(examTask, user);
            if (Objects.nonNull(callbackSyncCloudMark)) {
                callbackSyncCloudMark.callback(map);
            }
        }
        return ResultUtil.ok(map);
    }
}
