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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.conver.IotEquipmentConverMapper;
import com.tuoheng.admin.entity.IotEquipment;
import com.tuoheng.admin.entity.RoadInformation;
import com.tuoheng.admin.entity.Section;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.IotEquipmentMapper;
import com.tuoheng.admin.mapper.RoadInformationMapper;
import com.tuoheng.admin.mapper.SectionMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.IotEquipmentVo;
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 QueryEditIotEquipmentByIdService {

    private final IotEquipmentMapper iotEquipmentMapper;

    private final RoadInformationMapper roadInformationMapper;

    private final SectionMapper sectionMapper;

    public JsonResult getInfoById(String id) {
        User user = CurrentUserUtil.getUserInfo();
        JsonResult result = this.check(id);
        if (0 != result.getCode()) {
            log.info("修改物联设备：校验失败：{}", result.getMsg());
            return result;
        }
        IotEquipment iotEquipment = (IotEquipment) result.getData();

        IotEquipmentVo iotEquipmentVo = IotEquipmentConverMapper.INSTANCE.fromIotEquipmentToIotEquipmentVo(iotEquipment);
        if (StringUtils.isNotEmpty(iotEquipmentVo.getRoadId())) {
            RoadInformation roadInformation = roadInformationMapper.selectById(iotEquipmentVo.getRoadId());
            if (ObjectUtil.isNotEmpty(roadInformation)) {
                iotEquipmentVo.setRoadName(roadInformation.getName());
            }
        }
        return JsonResult.success(iotEquipmentVo);
    }

    /**
     * 检查参数
     *
     * @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);
    }

}
