package com.tuoheng.admin.service.iotequipment.delete;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.IotEquipment;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.IotEquipmentMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 物联设备 业务类
 *
 * @author wanjing
 * @since 2023-11-25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeleteEditIotEquipmentByIdService {

    private final IotEquipmentMapper iotEquipmentMapper;

    public JsonResult deletedById(String id) {
        User user = CurrentUserUtil.getUserInfo();
        JsonResult result = this.check(id);
        if (0 != result.getCode()) {
            log.info("删除物联设备：校验失败：{}", result.getMsg());
            return result;
        }
        Integer rowId = iotEquipmentMapper.deleteById(id);
        if (rowId <= 0) {
            log.info("删除物联设备：失败：{}", result.getMsg());
            return JsonResult.error("删除物联设备失败");
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param id
     * @return
     */
    private JsonResult check(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException("设备Id码为空");
        }
        IotEquipment iotEquipment = iotEquipmentMapper.selectOne(new LambdaQueryWrapper<IotEquipment>()
                .eq(IotEquipment::getId, id)
                .eq(IotEquipment::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isEmpty(iotEquipment)) {
            throw new ServiceException("该设备不存在");
        }
        return JsonResult.success(iotEquipment);
    }

}
