package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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 com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.lotVideo.LotVideoAddRequest;
import com.ruoyi.web.domain.dto.lotVideo.LotVideoEditRequest;
import com.ruoyi.web.domain.dto.lotVideo.LotVideoQueryRequest;
import com.ruoyi.web.domain.entity.LotVideo;
import com.ruoyi.web.domain.vo.LotVideoVO;
import com.ruoyi.web.mapper.LotVideoMapper;
import com.ruoyi.web.service.LotVideoService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class LotVideoServiceImpl extends ServiceImpl<LotVideoMapper, LotVideo>
        implements LotVideoService {
    @Autowired
    private LotVideoMapper lotVideoMapper;
    /**
     * 添加
     *
     * @param lotVideoAddRequest
     * @return
     */
    @Override
    public Integer addLotVideo(LotVideoAddRequest lotVideoAddRequest) {
        if (lotVideoAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            LotVideo lotVideo = new LotVideo();
            BeanUtil.copyProperties(lotVideoAddRequest, lotVideo);
            //数据校验
            validLotVideo(lotVideo, BusinessType.INSERT);

            // 保存到数据库
            this.save(lotVideo);
            return lotVideo.getId();
        } catch (Exception e) {
            log.error("添加失败", e);
            throw new ServiceException("添加失败");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteLotVideo(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("id不能为空或id异常");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<LotVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

        // 4. 执行删除（返回是否删除成功）
        return remove(queryWrapper);

    }

    /**
     * 编辑
     *
     * @param lotVideoEditRequest
     */
    @Override
    public void editLotVideo(LotVideoEditRequest lotVideoEditRequest) {
        // 判断是否存在
        Integer id = lotVideoEditRequest.getId();
        LotVideo oldLotVideo = this.getById(id);
        if (oldLotVideo == null) {
            throw new ServiceException("没有找到物联网视频监控数据");
        }
        LotVideo lotVideo = new LotVideo();
        BeanUtil.copyProperties(lotVideoEditRequest, lotVideo);
        lotVideo.setUpdateTime(new Date());
        // 数据校验
        validLotVideo(lotVideo, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(lotVideo);
        if (!result) {
            throw new ServiceException("修改物联网视频监控数据操作失败");
        }
    }

    /**
     * 校验数据
     *
     * @param lotVideo
     */
    public void validLotVideo(LotVideo lotVideo, BusinessType type) {
        if (ObjectUtil.isEmpty(lotVideo)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = lotVideo.getId();
        String name = lotVideo.getName();
        String location = lotVideo.getLocation();
        String ip = lotVideo.getIp();
        String monitoringRange = lotVideo.getMonitoringRange();
        String scenarios = lotVideo.getScenarios();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("监控名称不能为空");
        }
        if (StrUtil.isBlank(location)) {
            throw new ServiceException("安装位置不能为空");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public LotVideoVO getLotVideoById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        LotVideo lotVideo = this.getById(id);
        return getLotVideoVO(lotVideo);
    }

    /**
     * 获取视频监控包装类
     *
     * @param lotVideo
     * @return
     */
    @Override
    public LotVideoVO getLotVideoVO(LotVideo lotVideo) {
        if (ObjectUtil.isEmpty(lotVideo)) {
            throw new ServiceException("请求参数不存在");
        }
        LotVideoVO lotVideoVO = new LotVideoVO();
        BeanUtils.copyProperties(lotVideo, lotVideoVO);
        return lotVideoVO;
    }

    /**
     * 分页获取视频监控列表
     *
     * @param lotVideoQueryRequest
     * @return
     */
    @Override
    public Page<LotVideoVO> getListLotVideoByPage(LotVideoQueryRequest lotVideoQueryRequest) {
        long current = lotVideoQueryRequest.getPageNum();
        long size = lotVideoQueryRequest.getPageSize();
        Page<LotVideo> page = this.page(new Page<>(current, size),
                getQueryWrapper(lotVideoQueryRequest));
        Page<LotVideoVO> lotVideoVOPage = new Page<>();
        BeanUtils.copyProperties(page, lotVideoVOPage, "records");
        List<LotVideoVO> voList = page.getRecords().stream()
                .map(lotVideo -> {
                    LotVideoVO vo = new LotVideoVO();
                    BeanUtils.copyProperties(lotVideo, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        lotVideoVOPage.setRecords(voList);
        return lotVideoVOPage;
    }

    /**
     * 获取查询条件
     *
     * @param lotVideoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<LotVideo> getQueryWrapper(LotVideoQueryRequest lotVideoQueryRequest) {
        QueryWrapper<LotVideo> queryWrapper = new QueryWrapper<>();
        if (lotVideoQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        Integer id = lotVideoQueryRequest.getId();
        String name = lotVideoQueryRequest.getName();
        String location = lotVideoQueryRequest.getLocation();
        String scenarios = lotVideoQueryRequest.getScenarios();
        String sortField = lotVideoQueryRequest.getSortField();
        String sortOrder = lotVideoQueryRequest.getSortOrder();


        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.like(StrUtil.isNotBlank(scenarios), "scenarios", scenarios);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(location), "location", location);

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }

    @Override
    public List<LotVideo> listLotVideo(LotVideoQueryRequest lotVideoQueryRequest) {
        List<LotVideo> list = this.list(
                getQueryWrapper(lotVideoQueryRequest));

        return list;
    }

    @Override
    public void removeAll() {
        lotVideoMapper.removeAll();
    }
}




