/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.coldchain.modular.monitordevicetype.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.coldchain.modular.monitordevice.entity.MonitorDevice;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.coldchain.modular.monitordevicetype.entity.MonitorDeviceType;
import vip.xiaonuo.coldchain.modular.monitordevicetype.mapper.MonitorDeviceTypeMapper;
import vip.xiaonuo.coldchain.modular.monitordevicetype.param.MonitorDeviceTypeAddParam;
import vip.xiaonuo.coldchain.modular.monitordevicetype.param.MonitorDeviceTypeEditParam;
import vip.xiaonuo.coldchain.modular.monitordevicetype.param.MonitorDeviceTypeIdParam;
import vip.xiaonuo.coldchain.modular.monitordevicetype.param.MonitorDeviceTypePageParam;
import vip.xiaonuo.coldchain.modular.monitordevicetype.service.MonitorDeviceTypeService;

import java.util.List;

/**
 * 监控设备型号Service接口实现类
 *
 * @author 黄渊昊
 * @date 2024/11/25 10:15
 **/
@Service
public class MonitorDeviceTypeServiceImpl extends ServiceImpl<MonitorDeviceTypeMapper, MonitorDeviceType> implements MonitorDeviceTypeService {

    @Override
    public Page<MonitorDeviceType> page(MonitorDeviceTypePageParam monitorDeviceTypePageParam) {
        QueryWrapper<MonitorDeviceType> queryWrapper = new QueryWrapper<MonitorDeviceType>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(monitorDeviceTypePageParam.getName())) {
            queryWrapper.lambda().like(MonitorDeviceType::getName, monitorDeviceTypePageParam.getName());
        }
        if (ObjectUtil.isNotEmpty(monitorDeviceTypePageParam.getSensorCount())) {
            queryWrapper.lambda().eq(MonitorDeviceType::getSensorCount, monitorDeviceTypePageParam.getSensorCount());
        }
        if (ObjectUtil.isAllNotEmpty(monitorDeviceTypePageParam.getSortField(), monitorDeviceTypePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(monitorDeviceTypePageParam.getSortOrder());
            queryWrapper.orderBy(true, monitorDeviceTypePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(monitorDeviceTypePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(MonitorDeviceType::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(MonitorDeviceTypeAddParam monitorDeviceTypeAddParam) {
        if (monitorDeviceTypeAddParam.getSensorCount() > 4 || monitorDeviceTypeAddParam.getSensorCount() < 1) {
            throw new CommonException("传感器路数的大小必须在1到4之间");
        }
        MonitorDeviceType monitorDeviceType = BeanUtil.toBean(monitorDeviceTypeAddParam, MonitorDeviceType.class);
        if (this.getByCode(monitorDeviceType.getCode())) {
            throw new CommonException("设备编码已注册使用：{}", monitorDeviceType.getCode());
        }
        if (this.getByName(monitorDeviceType.getName())) {
            throw new CommonException("设备名已注册使用：{}", monitorDeviceType.getName());
        }
        this.save(monitorDeviceType);
    }

    @Override
    public boolean getByName(String name) {
        List<MonitorDeviceType> types = this.list(new LambdaQueryWrapper<MonitorDeviceType>()
                .eq(MonitorDeviceType::getName, name).eq(MonitorDeviceType::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE));
        return !types.isEmpty();
    }

    @Override
    public boolean getByCode(String code) {
        List<MonitorDeviceType> types = this.list(new LambdaQueryWrapper<MonitorDeviceType>()
                .eq(MonitorDeviceType::getCode, code).eq(MonitorDeviceType::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE));
        return !types.isEmpty();
    }

    @Override
    public List<MonitorDeviceType> myList(String sensorType) {
        LambdaQueryWrapper<MonitorDeviceType> queryWrapper = new LambdaQueryWrapper<>();
        if (sensorType != null) {
            queryWrapper.eq(MonitorDeviceType::getSensorType, sensorType);
        }
        queryWrapper.eq(MonitorDeviceType::getDeleteFlag,CommonDeleteFlagEnum.NOT_DELETE);
        return list(queryWrapper);
    }

    @Override
    public MonitorDeviceType getByModelName(String modelName) {
        LambdaQueryWrapper<MonitorDeviceType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MonitorDeviceType::getCode, modelName);
        return getOne(queryWrapper);
    }

    public List<MonitorDeviceType> getTypeByName(String name) {
        return this.list(new LambdaQueryWrapper<MonitorDeviceType>()
                .eq(MonitorDeviceType::getName, name).eq(MonitorDeviceType::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE));
    }

    public List<MonitorDeviceType> getTypeByCode(String code) {
        return this.list(new LambdaQueryWrapper<MonitorDeviceType>()
                .eq(MonitorDeviceType::getCode, code).eq(MonitorDeviceType::getDeleteFlag, CommonDeleteFlagEnum.NOT_DELETE));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MonitorDeviceTypeEditParam monitorDeviceTypeEditParam) {
        MonitorDeviceType monitorDeviceType = this.queryEntity(monitorDeviceTypeEditParam.getId());
        BeanUtil.copyProperties(monitorDeviceTypeEditParam, monitorDeviceType);
        List<MonitorDeviceType> deviceByDeviceName = this.getTypeByName(monitorDeviceType.getName());
        for (MonitorDeviceType deviceType : deviceByDeviceName) {
            if (!deviceType.getId().equals(monitorDeviceTypeEditParam.getId())) {
                throw new CommonException("设备名已注册使用：{}", deviceType.getName());
            }
        }
        List<MonitorDeviceType> deviceByDeviceCode = this.getTypeByCode(monitorDeviceType.getCode());
        for (MonitorDeviceType deviceType : deviceByDeviceCode) {
            if (!deviceType.getId().equals(monitorDeviceTypeEditParam.getId())) {
                throw new CommonException("设备编码已注册使用：{}", deviceType.getCode());
            }
        }
        this.updateById(monitorDeviceType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<MonitorDeviceTypeIdParam> monitorDeviceTypeIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(monitorDeviceTypeIdParamList, MonitorDeviceTypeIdParam::getId));
    }

    @Override
    public MonitorDeviceType detail(MonitorDeviceTypeIdParam monitorDeviceTypeIdParam) {
        return this.queryEntity(monitorDeviceTypeIdParam.getId());
    }

    @Override
    public MonitorDeviceType queryEntity(String id) {
        MonitorDeviceType monitorDeviceType = this.getById(id);
        if (ObjectUtil.isEmpty(monitorDeviceType)) {
            throw new CommonException("监控设备型号不存在，id值为：{}", id);
        }
        return monitorDeviceType;
    }
}
