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

import cn.hutool.core.date.DateUtil;
import cn.hutool.cron.TaskTable;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.boot.api.exception.ApiException;
import com.qmth.distributed.print.business.entity.TBTaskPdf;
import com.qmth.distributed.print.business.mapper.TBTaskPdfMapper;
import com.qmth.distributed.print.business.service.TBTaskPdfService;
import com.qmth.teachcloud.common.bean.result.TaskPdfResult;
import com.qmth.teachcloud.common.bean.result.TbTaskDetailResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.*;
import com.qmth.teachcloud.common.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * <p>
 * 导入导出任务表 服务实现类
 * </p>
 *
 * @author xf
 * @since 2024-02-06
 */
@Service
public class TBTaskPdfServiceImpl extends ServiceImpl<TBTaskPdfMapper, TBTaskPdf> implements TBTaskPdfService {

    @Override
    public boolean updateStatusById(TaskStatusEnum status, TaskResultEnum result, String summary, Long id) {
        UpdateWrapper<TBTaskPdf> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<TBTaskPdf> lambda = updateWrapper.lambda();
        lambda.set(TBTaskPdf::getStatus, status)
                .set(TBTaskPdf::getResult, result);
        if (StringUtils.isNotBlank(summary)) {
            lambda.set(TBTaskPdf::getSummary, status);
        }
        lambda.eq(TBTaskPdf::getId, id);
        return this.update(updateWrapper);
    }

    @Override
    public TBTaskPdf saveTask(TbTaskDetailResult tbTaskDetailResult, Long printPlanId, SysUser user, Long examDetailId) {
        try {
            TBTaskPdf tbTaskPdf = this.getById(examDetailId);
            if (tbTaskPdf == null) {
                tbTaskPdf = new TBTaskPdf(examDetailId, user.getSchoolId(), tbTaskDetailResult.getSemesterId(), tbTaskDetailResult.getExamId(), printPlanId, tbTaskDetailResult.getCourseNameCode(), tbTaskDetailResult.getPaperNumber(), user.getId());
                this.save(tbTaskPdf);
            } else {
                if (!TaskStatusEnum.RUNNING.equals(tbTaskPdf.getStatus())) {
                    tbTaskPdf.setStatus(TaskStatusEnum.INIT);
                    tbTaskPdf.setResult(null);
                    tbTaskPdf.setSummary(MessageFormat.format("{0}{1}{2}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), "->", "PDF待生成"));
                    this.updateById(tbTaskPdf);
                }
            }
            return tbTaskPdf;
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return null;
    }

    @Override
    public void resetRunningCreatePdf(Long id, CreatePdfTypeEnum type) {
        TBTaskPdf tbTaskPdf = this.getById(id);
        if (TaskStatusEnum.RUNNING.equals(tbTaskPdf.getStatus())) {
            throw ExceptionResultEnum.ERROR.exception("任务正在生成中，请稍后再试");
        }
        tbTaskPdf.setStatus(TaskStatusEnum.INIT);
        tbTaskPdf.setCreateType(type);
        tbTaskPdf.setResult(null);
        tbTaskPdf.setSummary(MessageFormat.format("{0}{1}{2}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), "->", "重置成功，PDF待生成"));
        this.updateById(tbTaskPdf);
    }

    @Override
    public int countRunningByExamDetailIds(List<Long> examDetailIds) {
        QueryWrapper<TBTaskPdf> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(TBTaskPdf::getId, examDetailIds)
                .eq(TBTaskPdf::getStatus, TaskStatusEnum.RUNNING);
        return this.count(queryWrapper);
    }

    @Override
    public IPage<TaskPdfResult> pageData(Page<TaskPdfResult> page, Long examId, String printPlanId, String courseCode, String paperNumber, TaskStatusEnum status, TaskResultEnum result, String examPlace, String examRoom, Long examStartTime, Long examEndTime) {
        if (examId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择考试");
        }
        return this.baseMapper.pageData(page, examId, printPlanId, courseCode, paperNumber, status, result, examPlace, examRoom, examStartTime, examEndTime);
    }

    @Override
    public List<TBTaskPdf> listWaitingTask() {
        QueryWrapper<TBTaskPdf> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TBTaskPdf::getStatus, TaskStatusEnum.INIT)
                .orderByAsc(TBTaskPdf::getSchoolId)
                .orderByAsc(TBTaskPdf::getId);
        return this.list(queryWrapper);
    }

    @Override
    public boolean countByPrintPlanIdAndEntityId(Long schoolId, Long printPlanId) {
        QueryWrapper<TBTaskPdf> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(TBTaskPdf::getStatus, TaskStatusEnum.FINISH);
        if (Objects.nonNull(schoolId)) {
            queryWrapper.lambda().eq(TBTaskPdf::getSchoolId, schoolId);
        }
        if (Objects.nonNull(printPlanId)) {
            queryWrapper.lambda().eq(TBTaskPdf::getPrintPlanId, printPlanId);
        }
        return this.count(queryWrapper) == 0;
    }
}
