package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.entity.TBSyncTask;
import com.qmth.distributed.print.business.mapper.TBSyncTaskMapper;
import com.qmth.distributed.print.business.service.*;
import com.qmth.distributed.print.business.templete.execute.AsyncCloudMarkingTaskService;
import com.qmth.distributed.print.business.templete.execute.AsyncTeachCloudReportService;
import com.qmth.teachcloud.common.bean.result.SyncListResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.PushTypeEnum;
import com.qmth.teachcloud.common.enums.TaskResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @Date: 2021/5/20.
 */
@Service
public class TBSyncTaskServiceImpl extends ServiceImpl<TBSyncTaskMapper, TBSyncTask> implements TBSyncTaskService {

    @Resource
    AsyncCloudMarkingTaskService asyncCloudMarkingTaskService;

    @Resource
    ExamPaperStructureService examPaperStructureService;

    @Resource
    ExamPrintPlanService examPrintPlanService;

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Resource
    AsyncTeachCloudReportService asyncTeachCloudReportService;

    @Resource
    GradeBatchService gradeBatchService;

    @Resource
    GradeBatchPaperService gradeBatchPaperService;

    @Transactional
    @Override
    public TBSyncTask saveTask(Long schoolId, Long objectId, PushTypeEnum type) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        QueryWrapper<TBSyncTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TBSyncTask::getSchoolId, schoolId)
                .eq(TBSyncTask::getObjectId, objectId)
                .eq(TBSyncTask::getType, type);
        TBSyncTask tbSyncTask = this.getOne(queryWrapper);
        Long id = SystemConstant.getDbUuid();
        if (tbSyncTask != null) {
            if (!TaskStatusEnum.FINISH.equals(tbSyncTask.getStatus())) {
                throw ExceptionResultEnum.ERROR.exception("有任务未结束");
            }
            id = tbSyncTask.getId();
            this.removeById(id);
        }
        tbSyncTask = new TBSyncTask();
        tbSyncTask.setId(id);
        tbSyncTask.setSchoolId(schoolId);
        tbSyncTask.setObjectId(objectId);
        tbSyncTask.setType(type);
        tbSyncTask.setStatus(TaskStatusEnum.INIT);
        tbSyncTask.setCreateId(sysUser.getId());
        tbSyncTask.setCreateTime(System.currentTimeMillis());
        this.save(tbSyncTask);
        return tbSyncTask;
    }

    @Override
    public void updateStatusAndResultById(Long id, Long thirdRelateId, TaskStatusEnum status, TaskResultEnum result, String errorMessage) {
        UpdateWrapper<TBSyncTask> tbSyncTaskUpdateWrapper = new UpdateWrapper<>();
        tbSyncTaskUpdateWrapper.lambda().set(TBSyncTask::getStatus, status)
                .set(TBSyncTask::getThirdRelateId, thirdRelateId)
                .set(TBSyncTask::getResult, result)
                .set(TBSyncTask::getErrorMessage, errorMessage)
                .eq(TBSyncTask::getId, id);
        this.update(tbSyncTaskUpdateWrapper);
    }

    @Transactional
    @Override
    public TBSyncTask savePushCommon(PushTypeEnum pushTypeEnum, Map map, SysUser sysUser) {
        SysUser requestUser = Objects.nonNull(sysUser) ? sysUser : (SysUser) ServletUtil.getRequestUser();
        TBSyncTask tbSyncTask = new TBSyncTask(pushTypeEnum,
                TaskStatusEnum.INIT,
                requestUser.getId(),
                requestUser.getSchoolId());

        map.computeIfAbsent(SystemConstant.TB_SYNC_TASK, v -> tbSyncTask);
        map.computeIfAbsent(SystemConstant.USER, v -> requestUser);
        map.computeIfAbsent(SystemConstant.TB_SYNC_TASK_ID, v -> tbSyncTask.getId());
        return tbSyncTask;
    }

    @Override
    public IPage<SyncListResult> query(Long schoolId, TaskStatusEnum status, PushTypeEnum type, TaskResultEnum result, int pageNumber, int pageSize) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Set<Long> orgIds = teachcloudCommonService.listSubOrgIds(null);

        IPage<SyncListResult> page = this.baseMapper.query(new Page<>(pageNumber, pageSize), schoolId, status, type, result, sysUser.getId(), orgIds);
        List<SyncListResult> list = page.getRecords();
        for (SyncListResult syncListResult : list) {
            syncListResult.setStatus(Objects.nonNull(syncListResult.getStatus()) ? TaskStatusEnum.valueOf(syncListResult.getStatus()).getTitle() : null);
            syncListResult.setType(Objects.nonNull(syncListResult.getType()) ? PushTypeEnum.valueOf(syncListResult.getType()).getTitle() : null);
            syncListResult.setResultStr(Objects.nonNull(syncListResult.getResult()) ? TaskResultEnum.valueOf(syncListResult.getResult()).getTitle() : null);
        }
        return page;
    }

    @Override
    public void resync(Long id) {
        TBSyncTask tbSyncTask = this.getById(id);
        if (tbSyncTask == null) {
            throw ExceptionResultEnum.ERROR.exception("任务不存在");
        }
        if (!TaskStatusEnum.FINISH.equals(tbSyncTask.getStatus())) {
            throw ExceptionResultEnum.ERROR.exception("任务同步中");
        }
        if (TaskResultEnum.SUCCESS.equals(tbSyncTask.getResult())) {
            throw ExceptionResultEnum.ERROR.exception("任务同步成功");
        }
        switch (tbSyncTask.getType()) {
            case EXAM_PUSH:
                asyncCloudMarkingTaskService.syncExamAndStudentAndCard(examPrintPlanService.getById(tbSyncTask.getObjectId()), tbSyncTask.getThirdRelateId(), null);
                break;
            case STRUCTURE_GROUP_PUSH:
                asyncCloudMarkingTaskService.syncPaperStructureAndGroup(examPaperStructureService.getById(tbSyncTask.getObjectId()));
                break;
            case PAPER_ANSWER_FILE_PUSH:
                asyncCloudMarkingTaskService.syncPaperAndAnswer(examPaperStructureService.getById(tbSyncTask.getObjectId()));
                break;
            case OBJECTIVE_ANSWER_PUSH:
                asyncCloudMarkingTaskService.syncObjectiveStructure(examPaperStructureService.getById(tbSyncTask.getObjectId()));
                break;
            case GRADE_BATCH_PUSH:
                asyncTeachCloudReportService.syncGradeBatch(gradeBatchService.getById(tbSyncTask.getObjectId()));
                break;
            case PUBLISH:
                asyncTeachCloudReportService.publish(gradeBatchPaperService.getById(tbSyncTask.getObjectId()));
                break;
        }


    }
}
