package org.dromara.service.impl;

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 org.dromara.domain.SenMonitorPointMedia;
import org.dromara.domain.vo.MonitorTreeVo;
import org.dromara.mapper.SenMonitorPointMediaMapper;
import org.dromara.system.domain.SysArea;
import org.dromara.system.mapper.SysAreaMapper;
import org.springframework.stereotype.Service;
import org.dromara.domain.bo.SenMonitorPointBo;
import org.dromara.domain.vo.SenMonitorPointVo;
import org.dromara.domain.SenMonitorPoint;
import org.dromara.mapper.SenMonitorPointMapper;
import org.dromara.service.ISenMonitorPointService;

import java.util.*;

/**
 * 监控点位信息Service业务层处理
 *
 * @author luogang
 * @date 2024-09-14
 */
@RequiredArgsConstructor
@Service
public class SenMonitorPointServiceImpl implements ISenMonitorPointService {

    private final SenMonitorPointMapper baseMapper;
    private final SysAreaMapper areaMapper;
    private final SenMonitorPointMediaMapper mediaMapper;

    /**
     * 查询监控点位信息
     *
     * @param pointId 主键
     * @return 监控点位信息
     */
    @Override
    public SenMonitorPointVo queryById(Long pointId) {
        return baseMapper.selectVoById(pointId);
    }

    /**
     * 分页查询监控点位信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 监控点位信息分页列表
     */
    @Override
    public TableDataInfo<SenMonitorPointVo> queryPageList(SenMonitorPointBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SenMonitorPoint> lqw = buildQueryWrapper(bo);
        Page<SenMonitorPointVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的监控点位信息列表
     *
     * @param bo 查询条件
     * @return 监控点位信息列表
     */
    @Override
    public List<SenMonitorPointVo> queryList(SenMonitorPointBo bo) {
        LambdaQueryWrapper<SenMonitorPoint> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SenMonitorPoint> buildQueryWrapper(SenMonitorPointBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SenMonitorPoint> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getPointName()), SenMonitorPoint::getPointName, bo.getPointName());
        lqw.eq(StringUtils.isNotBlank(bo.getSceneType()), SenMonitorPoint::getSceneType, bo.getSceneType());
        return lqw;
    }

    /**
     * 新增监控点位信息
     *
     * @param bo 监控点位信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SenMonitorPointBo bo) {
        SenMonitorPoint add = MapstructUtils.convert(bo, SenMonitorPoint.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPointId(add.getPointId());
            //实时视频
            if (Objects.equals(bo.getVideoType(), "1")) {
                SenMonitorPointMedia media =new SenMonitorPointMedia();
                media.setPointId(bo.getPointId());
                media.setVideoType(bo.getVideoType());
                media.setDeviceNo(bo.getDeviceNo());
                media.setStreamUrl(bo.getStreamUrl());
                mediaMapper.insert(media);
            }
        }
        return flag;
    }

    /**
     * 修改监控点位信息
     *
     * @param bo 监控点位信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SenMonitorPointBo bo) {
        SenMonitorPoint update = MapstructUtils.convert(bo, SenMonitorPoint.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public List<SenMonitorPoint> getListByAreaId(SenMonitorPointBo bo) {
        List<SysArea> resultList = new ArrayList<>();
        // 直接获取该节点的信息
        SysArea root = areaMapper.selectOne(new LambdaQueryWrapper<SysArea>()
                .eq(SysArea::getAreaId, bo.getAreaId()));
        if (root != null) {
            resultList.add(root);
        }
        // 获取所有子节点
        String ancestorPattern = "%" + bo.getAreaId() + "%";
        List<SysArea> children = areaMapper.selectList(new LambdaQueryWrapper<SysArea>()
                .like(StringUtils.isNotBlank(ancestorPattern), SysArea::getAncestors, ancestorPattern));
        resultList.addAll(children);
        List<Long> areaIds = resultList.stream()
                .map(SysArea::getAreaId)
                .toList();
        return baseMapper.selectList(
                Wrappers.<SenMonitorPoint>lambdaQuery()
                        .in(SenMonitorPoint::getAreaId, areaIds)
                        .like(StringUtils.isNotBlank(bo.getPointName()), SenMonitorPoint::getPointName, bo.getPointName())
                        .orderByAsc(SenMonitorPoint::getPointId)
        );

    }


    @Override
    public MonitorTreeVo selectAreaTreeList(SenMonitorPointBo bo) {
        // 查询所有区域数据
        List<SysArea> allAreas = areaMapper.selectList(Wrappers.<SysArea>lambdaQuery().orderByAsc(SysArea::getOrderNum));
        // 构建节点映射表
        Map<Long, MonitorTreeVo> nodeMap = new HashMap<>();
        for (SysArea area : allAreas) {
            MonitorTreeVo node = new MonitorTreeVo(area);
            nodeMap.put(area.getAreaId(), node);
        }

        // 构建树形结构
        for (SysArea area : allAreas) {
            Long parentId = area.getParentId();
            if (parentId != 0) {
                MonitorTreeVo parentNode = nodeMap.get(parentId);
                if (parentNode != null) {
                    parentNode.getChildren().add(nodeMap.get(area.getAreaId()));
                }
            }
        }

        // 查找根节点
        MonitorTreeVo root = null;
        for (MonitorTreeVo node : nodeMap.values()) {
            if (node.getParentId() == 0) {
                if (root == null) {
                    root = node;
                }
            }
        }

        // 关联监控点数据
        associateMonitorPoints(root, 3, bo);
        return root;
    }

    private void associateMonitorPoints(MonitorTreeVo node, Integer level, SenMonitorPointBo bo) {
        if (node != null) {
            if (node.getAreaLevel().equals(level)) {
                List<SenMonitorPoint> points = baseMapper.selectList(
                        Wrappers.<SenMonitorPoint>lambdaQuery()
                                .eq(SenMonitorPoint::getAreaId, node.getAreaId())
                                .eq(SenMonitorPoint::getVideoType,"1")
                                .like(StringUtils.isNotBlank(bo.getPointName()),SenMonitorPoint::getPointName, bo.getPointName())
                                .orderByAsc(SenMonitorPoint::getPointId)
                );
                List<MonitorTreeVo> treePoints = getMonitorTreeVos(points);
                node.setChildren(treePoints);

            }
            for (MonitorTreeVo child : node.getChildren()) {
                associateMonitorPoints(child, level, bo);
            }
        }
    }

    private static List<MonitorTreeVo> getMonitorTreeVos(List<SenMonitorPoint> points) {
        List<MonitorTreeVo> treePoints = new ArrayList<>();
        for (SenMonitorPoint point : points) {
            SysArea area = new SysArea();
            area.setAreaId(point.getPointId());
            area.setAreaName(point.getPointName());
            area.setParentId(point.getAreaId());
            area.setAreaLevel(4);
            MonitorTreeVo tree = new MonitorTreeVo(area);
            treePoints.add(tree);
        }
        return treePoints;
    }

}
