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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.gateway.exception.ConstraintException;
import com.zsc.edu.gateway.modules.iot.product.dto.ProductDto;
import com.zsc.edu.gateway.modules.iot.product.entity.Product;
import com.zsc.edu.gateway.modules.iot.product.mapper.ProductMapper;
import com.zsc.edu.gateway.modules.iot.product.repo.ProductRepository;
import com.zsc.edu.gateway.modules.iot.product.service.ProductService;
import com.zsc.edu.gateway.modules.iot.tsl.entity.Param;
import com.zsc.edu.gateway.modules.iot.tsl.service.ParamService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author zhaung
 */
@AllArgsConstructor
@Service
public class ProductServiceImpl extends ServiceImpl<ProductRepository, Product> implements ProductService {
    private final ProductMapper mapper;
    private final ParamService paramService;

    /**
     * 新建产品
     */
    @Override
    @Transactional
    public Product create(ProductDto dto) {
        if (baseMapper.findByName(dto.getName()) != null) {
            throw new ConstraintException("该设备已存在！");
        }
        if (dto.getName() == null) {
            throw new ConstraintException("设备名称不能为空！");
        }
        Product product = mapper.toEntity(dto);
        save(product);
        if (dto.getParams() != null) {
            paramService.create(dto.getParams(), product.getId(), Param.ForeignType.PRODUCT);
        }
        return product;
    }
    /**
     * 更新产品
     */
    @Override
    @Transactional
    public Product update(ProductDto dto, Long id) {
        if (dto.getName() == null) {
            throw new ConstraintException("设备名称不能为空！");
        }
        Product product = baseMapper.selectById(id);
        mapper.convert(dto, product);
        updateById(product);
        paramService.update(dto.getParams(), product.getId());
        return product;
    }

    @Override
    public Product detail(Long id) {
        Product product = baseMapper.selectById(id);
        if (product == null) {
            throw new RuntimeException("产品不存在！请检查产品ID是否正确");
        }
        return product;
    }

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