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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.entity.ExamPrintPlan;
import com.qmth.distributed.print.business.entity.TBSyncTask;
import com.qmth.distributed.print.business.mapper.TBSyncTaskMapper;
import com.qmth.distributed.print.business.service.TBSyncTaskService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import org.springframework.stereotype.Service;

/**
 * @Date: 2021/5/20.
 */
@Service
public class TBSyncTaskServiceImpl extends ServiceImpl<TBSyncTaskMapper, TBSyncTask> implements TBSyncTaskService {
    @Override
    public TBSyncTask saveTask(ExamPrintPlan examPrintPlan) {
        QueryWrapper<TBSyncTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TBSyncTask::getSchoolId, examPrintPlan.getSchoolId())
                .eq(TBSyncTask::getPrintPlanId, examPrintPlan.getId())
                .ne(TBSyncTask::getStatus, TaskStatusEnum.FINISH);
        TBSyncTask tbSyncTask = this.getOne(queryWrapper);
        if (tbSyncTask != null) {
            throw ExceptionResultEnum.ERROR.exception("计划下有数据正在同步");
        } else {
            tbSyncTask = new TBSyncTask();
            tbSyncTask.setId(SystemConstant.getDbUuid());
            tbSyncTask.setSchoolId(examPrintPlan.getSchoolId());
            tbSyncTask.setPrintPlanId(examPrintPlan.getId());
            tbSyncTask.setPrintPlanName(examPrintPlan.getName());
            tbSyncTask.setStatus(TaskStatusEnum.INIT);
            tbSyncTask.setCreateTime(System.currentTimeMillis());
        }
        this.save(tbSyncTask);
        return tbSyncTask;
    }
}
