package org.dromara.rfid.service.impl;

import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.rfid.domain.bo.RfidDeviceBo;
import org.dromara.rfid.domain.vo.RfidDeviceVo;
import org.dromara.rfid.domain.RfidDevice;
import org.dromara.rfid.domain.RfidReadRecord;
import org.dromara.rfid.mapper.RfidDeviceMapper;
import org.dromara.rfid.mapper.RfidReadRecordMapper;
import org.dromara.rfid.service.IRfidDeviceService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 设备信息Service业务层处理
 *
 * @author zch
 * @date 2025-11-25
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class RfidDeviceServiceImpl implements IRfidDeviceService {

    private final RfidDeviceMapper baseMapper;

    private final RfidReadRecordMapper rfidReadRecordMapper;

    /**
     * 查询设备信息
     *
     * @param id 主键
     * @return 设备信息
     */
    @Override
    public RfidDeviceVo queryById(Long id){
        return baseMapper.selectCustomRfidDeviceVoById(id);
    }

    /**
     * 分页查询设备信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备信息分页列表
     */
    @Override
    public TableDataInfo<RfidDeviceVo> queryPageList(RfidDeviceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<RfidDevice> lqw = buildQueryWrapper(bo);
        // 使用自定义 Mapper XML + MyBatis-Plus Wrapper 进行分页查询
        Page<RfidDeviceVo> result = baseMapper.selectCustomRfidDeviceVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的设备信息列表
     *
     * @param bo 查询条件
     * @return 设备信息列表
     */
    @Override
    public List<RfidDeviceVo> queryList(RfidDeviceBo bo) {
        LambdaQueryWrapper<RfidDevice> lqw = buildQueryWrapper(bo);
        // 使用自定义 Mapper XML + MyBatis-Plus Wrapper 查询列表
        return baseMapper.selectCustomRfidDeviceVoList(lqw);
    }

    @Override
    public long count() {
        return baseMapper.countCustomRfidDevice(Wrappers.<RfidDevice>lambdaQuery());
    }

    @Override
    public long count(LambdaQueryWrapper<RfidDevice> queryWrapper) {
        LambdaQueryWrapper<RfidDevice> wrapper = queryWrapper;
        if (wrapper == null) {
            wrapper = Wrappers.lambdaQuery();
        }
        return baseMapper.countCustomRfidDevice(wrapper);
    }

    private LambdaQueryWrapper<RfidDevice> buildQueryWrapper(RfidDeviceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<RfidDevice> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(RfidDevice::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceCode()), RfidDevice::getDeviceCode, bo.getDeviceCode());
        lqw.like(StringUtils.isNotBlank(bo.getDeviceName()), RfidDevice::getDeviceName, bo.getDeviceName());
        lqw.eq(bo.getLocationId() != null, RfidDevice::getLocationId, bo.getLocationId());
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceAddress()), RfidDevice::getDeviceAddress, bo.getDeviceAddress());
        lqw.eq(bo.getDevicePort() != null, RfidDevice::getDevicePort, bo.getDevicePort());
        lqw.eq(bo.getReadFrequency() != null, RfidDevice::getReadFrequency, bo.getReadFrequency());
        lqw.eq(StringUtils.isNotBlank(bo.getOnlineStatus()), RfidDevice::getOnlineStatus, bo.getOnlineStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getAlarmStatus()), RfidDevice::getAlarmStatus, bo.getAlarmStatus());
        if (StringUtils.isNotBlank(bo.getIsMarked())) {
            lqw.apply("t.is_marked = {0}", bo.getIsMarked());
        }
        lqw.eq(StringUtils.isNotBlank(bo.getCreatedBy()), RfidDevice::getCreatedBy, bo.getCreatedBy());
        lqw.eq(bo.getCreatedAt() != null, RfidDevice::getCreatedAt, bo.getCreatedAt());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdatedBy()), RfidDevice::getUpdatedBy, bo.getUpdatedBy());
        lqw.eq(bo.getUpdatedAt() != null, RfidDevice::getUpdatedAt, bo.getUpdatedAt());
        return lqw;
    }

    /**
     * 新增设备信息
     *
     * @param bo 设备信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(RfidDeviceBo bo) {
        RfidDevice add = MapstructUtils.convert(bo, RfidDevice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改设备信息
     *
     * @param bo 设备信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(RfidDeviceBo bo) {
        RfidDevice update = MapstructUtils.convert(bo, RfidDevice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(RfidDevice entity){
        // 业务编号 deviceCode 唯一校验
        if (StringUtils.isNotBlank(entity.getDeviceCode())) {
            boolean exists = baseMapper.existsRfidDevice(Wrappers.<RfidDevice>lambdaQuery()
                .eq(RfidDevice::getDeviceCode, entity.getDeviceCode())
                .ne(entity.getId() != null, RfidDevice::getId, entity.getId()));
            if (exists) {
                throw new ServiceException("设备编号已存在");
            }
        }

        // isMarked 默认值处理
        if (StringUtils.isBlank(entity.getIsMarked())) {
            entity.setIsMarked("1");
        }
    }

    /**
     * 校验并批量删除设备信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid && ids != null && !ids.isEmpty()) {
            // 校验是否存在关联的读取记录，防止产生孤儿记录
            boolean existsRecord = rfidReadRecordMapper.existsRfidReadRecord(
                Wrappers.<RfidReadRecord>lambdaQuery().in(RfidReadRecord::getDeviceId, ids)
            );
            if (existsRecord) {
                throw new ServiceException("存在关联读取记录的设备，无法删除");
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
