package com.fuyuanshen.equipment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.core.utils.StringUtils;
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.equipment.domain.AppOperationVideo;
import com.fuyuanshen.equipment.domain.bo.AppOperationVideoBo;
import com.fuyuanshen.equipment.domain.vo.AppOperationVideoVo;
import com.fuyuanshen.equipment.mapper.AppOperationVideoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.fuyuanshen.equipment.service.IAppOperationVideoService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 操作视频Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-02
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppOperationVideoServiceImpl implements IAppOperationVideoService {

    private final AppOperationVideoMapper baseMapper;

    /**
     * 查询操作视频
     *
     * @param id 主键
     * @return 操作视频
     */
    @Override
    public AppOperationVideoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询操作视频列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 操作视频分页列表
     */
    @Override
    public TableDataInfo<AppOperationVideoVo> queryPageList(AppOperationVideoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppOperationVideo> lqw = buildQueryWrapper(bo);
        Page<AppOperationVideoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的操作视频列表
     *
     * @param bo 查询条件
     * @return 操作视频列表
     */
    @Override
    public List<AppOperationVideoVo> queryList(AppOperationVideoBo bo) {
        LambdaQueryWrapper<AppOperationVideo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppOperationVideo> buildQueryWrapper(AppOperationVideoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppOperationVideo> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppOperationVideo::getId);
        lqw.like(StringUtils.isNotBlank(bo.getVideoName()), AppOperationVideo::getVideoName, bo.getVideoName());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoUrl()), AppOperationVideo::getVideoUrl, bo.getVideoUrl());
        lqw.eq(bo.getDeviceId() != null, AppOperationVideo::getDeviceId, bo.getDeviceId());
        return lqw;
    }

    /**
     * 新增操作视频
     *
     * @param bo 操作视频
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppOperationVideoBo bo) {
        AppOperationVideo add = MapstructUtils.convert(bo, AppOperationVideo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean insertBatch(Collection<AppOperationVideo> bo) {
        // 1. 去重后的 businessId 集合
        List<Long> deviceIds = bo.stream()
                .map(AppOperationVideo::getDeviceId)
                .distinct()
                .toList();
        QueryWrapper<AppOperationVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("device_id", deviceIds);
        baseMapper.delete(queryWrapper);
        return baseMapper.insertBatch(bo);
    }

    /**
     * 修改操作视频
     *
     * @param bo 操作视频
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppOperationVideoBo bo) {
        AppOperationVideo update = MapstructUtils.convert(bo, AppOperationVideo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 克隆业务文件列表到新业务ID
     * @param sourceId 源业务ID（如设备类型ID）
     * @param targetId 目标业务ID（如新设备ID）
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cloneFiles(Long sourceId, Long targetId) {
        // 1. 使用 Wrappers 替代 this.lambdaQuery()
        List<AppOperationVideo> sourceFiles = baseMapper.selectList(
                Wrappers.<AppOperationVideo>lambdaQuery().eq(AppOperationVideo::getDeviceId, sourceId)
        );

        if (CollUtil.isEmpty(sourceFiles)) {
            return;
        }

        // 2. 批量转换并重置ID
        List<AppOperationVideo> newFiles = sourceFiles.stream().map(file -> {
            AppOperationVideo entity = new AppOperationVideo();
            // 建议使用你代码中已有的 MapstructUtils 或 BeanUtil
            BeanUtil.copyProperties(file, entity);
            entity.setId(null);             // 确保主键自增
            entity.setDeviceId(targetId);  // 绑定到新设备ID
            return entity;
        }).collect(Collectors.toList());

        // 3. 使用你已有的 insertBatch 替代 saveBatch
        this.insertBatch(newFiles);
    }

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

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