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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.AuditTypeEnum;
import com.tofly.gpsboot.common.system.PlanStateEnum;
import com.tofly.gpsboot.common.system.ReportSateEnum;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.service.comm.IAuditService;
import com.tofly.gpsboot.service.mq.IReportMessageService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.paln.task.PlanstopService;
import com.tofly.gpsboot.service.report.IReportPlanMtServer;
import com.tofly.gpsboot.service.report.IReportPlanStopServer;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.comm.Audit;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.Planstop;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


/**
 * 维护计划上报
 * @author Zev
 */
@Service("REPORT_TYPE_PLAN_MT")
public class ReportPlanMtServerImpl implements IReportPlanMtServer {

    @Autowired
    private PlanService planService;

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IReportMessageService iReportMessageService;

    @Override
    public void report(ReportAuditDto dto) throws BusinessException {
        Long id = dto.getId();
        Plan plan = planService.getById(id);
        // 满足条件当前任务正在执行中
        if(!PlanStateEnum.PLAN_STATE_BEING_PERFORMED.getCode().equals(plan.getPlanState())){
            throw new BusinessException(Constant.TASK_PLAN_STATE_MT_CODE, Constant.TASK_PLAN_STATE_MT);
        }else {
            // 先清除审核链已有信息
            auditService.remove(new QueryWrapper<Audit>().lambda()
                    .eq(Audit::getAuditPlanId,id)
                    .eq(Audit::getAuditType,(AuditTypeEnum.AUDIT_TYPE_PLAN_MT.getCode())));

            Audit audit = new Audit();
            audit.setAuditPlanId(id);
            audit.setAuditType(AuditTypeEnum.AUDIT_TYPE_PLAN_MT.getCode());
            audit.setAuditState(AuditSateEnum.AUDIT_UNCOMMITTED.getCode());
            audit.setAuditUser(dto.getAuditId());
            audit.setAuditLevel(1);
            auditService.save(audit);
            // 修改当前主任务状态为 2 审核
            plan.setPlanState(PlanStateEnum.PLAN_STATE_NOT_AUDIT.getCode());
            planService.updateById(plan);
            // 通知审核对象mq消息
            iReportMessageService.reportPlanMt(dto);
        }

    }
}
