package com.tuoheng.admin.service.camera.query;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.Camera;
import com.tuoheng.admin.enums.MarkTypeEnum;
import com.tuoheng.admin.mapper.CameraMapper;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 根据Id查询摄像头业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-22
 */
@Slf4j
@Service
public class QueryCameraByIdService {

    @Autowired
    private CameraMapper cameraMapper;

    public JsonResult getOneById(Integer id) {
//        log.info("进入根据Id查询摄像头业务");
        User user = ShiroUtils.getUserInfo();
        Integer tenantId = user.getTenantId();
        JsonResult result = this.check(tenantId, id);
        if (0 != result.getCode()) {
            log.info("进入根据ID查询摄像头业务：校验失败：{}", result.getMsg());
            return result;
        }
        Camera camera = (Camera) result.getData();
        return JsonResult.success(camera);
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param id
     * @return
     */
    private JsonResult check(Integer tenantId, Integer id) {
        // 判断部门id是否为空
        if (Optional.ofNullable(id).orElse(0) == 0) {
            log.info("摄像头ID为空, id:{}", id);
            throw new ServiceException("摄像头ID为空");
        }
        // 判断摄像头是否存在
        Camera camera = cameraMapper.selectOne(new LambdaQueryWrapper<Camera>()
                .eq(Camera::getTenantId, tenantId)
                .eq(Camera::getId, id)
                .eq(Camera::getMark, MarkTypeEnum.VALID));
        if (ObjectUtil.isNull(camera)) {
            log.info("摄像头不存在, id:{}", id);
            throw new ServiceException("摄像头不存在");
        }
        return JsonResult.success(camera);
    }

}
