package com.usky.issue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usky.common.core.exception.BusinessException;
import com.usky.issue.domain.IssueCloudConfig;
import com.usky.issue.domain.IssueTriggerEvent;
import com.usky.issue.mapper.IssueTriggerEventMapper;
import com.usky.issue.service.CloudConfigService;
import com.usky.issue.service.CloudOperationLogService;
import com.usky.issue.service.CloudTriggerEventService;
import com.usky.issue.service.constant.CloudIntegrationConstants;
import com.usky.issue.service.enums.TriggerEventCodeEnum;
import com.usky.issue.service.support.CloudEntitySupport;
import com.usky.issue.service.vo.TriggerEventItemRequest;
import com.usky.issue.service.vo.TriggerEventResponse;
import com.usky.issue.service.vo.TriggerEventSaveRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 触发事件配置服务实现
 *
 * @author fyc
 * @date 2026-05-21
 */
@Service
public class CloudTriggerEventServiceImpl implements CloudTriggerEventService {

    @Autowired
    private IssueTriggerEventMapper triggerEventMapper;
    @Autowired
    private CloudConfigService cloudConfigService;
    @Autowired
    private CloudOperationLogService operationLogService;

    @Override
    public List<TriggerEventResponse> listEvents() {
        IssueCloudConfig config = cloudConfigService.requireActiveConfig();
        return triggerEventMapper.selectList(new LambdaQueryWrapper<IssueTriggerEvent>()
                        .eq(IssueTriggerEvent::getConfigId, config.getId())
                        .eq(IssueTriggerEvent::getIsDeleted, 0))
                .stream()
                .map(this::toResponse)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEvents(TriggerEventSaveRequest request, String operator, String requestIp) {
        IssueCloudConfig config = cloudConfigService.requireActiveConfig();
        triggerEventMapper.delete(new LambdaQueryWrapper<IssueTriggerEvent>()
                .eq(IssueTriggerEvent::getConfigId, config.getId()));
        for (TriggerEventItemRequest item : request.getEvents()) {
            TriggerEventCodeEnum codeEnum = resolveEventCode(item.getEventCode());
            if (codeEnum == null) {
                throw new BusinessException("未知事件编码: " + item.getEventCode());
            }
            IssueTriggerEvent event = new IssueTriggerEvent();
            event.setConfigId(config.getId());
            event.setTenantId(config.getTenantId());
            event.setEventCode(codeEnum.getCode());
            event.setEventName(codeEnum.getName());
            event.setDescription(codeEnum.getDescription());
            event.setEnabled(Boolean.TRUE.equals(item.getEnabled()) ? 1 : 0);
            CloudEntitySupport.fillOnInsert(event);
            triggerEventMapper.insert(event);
        }
        operationLogService.log(config.getId(), CloudIntegrationConstants.OPERATION_SAVE_TRIGGER,
                "保存触发事件 " + request.getEvents().size() + " 项", operator, requestIp);
    }

    private TriggerEventCodeEnum resolveEventCode(String eventCode) {
        for (TriggerEventCodeEnum e : TriggerEventCodeEnum.values()) {
            if (e.getCode().equalsIgnoreCase(eventCode) || e.name().equalsIgnoreCase(eventCode)) {
                return e;
            }
        }
        return null;
    }

    private TriggerEventResponse toResponse(IssueTriggerEvent event) {
        TriggerEventResponse resp = new TriggerEventResponse();
        resp.setEventCode(event.getEventCode());
        resp.setEventName(event.getEventName());
        resp.setDescription(event.getDescription());
        resp.setEnabled(event.getEnabled() != null && event.getEnabled() == 1);
        return resp;
    }
}
