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.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.report.IReportHiddenTroubleServer;
import com.tofly.gpsboot.service.trouble.TroubleService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.trouble.Trouble;

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


import java.time.LocalDateTime;

/**
 * 隐患上报 实现类
 * @author Zev
 */
@Service("REPORT_TYPE_HIDDEN_TROUBLE")
public class ReportHiddenTroubleServerImpl implements IReportHiddenTroubleServer {

    @Autowired
    private TroubleService troubleService;

    @Autowired
    private IReportMessageService iReportMessageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void report(ReportAuditDto dto) {
        Long id = dto.getId();
        Trouble info = troubleService.getById(id);

        String isSubmit = info.getIsSubmit();
        String auditResult = info.getAuditResult();
        // 上报条件 1.当前对象未上报
        // 2.当前对象已上报 审核状态为不通过
        if(ReportSateEnum.REPORT_UNCOMMITTED.getCode().equals(isSubmit) || AuditSateEnum.AUDIT_NO.getCode().equals(auditResult)){
            // 修改当前对象上报状态为 已上报,上报时间,修改审核状态为 未审批
            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());
            troubleService.updateById(info);

            iReportMessageService.reportTypeHiddenPlan(JSON.toJSONString(dto));
        }else {
            throw new BusinessException(Constant.REPORT_NOT_UNCOMMITTED_CODE,Constant.REPORT_NOT_UNCOMMITTED);
        }


    }
}
