package com.hotwj.platform.config.hiddenDanger.strategy;

import com.hotwj.platform.flow.callback.IFlowCallback;
import com.hotwj.platform.flow.event.StartFlowEvent;
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 com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.HotHiddenDangerInspection;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.mapper.HotHiddenDangerInspectionMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

/**
 * 隐患排查流程回调
 *
 * @author shihongwei
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class HiddenDangerCheckCallback implements IFlowCallback {

    private final HotHiddenDangerInspectionMapper inspectMapper;
    private final HotHiddenDangerMapper hiddenDangerMapper;
    private final ApplicationEventPublisher eventPublisher;

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

    @Override
    public void onProcessEnd(String instanceId, String businessId, String flowCode, boolean success) {
        log.info("隐患排查流程结束回调: businessId={}, success={}", businessId, success);
        Long id = Long.parseLong(businessId);
        HotHiddenDangerInspection inspection = inspectMapper.selectById(id);
        if (inspection != null) {
            if (success) {
                inspection.setFlowStatus("APPROVED");
                inspection.setStatus(inspection.getAuditHasDanger() != null && inspection.getAuditHasDanger() == 1L ? 6L : 3L);
            } else {
                inspection.setFlowStatus("REJECTED");
                inspection.setStatus(10L);
                inspection.setInstanceId(null);
                log.info("隐患排查流程被驳回或非正常结束: {}", businessId);
            }
            if (success && inspection.getAuditHasDanger() != null && inspection.getAuditHasDanger() == 1L) {
                createHiddenDangerFlow(inspection);
            }
            inspectMapper.updateById(inspection);
        }
    }

    /**
     * 创建隐患治理流程
     */
    private void createHiddenDangerFlow(HotHiddenDangerInspection inspection) {
        log.info("隐患排查发现隐患，自动创建隐患治理流程，业务ID: {}", inspection.getId());

        HotHiddenDangerBo dangerBo = new HotHiddenDangerBo();
        dangerBo.setCompanyId(inspection.getCompanyId());
        dangerBo.setCheckTime(inspection.getCheckDate());
        dangerBo.setCheckerId(inspection.getCheckerId());
        dangerBo.setCheckerName(inspection.getCheckerName());
        dangerBo.setDescription(inspection.getDangerDesc());
        dangerBo.setEvidenceUrls(inspection.getAttachmentUrl());

        // 生成隐患编号 YH-时间戳
        dangerBo.setDangerNo("YH-" + System.currentTimeMillis() / 1000);

        // 设置评估人
        dangerBo.setEvaluatorId(inspection.getEvaluatorId());
        dangerBo.setEvaluatorName(inspection.getEvaluatorName());

        // 映射隐患来源类型
        dangerBo.setSourceName(inspection.getProjectName());
        dangerBo.setSourceId(String.valueOf(inspection.getId()));
        dangerBo.setSourceType(inspection.getProjectType());
        dangerBo.setDataSource(1L); // 1=日常排查

        // 隐患名称
        String dangerName = "隐患排查";
        dangerBo.setDangerName(dangerName);
        dangerBo.setStatus(0L); // 0=待评估

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

        // 2. 启动隐患治理流程
        String initiator = LoginHelper.getBusinessUserId();
        String rectifierId = String.valueOf(inspection.getEvaluatorId());

        // 使用事件发布解耦
        StartFlowEvent startFlowEvent = new StartFlowEvent(this,
                "HIDDEN_DANGER_GOVERNANCE",
                String.valueOf(danger.getId()),
                inspection.getCompanyId(),
                initiator,
                rectifierId
        );
        eventPublisher.publishEvent(startFlowEvent);

        if (startFlowEvent.getInstanceId() != null) {
            danger.setInstanceId(startFlowEvent.getInstanceId());
            danger.setFlowStatus("SUBMITTED");
            hiddenDangerMapper.updateById(danger);
        }
    }
}
