package com.aegis.emergency.event.service.impl;

import java.util.Date;
import java.util.List;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aegis.common.core.domain.model.LoginUser;
import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.SecurityUtils;
import com.aegis.common.utils.StringUtils;
import com.aegis.emergency.event.domain.EventLog;
import com.aegis.emergency.event.mapper.EventLogMapper;
import com.aegis.emergency.event.service.IEventLogService;
import org.springframework.stereotype.Service;

/**
 * 事件操作日志 Service 实现
 *
 * 统一记录与查询日志
 *
 * @author aegis
 */
@Service
public class EventLogServiceImpl extends ServiceImpl<EventLogMapper, EventLog>
        implements IEventLogService {

    @Override
    public List<EventLog> listByCondition(EventLog condition) {
        LambdaQueryWrapper<EventLog> wrapper = new LambdaQueryWrapper<>();
        if (condition != null) {
            if (condition.getEventId() != null) {
                wrapper.eq(EventLog::getEventId, condition.getEventId());
            }
            if (StringUtils.isNotEmpty(condition.getAction())) {
                wrapper.eq(EventLog::getAction, condition.getAction());
            }
            if (condition.getCreatedAt() != null) {
                wrapper.ge(EventLog::getCreatedAt, condition.getCreatedAt());
            }
        }
        wrapper.orderByDesc(EventLog::getCreatedAt);
        return list(wrapper);
    }

    @Override
    public List<EventLog> listByEventId(Long eventId) {
        if (eventId == null) {
            throw new ServiceException("事件ID不能为空");
        }
        LambdaQueryWrapper<EventLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventLog::getEventId, eventId)
                .orderByDesc(EventLog::getCreatedAt);
        return list(wrapper);
    }

    @Override
    public void recordLog(Long eventId, String action, Object payload) {
        if (eventId == null) {
            throw new ServiceException("事件ID不能为空");
        }
        if (StringUtils.isEmpty(action)) {
            throw new ServiceException("操作类型不能为空");
        }

        EventLog log = new EventLog();
        log.setEventId(eventId);
        log.setAction(action);
        log.setOperatorId(SecurityUtils.getUserId());
        
        // 优先使用昵称，如果昵称为空则使用用户名
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String operatorName = StringUtils.isNotEmpty(loginUser.getUser().getNickName()) 
            ? loginUser.getUser().getNickName() 
            : loginUser.getUser().getUserName();
        log.setOperatorName(operatorName);
        
        log.setCreatedAt(new Date());

        if (payload != null) {
            log.setPayload(JSON.toJSONString(payload));
        }

        save(log);
    }
}