package com.yeejoin.amos.boot.module.jg.biz.refresh.handler;

import com.yeejoin.amos.boot.module.common.api.dao.EsEquipmentDao;
import com.yeejoin.amos.boot.module.common.api.entity.TzsDataRefreshMessage;
import com.yeejoin.amos.boot.module.common.api.service.IDataRefreshHandler;
import com.yeejoin.amos.boot.module.common.biz.refresh.DataRefreshEvent;
import com.yeejoin.amos.boot.module.jg.biz.service.IIdxBizJgInspectionDetectionInfoService;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgMaintenanceRecordInfoServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgUseInfoServiceImpl;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.SafetyProblemTracingServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgInspectionDetectionInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgMaintenanceRecordInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class EquipmentSafetyProblemRefreshHandler implements IDataRefreshHandler {

    private final IdxBizJgUseInfoServiceImpl useInfoService;
    private final IIdxBizJgInspectionDetectionInfoService iIdxBizJgInspectionDetectionInfoService;
    private final EsEquipmentDao esEquipmentDao;
    private final IdxBizJgMaintenanceRecordInfoServiceImpl maintenanceRecordInfoService;
    private final SafetyProblemTracingServiceImpl safetyProblemTracingService;

    @Override
    public String supportType() {
        return "equipment";
    }

    @Override
    public void doRefresh(TzsDataRefreshMessage message) {
        log.info("设备更新安全追溯问题开始，设备id：{}", message.getDataId());
        String record = message.getDataId();
        switch (DataRefreshEvent.Operation.valueOf(message.getOperation())) {
            case DELETE:
                safetyProblemTracingService.deleteBySourceId(record, "问题源被删除");
                break;
            case INSERT:
            case UPDATE:
                Map<String, Object> detail = useInfoService.getBaseMapper().queryDetail(record);
                if(detail == null) {
                    return;
                }
                IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = iIdxBizJgInspectionDetectionInfoService.queryNewestDetailByRecord(record);
                IdxBizJgMaintenanceRecordInfo lastMaintenanceRecordInfo = maintenanceRecordInfoService.queryNewestDetailByRecord(record);
                safetyProblemTracingService.updateBySourceId(record, detail, inspectionDetectionInfo, lastMaintenanceRecordInfo);
                break;
            default:
                log.error("unknown operation: {}", message.getOperation());
        }
    }
}
