package com.seer.teach.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.teacher.module.entity.MaterialDocEntity;
import com.seer.teach.teacher.module.mapper.MaterialDocMapper;
import com.seer.teach.teacher.service.MaterialDocService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class MaterialDocServiceImpl extends ServiceImpl<MaterialDocMapper, MaterialDocEntity> implements MaterialDocService {
    
    @Override
    public InputStream getMaterialDocumentInputStream(Long materialDocId) {
        MaterialDocEntity materialDoc = this.getById(materialDocId);
        if (materialDoc == null) {
            throw new CommonException(ResultCodeEnum.MATERIAL_DOCUMENT_NOT_FOUND, "未找到ID为 " + materialDocId + " 的教材文档");
        }
        
        try {
            // 从URL获取输入流
            URL url = new URL(materialDoc.getTeacherMaterialUrl());
            URLConnection connection = url.openConnection();
            return connection.getInputStream();
        } catch (Exception e) {
            log.error("获取教材文档输入流失败", e);
            throw new CommonException(ResultCodeEnum.MATERIAL_DOCUMENT_STREAM_FAILED, "获取教材文档输入流失败: " + e.getMessage());
        }
    }
    
    @Override
    public byte[] getMaterialDocumentBytes(Long materialDocId) {
        try (InputStream inputStream = getMaterialDocumentInputStream(materialDocId);
             ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            
            buffer.flush();
            return buffer.toByteArray();
        } catch (Exception e) {
            log.error("读取教材文档字节数组失败", e);
            throw new CommonException(ResultCodeEnum.MATERIAL_DOCUMENT_READ_FAILED, "读取教材文档字节数组失败: " + e.getMessage());
        }
    }

    @Override
    public List<MaterialDocEntity> getMaterialDocIdsByMaterialIds(Collection<Integer> materialIds) {
        return super.list(new LambdaQueryWrapper<>(MaterialDocEntity.class).in(MaterialDocEntity::getId, materialIds));
    }
}