package com.fuyuanshen.equipment.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.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 com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.fuyuanshen.equipment.domain.bo.DeviceLogBo;
import com.fuyuanshen.equipment.domain.vo.DeviceLogVo;
import com.fuyuanshen.equipment.domain.DeviceLog;
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
import com.fuyuanshen.equipment.service.IDeviceLogService;

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

/**
 * 设备日志Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DeviceLogServiceImpl implements IDeviceLogService {

    private final DeviceLogMapper baseMapper;

    private final DeviceAssignmentsMapper deviceAssignmentsMapper;


    /**
     * 查询设备日志
     *
     * @param id 主键
     * @return 设备日志
     */
    @Override
    public DeviceLogVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }


    /**
     * 分页查询设备日志列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备日志分页列表
     */
    @Override
    public TableDataInfo<DeviceLogVo> queryPageList(DeviceLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DeviceLog> lqw = buildQueryWrapper(bo);
        Page<DeviceLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    /**
     * 查询符合条件的设备日志列表
     *
     * @param bo 查询条件
     * @return 设备日志列表
     */
    @Override
    public List<DeviceLogVo> queryList(DeviceLogBo bo) {
        LambdaQueryWrapper<DeviceLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DeviceLog> buildQueryWrapper(DeviceLogBo bo) {

        // 管理员
        String username = LoginHelper.getUsername();
        if (!username.equals("admin")) {
            Long userId = LoginHelper.getUserId();
            List<DeviceAssignments> assignments = deviceAssignmentsMapper.selectList(new QueryWrapper<DeviceAssignments>().eq("assignee_id", userId));
            List<Long> deviceIds = assignments.stream().map(DeviceAssignments::getDeviceId).collect(Collectors.toList());
            if (deviceIds.isEmpty()) {
                deviceIds.add(-1L);
            }
            bo.setDeviceIds(deviceIds);
        }

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DeviceLog> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(DeviceLog::getCreateTime);
        lqw.like(StringUtils.isNotBlank(bo.getDeviceAction()), DeviceLog::getDeviceAction, bo.getDeviceAction());
        lqw.like(StringUtils.isNotBlank(bo.getDeviceName()), DeviceLog::getDeviceName, bo.getDeviceName());
        lqw.eq(StringUtils.isNotBlank(bo.getDataSource()), DeviceLog::getDataSource, bo.getDataSource());
        lqw.like(StringUtils.isNotBlank(bo.getContent()), DeviceLog::getContent, bo.getContent());
        lqw.in(CollectionUtil.isNotEmpty(bo.getDeviceIds()), DeviceLog::getDeviceId, bo.getDeviceIds());
        lqw.orderByDesc(DeviceLog::getCreateTime);
        return lqw;
    }


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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DeviceLog entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除设备日志信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
