package com.zsc.edu.gateway.modules.iot.tsl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.iot.tsl.dto.EventDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Event;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.EventMapper;
import com.zsc.edu.gateway.modules.iot.tsl.repo.EventRepository;
import com.zsc.edu.gateway.modules.iot.tsl.service.EventService;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Yao
 */
@Service
@AllArgsConstructor
public class EventServiceImpl extends ServiceImpl<EventRepository, Event> implements EventService {
    private final EventMapper mapper;
    private final ParamService paramService;

    /**
     * 新建物模型事件
     */
    @Override
    @Transactional
    public Event create(EventDto dto) {
        if (baseMapper.findByName(dto.getName()) != null) {
            throw new ConstraintException("该事件已存在！");
        }
        if (dto.getName() == null) {
            throw new ConstraintException("事件名称不能为空！");
        }
        Event event = mapper.toEntity(dto);
        save(event);
        paramService.create(dto.getOutputs(), event.getId(), Param.ForeignType.EVENT);
        return event;
    }
    /**
     * 更新物模型事件
     */
    @Override
    @Transactional
    public Event update(EventDto dto, Long id) {
        if (dto.getName() == null) {
            throw new ConstraintException("事件名称不能为空！");
        }
        Event event = baseMapper.selectById(id);
        mapper.convert(dto, event);
        updateById(event);
        paramService.update(dto.getOutputs(), event.getId());
        return event;
    }

    /**
     * 查询详情
     * @param id Id
     * @return Event
     */
    @Override
    public Event detail(Long id) {
        Event event = baseMapper.selectById(id);
        if (event == null) {
            throw new ConstraintException("该事件不存在！请检查输入ID是否正确！");
        }
        return event;
    }

    /**
     *删除
     */
    @Override
    @Transactional
    public boolean delete(Long id) {
        removeById(id);
        return paramService.delete(id);
    }
}
