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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.exception.BusinessException;
import com.tofly.gpsboot.service.comm.IAuditService;
import com.tofly.gpsboot.service.emergency.EmergencyDisService;
import com.tofly.gpsboot.service.emergency.EmergencyService;
import com.tofly.gpsboot.service.mq.IReportMessageService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.report.IReportEmergencyDisServer;
import com.tofly.gpsboot.service.report.IReportPlanMtServer;
import com.tofly.pojo.comm.Audit;
import com.tofly.pojo.emergency.Emergency;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 应急记录处理上报
 * @author Zev
 */
@Service("REPORT_TYPE_EMERGENCY_DIS")
public class IReportEmergencyDisServerImpl implements IReportEmergencyDisServer {

    @Autowired
    private EmergencyService emergencyService;

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IReportMessageService iReportMessageService;

    @Override
    public void report(ReportAuditDto dto) throws BusinessException {
        Long id = dto.getId();
        Emergency emergency = emergencyService.getById(id);
        // 满足条件当前任务正在派工中
        if(!"2".equals(emergency.getState())){
            throw new BusinessException(Constant.EMERGENCY_DIS_REPORT_STATE_ERROR_CODE, Constant.EMERGENCY_DIS_REPORT_STATE_ERROR);
        }else {
            // 先清除审核链已有信息
            auditService.remove(new QueryWrapper<Audit>().lambda()
                    .eq(Audit::getAuditPlanId,id)
                    .eq(Audit::getAuditType,(AuditTypeEnum.AUDIT_TYPE_EMERGENCY_DIS.getCode())));

            Audit audit = new Audit();
            audit.setAuditPlanId(id);
            audit.setAuditType(AuditTypeEnum.AUDIT_TYPE_EMERGENCY_DIS.getCode());
            audit.setAuditState(AuditSateEnum.AUDIT_UNCOMMITTED.getCode());
            audit.setAuditUser(dto.getAuditId());
            audit.setAuditLevel(1);
            auditService.save(audit);
            // 修改当前应急事件状态为 3 待审核
            emergency.setState("3");
            emergencyService.updateById(emergency);
            // 通知审核对象mq消息
            iReportMessageService.reportEmergencyDis(dto);
        }

    }
}
