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.ParamDto;
import com.zsc.edu.gateway.modules.iot.tsl.dto.ServeDto;
import com.zsc.edu.gateway.modules.iot.tsl.entity.*;
import com.zsc.edu.gateway.modules.iot.tsl.mapper.ServeMapper;
import com.zsc.edu.gateway.modules.iot.tsl.repo.ServeRepository;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import com.zsc.edu.gateway.modules.iot.tsl.service.ServeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 15864
 */
@AllArgsConstructor
@Service
public class ServeServiceImpl extends ServiceImpl<ServeRepository, Serve> implements ServeService {

    private final ServeMapper mapper;
    private final ParamService paramService;
    /**
     * 新建功能
     */
    @Override
    @Transactional
    public Serve create(ServeDto dto) {
        if (baseMapper.findByName(dto.getName()) != null) {
            throw new ConstraintException("该服务已存在！");
        }
        if (dto.getName() == null) {
            throw new ConstraintException("服务名称不能为空！");
        }
        Serve serve = mapper.toEntity(dto);
        save(serve);
        List<ParamDto> params = new ArrayList<>(dto.getInputs());
        params.addAll(dto.getOutputs());
        paramService.create(params, serve.getId(), Param.ForeignType.SERVE);
        return serve;
    }
    /**
     * 更新功能
     */
    @Override
    @Transactional
    public Serve update(ServeDto dto, Long id) {
        if (dto.getName() == null) {
            throw new ConstraintException("服务名称不能为空！");
        }
        Serve serve = baseMapper.selectById(id);
        mapper.convert(dto, serve);
        updateById(serve);
        List<ParamDto> params = new ArrayList<>(dto.getInputs());
        params.addAll(dto.getOutputs());
        paramService.update(params, serve.getId());
        return serve;
    }

    /**
     * 查询详情
     * @param id 主键
     * @return Serve
     */
    @Override
    public Serve detail(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (serve == null) {
            throw new ConstraintException("该服务不存在！请检查输入ID是否正确！");
        }
        return serve;
    }

    /**
     * 删除功能
     *
     * @param id serveId
     * @return true
     */
    @Override
    @Transactional
    public Boolean delete(Long id) {
        removeById(id);
        return paramService.delete(id);
    }
}
