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

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.User;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.IotEquipmentMapper;
import com.tuoheng.admin.request.iotequipment.AddIotEquipmentRequest;
import com.tuoheng.admin.request.iotequipment.EditIotEquipmentRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.DateUtils;
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 EditIotEquipmentService {

    private final IotEquipmentMapper iotEquipmentMapper;

    public JsonResult edit(EditIotEquipmentRequest request) {
        User user = CurrentUserUtil.getUserInfo();
        JsonResult result = this.check(user.getTenantId(), request);
        if (0 != result.getCode()) {
            log.info("修改物联设备：校验失败：{}", result.getMsg());
            return result;
        }
        IotEquipment iotEquipment = IotEquipmentConverMapper.INSTANCE.fromEditIotEquipmentToIotEquipment(request);
        iotEquipment.setUpdateUser(user.getId());
        iotEquipment.setUpdateTime(DateUtils.now());
        Integer rowId = iotEquipmentMapper.updateById(iotEquipment);
        if (rowId <= 0) {
            log.info("修改物联设备：失败：{}", result.getMsg());
            return JsonResult.error("修改物联设备失败");
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private JsonResult check(String tenantId, EditIotEquipmentRequest request) {
        if (StringUtils.isEmpty(request.getCode())) {
            throw new ServiceException("设备编码为空");
        }
        if (StringUtils.isEmpty(request.getName())) {
            throw new ServiceException("设备名称为空");
        }
        if (StringUtils.isEmpty(request.getDeptId())) {
            throw new ServiceException("部门Id为空");
        }
        if (StringUtils.isEmpty(request.getRoadId())) {
            throw new ServiceException("高速为空");
        }
        if (StringUtils.isEmpty(request.getSectionId())) {
            throw new ServiceException("路段为空");
        }
        if (StringUtils.isEmpty(request.getLocation())) {
            throw new ServiceException("位置为空");
        }
        if (StringUtils.isEmpty(request.getLongitude()) || StringUtils.isEmpty(request.getLatitude())) {
            throw new ServiceException("经纬度为空");
        }
        if (StringUtils.isEmpty(request.getPlayUrl())) {
            throw new ServiceException("设备地址为空");
        }
        IotEquipment iotEquipment = iotEquipmentMapper.selectOne(new LambdaQueryWrapper<IotEquipment>()
                .eq(IotEquipment::getId, request.getId())
                .eq(IotEquipment::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isEmpty(iotEquipment)) {
            throw new ServiceException("该设备不存在");
        }

        String code = iotEquipment.getCode();
        if (!StringUtils.isEmpty(code)) {
            if (!request.getCode().equals(code)) {   //不相等  说明这次用户要修改设备编码
                //在修改前判断  用户传来的设备编号在数据库中是否已经存在
                IotEquipment equipment = iotEquipmentMapper.selectOne(new LambdaQueryWrapper<IotEquipment>()
                        .eq(IotEquipment::getTenantId, tenantId)
                        .eq(IotEquipment::getDeptId, request.getDeptId())
                        .eq(IotEquipment::getCode, request.getCode())
                        .eq(IotEquipment::getMark, MarkEnum.VALID.getCode()));
                if (ObjectUtil.isNotEmpty(equipment)) {
                    throw new ServiceException("该部门下已存在该编号设备");
                }
            }
        }

        return JsonResult.success();
    }

    /**
     * 启用、禁用
     *
     * @param id
     * @param status
     * @return
     */
    public JsonResult isEnabled(String id, int status) {
        JsonResult result = this.check1(id, status);

        if (0 != result.getCode()) {
            log.info("物联设备状态：校验失败：{}", result.getMsg());
            return result;
        }

        IotEquipment equipment = new IotEquipment();
        equipment.setId(id);
        equipment.setStatus(status);
        int rowId = iotEquipmentMapper.updateById(equipment);
        if (rowId <= 0) {
            log.info("启用，禁用算法：失败：{}", result.getMsg());
            return JsonResult.error("启用，禁用算法：失败");
        }
        return JsonResult.success();
    }

    /**
     * 检查启用/禁用参数
     *
     * @param id
     * @param status
     * @return
     */
    private JsonResult check1(String id, int status) {
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException("设备Id码为空");
        }
        if (String.valueOf(status).equals("")) {
            throw new ServiceException("设备状态为空");
        }

        if (1 != status && 0 != status) {
            throw new ServiceException("无法修改状态，状态只有启用或者禁用两种！");
        }

        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);
    }
}
