package com.fuyuanshen.web.service.device;

import cn.hutool.core.collection.CollUtil;
import com.fuyuanshen.equipment.domain.AppBusinessFile;
import com.fuyuanshen.equipment.domain.AppOperationVideo;
import com.fuyuanshen.equipment.domain.bo.AppBusinessFileBo;
import com.fuyuanshen.equipment.domain.bo.AppOperationVideoBo;
import com.fuyuanshen.app.domain.dto.AppFileDto;
import com.fuyuanshen.equipment.service.IAppBusinessFileService;
import com.fuyuanshen.equipment.service.IAppOperationVideoService;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.system.domain.vo.SysOssVo;
import com.fuyuanshen.system.service.ISysOssService;
import com.fuyuanshen.web.domain.vo.DeviceInfoVo;
import com.fuyuanshen.equipment.utils.FileHashUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备调试服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceDebugService {
    private final ISysOssService sysOssService;

    private final IAppBusinessFileService appBusinessFileService;
    private final IAppOperationVideoService appOperationVideoService;
    private final DeviceService deviceService;
    private final FileHashUtil fileHashUtil;

    /**
     * 文件上传并添加文件信息哈希去重
     * @param bo
     * @return
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean addFileHash(AppFileDto bo,Boolean isBatch) throws IOException {
        MultipartFile[] files = bo.getFiles();
        if (files == null || files.length == 0) {
            throw new ServiceException("请选择要上传的文件");
        }
        if (files.length > 5) {
            throw new ServiceException("最多只能上传5个文件");
        }
        if (bo.getDeviceIds() == null || bo.getDeviceIds().length == 0) {
            throw new ServiceException("请选择你要上传的设备");
        }

        Map<String, Long> hash2OssId = new LinkedHashMap<>(files.length);
        for (MultipartFile file : files) {
            // 1. 计算文件哈希
            String hash = fileHashUtil.hash(file);

            SysOssVo exist = sysOssService.updateHash(file, hash);
            // 2.1 已存在，直接复用
            long ossId = exist.getOssId();
            hash2OssId.putIfAbsent(hash, ossId);
        }
        // 4. 组装业务中间表
        List<AppBusinessFile> bizList = new ArrayList<>(bo.getDeviceIds().length * hash2OssId.size());
        Long userId = AppLoginHelper.getUserId();
        for (Long deviceId : bo.getDeviceIds()) {
            for (Long ossId : hash2OssId.values()) {
                // 3. 关联业务表
                AppBusinessFile appFile = new AppBusinessFile();
                appFile.setFileId(ossId);
                appFile.setBusinessId(deviceId);
                appFile.setFileType(bo.getFileType());
                appFile.setCreateBy(userId);
                bizList.add(appFile);
            }
        }
        if (CollUtil.isEmpty(bizList)) {          // 空集合直接返回
            throw new ServiceException("请选择要上传的文件");
        }
        return appBusinessFileService.insertBatch(bizList,isBatch);
    }

    public Boolean addVideoList(AppOperationVideoBo bo){
        if (bo.getVideoUrl().isEmpty()) {
            throw new ServiceException("请输入视频地址");
        }
        if (bo.getDeviceIds() == null || bo.getDeviceIds().length == 0) {
            throw new ServiceException("请选择你要上传的设备");
        }
        List<AppOperationVideo> bizList = new ArrayList<>(bo.getDeviceIds().length);
        for (Long deviceId : bo.getDeviceIds()) {

            AppOperationVideo appVideo = new AppOperationVideo();
            appVideo.setVideoName(bo.getVideoName());
            appVideo.setDeviceId(deviceId);
            appVideo.setVideoUrl(bo.getVideoUrl());
            bizList.add(appVideo);
        }
        if (CollUtil.isEmpty(bizList)) {          // 空集合直接返回
            throw new ServiceException("请选择要上传的视频");
        }
        return appOperationVideoService.insertBatch(bizList);
    }
    // 删除文件
    public void delFile(List<Long> ids) {
        // 3. 删除旧图片
        if(ids != null){
            appBusinessFileService.deleteWithValidByIds(ids, true);
        }
    }

    /**
     * 设备详情
     * @param deviceId
     * @return
     */
    public DeviceInfoVo getDeviceInfo(Long deviceId) {
        if(deviceId == null || deviceId <= 0L) {
            throw new ServiceException("请选择设备");
        }
        DeviceInfoVo vo = new DeviceInfoVo();
        var device = deviceService.getById(deviceId);
        AppBusinessFileBo fileBo = new AppBusinessFileBo();
        fileBo.setBusinessId(deviceId);
        AppOperationVideoBo videoBo = new AppOperationVideoBo();
        videoBo.setDeviceId(deviceId);
        vo.setAppBusinessFileVoList(appBusinessFileService.queryAppFileList(fileBo));
        vo.setAppOperationVideoVoList(appOperationVideoService.queryList(videoBo));
        return vo;
    }
}
