package com.tofly.gpsboot.service.report.impl;

import com.alibaba.fastjson.JSON;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.AuditSateEnum;
import com.tofly.gpsboot.common.system.PlanStateEnum;
import com.tofly.gpsboot.common.system.ReportSateEnum;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.service.mq.IReportMessageService;

import com.tofly.gpsboot.service.paln.task.PlanstopService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.report.IReportPlanStopServer;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.Planstop;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;


/**
 * 任务暂停上报
 * @author Zev
 */
@Service("REPORT_TYPE_PLAN_STOP")
public class ReportPlanStopServerImpl implements IReportPlanStopServer {

    @Autowired
    private PlanService planService;

    @Autowired
    private PlanstopService planstopService;

    @Autowired
    private IReportMessageService iReportMessageService;

    @Override
    public void report(ReportAuditDto dto) throws BusinessException {
        Long id = dto.getId();
        Planstop info = planstopService.getById(id);
        Plan plan = planService.getById(info.getPlanId());
        // 满足条件当前任务正在执行中
        if(!PlanStateEnum.PLAN_STATE_BEING_PERFORMED.getCode().equals(plan.getPlanState())){
            throw new BusinessException(Constant.TASK_PLAN_STATE_STOP_CODE, Constant.TASK_PLAN_STATE_STOP);
        }else {
            info.setSubmitTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
            info.setSubmitUser(SecurityUtils.getUserId());
            info.setIsSubmit(ReportSateEnum.REPORT_SUBMITTED.getCode());
            info.setAuditResult(AuditSateEnum.AUDIT_UNCOMMITTED.getCode());
            info.setAuditUser(dto.getAuditId());
            planstopService.updateById(info);
            // 修改当前主任务状态为 申请暂停
            plan.setPlanState(PlanStateEnum.PLAN_STATE_APPLY_SUSPENSION.getCode());
            planService.updateById(plan);
            // 通知审核对象mq消息
            iReportMessageService.reportPlanStop(JSON.toJSONString(dto));
        }

    }
}
