package com.hotwj.platform.config.vehicleThreeInspect.callback;

import com.hotwj.platform.config.vehicleThreeInspect.domain.HotVehicleThreeInspect;
import com.hotwj.platform.config.vehicleThreeInspect.mapper.HotVehicleThreeInspectMapper;
import com.hotwj.platform.flow.callback.IFlowCallback;
import com.hotwj.platform.flow.service.ISysFlowService;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.securityManagement.hiddenDanger.domain.HotHiddenDanger;
import com.hotwj.platform.securityManagement.hiddenDanger.domain.bo.HotHiddenDangerBo;
import com.hotwj.platform.securityManagement.hiddenDanger.mapper.HotHiddenDangerMapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 车辆三检流程回调
 *
 * @author shihongwei
 */
@Slf4j
@Component
public class VehicleThreeInspectCallback implements IFlowCallback {

    private final HotVehicleThreeInspectMapper inspectMapper;
    private final HotHiddenDangerMapper hiddenDangerMapper;
    private final ISysFlowService flowService;
    private final IHotSystemNotificationService notificationService;

    public VehicleThreeInspectCallback(HotVehicleThreeInspectMapper inspectMapper,
                                       HotHiddenDangerMapper hiddenDangerMapper,
                                       @Lazy ISysFlowService flowService,
                                       IHotSystemNotificationService notificationService) {
        this.inspectMapper = inspectMapper;
        this.hiddenDangerMapper = hiddenDangerMapper;
        this.flowService = flowService;
        this.notificationService = notificationService;
    }

    @Override
    public String getFlowCode() {
        return "VEHICLE_THREE_INSPECT";
    }

    @Override
    public void onProcessEnd(String instanceId, String businessId, String flowCode, boolean success) {
        log.info("车辆三检流程结束回调: businessId={}, success={}", businessId, success);
        Long id = Long.parseLong(businessId);
        // 去掉try catch，防止事务无法正常回滚
        HotVehicleThreeInspect inspect = inspectMapper.selectById(id);
        if (inspect != null) {
            if (success) {
                inspect.setFlowStatus("APPROVED");
                inspect.setAuditResult("审核通过");
            } else {
                inspect.setFlowStatus("REJECTED");
                // 审核驳回，如果有隐患信息，自动开启隐患治理流程
                createHiddenDangerFlow(inspect);
            }
            inspectMapper.updateById(inspect);
            try {
                sendDriverAuditNotification(inspect, success);
            } catch (Exception e) {
                log.warn("发送车辆三检审核结果通知失败 inspectId={} driverId={}", inspect.getId(), inspect.getDriverId(), e);
            }
        }
    }

    /**
     * 创建隐患治理流程
     */
    private void createHiddenDangerFlow(HotVehicleThreeInspect inspect) {
        if (inspect.getHasHiddenDanger() != null && inspect.getHasHiddenDanger() == 1L) {
            log.info("车辆三检存在隐患，自动创建隐患治理流程，业务ID: {}", inspect.getId());

            HotHiddenDangerBo hiddenDangerBo = new HotHiddenDangerBo();
            hiddenDangerBo.setCompanyId(inspect.getCompanyId());
            hiddenDangerBo.setCheckTime(new Date());
            hiddenDangerBo.setCheckerId(String.valueOf(inspect.getAuditorId()));
            hiddenDangerBo.setCheckerName(inspect.getAuditorName());
            hiddenDangerBo.setDescription(inspect.getAuditResult());
            hiddenDangerBo.setEvidenceUrls(inspect.getAttachImgUrl());
            hiddenDangerBo.setDangerNo("YH-" + System.currentTimeMillis() / 1000);
            hiddenDangerBo.setSourceName("车辆");
            hiddenDangerBo.setSourceId(String.valueOf(inspect.getId()));
            hiddenDangerBo.setSourceType(2L);
            hiddenDangerBo.setDataSource(2L);
            hiddenDangerBo.setDangerName("车辆三检治理");
            hiddenDangerBo.setStatus(0L);

            HotHiddenDanger danger = MapstructUtils.convert(hiddenDangerBo, HotHiddenDanger.class);
            hiddenDangerMapper.insert(danger);

            // 启动隐患治理流程
            // 发起人为审核人(发现隐患的人)
            String initiator = String.valueOf(inspect.getAuditorId());
            // 默认整改人也先设置为审核人，或者留空等待指派
            String rectifierId = String.valueOf(inspect.getEvaluatorId());

            String instanceId = flowService.startFlow(
                    "HIDDEN_DANGER_GOVERNANCE",
                    String.valueOf(danger.getId()),
                    inspect.getCompanyId(),
                    initiator,
                    rectifierId
            );
            danger.setInstanceId(instanceId);
            danger.setEvaluatorId(inspect.getEvaluatorId());
            danger.setFlowStatus("SUBMITTED");
            hiddenDangerMapper.updateById(danger);
        }
    }

    private void sendDriverAuditNotification(HotVehicleThreeInspect inspect, boolean success) {
        if (inspect == null || StringUtils.isBlank(inspect.getDriverId())) {
            return;
        }
        HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
        bos.setLevel("普通");
        bos.setContent(buildDriverAuditNotificationContent(inspect, success));
        bos.setSourceType("车辆管理");
        bos.setSenderType("SYSTEM");
        bos.setReceiverType("驾驶员");
        bos.setReceiverIds(java.util.Collections.singletonList(inspect.getDriverId()));
        bos.setIsDeleted(0L);
        notificationService.insertByBo(bos);
    }

    private String buildDriverAuditNotificationContent(HotVehicleThreeInspect inspect, boolean success) {
        String phaseName = getPhaseName(inspect.getInspectPhase());
        if (success) {
            return "您的车辆三检【" + phaseName + "】已审核通过，请及时查看。";
        }
        String rejectReason = StringUtils.trimToEmpty(inspect.getRejectReason());
        if (StringUtils.isNotBlank(rejectReason)) {
            return "您的车辆三检【" + phaseName + "】未通过，不通过原因：" + rejectReason;
        }
        String auditResult = StringUtils.trimToEmpty(inspect.getAuditResult());
        if (StringUtils.isNotBlank(auditResult)) {
            return "您的车辆三检【" + phaseName + "】未通过，审核意见：" + auditResult;
        }
        return "您的车辆三检【" + phaseName + "】未通过，请及时查看审核意见。";
    }

    private String getPhaseName(Long phase) {
        if (phase == null) {
            return "未知阶段";
        }
        if (phase == 1L) {
            return "出车前检查";
        }
        if (phase == 2L) {
            return "行车中检查";
        }
        if (phase == 3L) {
            return "收车后检查";
        }
        return "未知阶段";
    }
}
