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.BuildSateEnum;
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.build.BuildService;
import com.tofly.gpsboot.service.build.impl.BulidclearServiceImpl;
import com.tofly.gpsboot.service.mq.IReportMessageService;

import com.tofly.gpsboot.service.report.IReportConstructionSiteEliminationServer;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.build.Build;
import com.tofly.pojo.build.Bulidclear;

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_CONSTRUCTION_SITE_ELIMINATION")
public class ReportConstructionSiteEliminationServerImpl implements IReportConstructionSiteEliminationServer {

    @Autowired
    private BuildService buildService;

    @Autowired
    private BulidclearServiceImpl bulidclearService;

    @Autowired
    private IReportMessageService iReportMessageService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void report(ReportAuditDto dto) {
        Bulidclear info = bulidclearService.getById(dto.getId());
        Build build = buildService.getById(info.getBuildId());
        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(build.getAuditUser());
            dto.setAuditId(build.getAuditUser());
            // 工地主计划状态改为 工地监护消除申请
            build.setState(BuildSateEnum.BUILD_SATE_APPLY_ELIMINATE.getCode());
            buildService.updateById(build);
            bulidclearService.updateById(info);

            // 通知审核对象mq消息
            iReportMessageService.reportTypeConstructionSiteElimination(JSON.toJSONString(dto));
        }else {
            throw new BusinessException(Constant.REPORT_NOT_UNCOMMITTED_CODE,Constant.REPORT_NOT_UNCOMMITTED);
        }


    }
}
