package com.qmth.exam.reserve.template.execute;

import com.qmth.exam.reserve.bean.Constants;
import com.qmth.exam.reserve.entity.AsyncTaskEntity;
import com.qmth.exam.reserve.enums.AsyncTaskResult;
import com.qmth.exam.reserve.enums.AsyncTaskStatus;
import com.qmth.exam.reserve.enums.AsyncTaskType;
import com.qmth.exam.reserve.service.AsyncTaskService;
import com.qmth.exam.reserve.service.StudentAutoAssignService;
import com.qmth.exam.reserve.template.assign.AsyncAutoAssignTaskTemplate;
import com.qmth.exam.reserve.util.DateUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @Description 自动分配考生
 */
@Service
public class AutoAssignStudentService extends AsyncAutoAssignTaskTemplate {

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

    public static final String OBJ_TITLE = "未完成预约的考生";

    @Autowired
    private AsyncTaskService asyncTaskService;

    @Autowired
    private StudentAutoAssignService studentAutoAssignService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignTask(Map<String, Object> map) {
        AsyncTaskEntity task = (AsyncTaskEntity) map.get(Constants.ASYNC_TASK);
        StringJoiner summary = new StringJoiner("\n").add(
                MessageFormat.format("{0}{1}{2}", DateFormatUtils.format(new Date(), DateUtil.LongDateString), BEGIN_TITLE, OBJ_TITLE));
        task.setStatus(AsyncTaskStatus.RUNNING);
        task.setSummary(summary.toString());
        asyncTaskService.updateById(task);
        try {
            Long taskId = Long.parseLong(map.get("taskId").toString());
            Long operateId = Long.parseLong(map.get("operateId").toString());
            //自动分配
            String message = studentAutoAssignService.autoAssign(taskId, operateId);
            summary.add(message);

            task.setSummary(summary.toString());
            task.setImportFileName(AsyncTaskType.AUTO_ASSIGN.getTitle());
            task.setResult(AsyncTaskResult.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            task.setResult(AsyncTaskResult.ERROR);
            summary.add(MessageFormat.format("{0}{1}{2}{3}", DateFormatUtils.format(new Date(), DateUtil.LongDateString),
                    EXCEPTION_CREATE_TXT_TITLE, EXCEPTION_DATA, e.getMessage()));
            task.setSummary(summary.toString());
        } finally {
            task.setStatus(AsyncTaskStatus.FINISH);
            asyncTaskService.updateById(task);
        }
    }
}
