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.PlancancleService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.report.IReportPlanDisuseServer;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.Plancancle;

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


import java.time.LocalDateTime;

/**
 * 任务作废上报
 * @author Zev
 */
@Service("REPORT_TYPE_PLAN_DISUSE")
public class ReportPlanDisuseServerImpl implements IReportPlanDisuseServer {

    @Autowired
    private PlanService planService;

    @Autowired
    private PlancancleService plancancleService;

    @Autowired
    private IReportMessageService iReportMessageService;

    @Override
    public void report(ReportAuditDto dto) throws BusinessException {
        Long id = dto.getId();
        Plancancle info = plancancleService.getById(id);
        Plan plan = planService.getById(info.getPlanId());
        // 满足条件当前任务正在执行中
        if(!PlanStateEnum.PLAN_STATE_BEING_PERFORMED.getCode().equals(plan.getPlanState())){
            throw new BusinessException(Constant.PLAN_UPDATE_REPORT_UNCOMMITTED_CODE,Constant.PLAN_UPDATE_REPORT_UNCOMMITTED);
        }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());
            plancancleService.updateById(info);
            // 修改当前任务状态为 申请作废
            plan.setPlanState(PlanStateEnum.PLAN_STATE_APPLY_CANCELLATION.getCode());
            planService.updateById(plan);
            // 通知审核对象mq消息
            iReportMessageService.reportPlanDisuse(JSON.toJSONString(dto));
        }


    }
}
