package com.fs.qw.service.impl;


import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.qw.domain.QwMaterial;
import com.fs.qw.mapper.QwMaterialMapper;
import com.fs.qw.param.QwMaterialParam;
import com.fs.qw.service.IQwMaterialService;
import com.fs.qw.vo.QwMaterialVO;
import com.fs.qwApi.Result.QwUploadResult;
import com.fs.qwApi.service.QwApiService;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * 素材库Service业务层处理
 *
 * @author fs
 * @date 2024-06-20
 */
@Service
public class QwMaterialServiceImpl implements IQwMaterialService
{
    @Autowired
    private QwMaterialMapper qwMaterialMapper;

    @Autowired
    private QwApiService qwApiService;

    /**
     * 查询素材库
     *
     * @param materialId 素材库主键
     * @return 素材库
     */
    @Override
    public QwMaterial selectQwMaterialByMaterialId(Long materialId)
    {
        return qwMaterialMapper.selectQwMaterialByMaterialId(materialId);
    }

    /**
     * 查询素材库列表
     *
     * @param param 素材库
     * @return 素材库
     */
    @Override
    public List<QwMaterialVO> selectQwMaterialList(QwMaterialParam param)
    {
        return qwMaterialMapper.selectQwMaterialListVO(param);
    }

    /**
     * 新增素材库
     *
     * @param qwMaterial 素材库
     * @return 结果
     */
    @Override
    public R insertQwMaterial(QwMaterial qwMaterial) throws Exception {
        qwMaterial.setCreateTime(DateUtils.getNowDate());

        //调用企业微信接口 上次临时图片

        File fileImage = urlToFile(qwMaterial.getMaterialUrl());
        QwUploadResult imageResult = qwApiService.upload(fileImage, "image", qwMaterial.getCorpId());
        if (imageResult.getErrCode()==0){
            qwMaterial.setMaterialMediaId(imageResult.getMediaId());
            qwMaterialMapper.insertQwMaterial(qwMaterial);
            return R.ok();
        }else {
            return R.error("上传图片失败："+imageResult.getErrMsg());
        }
    }

    /**
     *  url转临时文件filr
     */
    public static File urlToFile(String fileUrl) throws Exception {

        // 从URL中提取文件名，文件后缀
        String fileExtension = getFileExtension(new File(fileUrl).getName());
        String fileName = extractFileName(new URL(fileUrl))+new Date().getTime();
        File tempFile=null;
        if (!StringUtil.strIsNullOrEmpty(fileExtension)){
            // 创建一个临时文件
            tempFile = File.createTempFile(fileName, "."+fileExtension);
        }else {
            tempFile = File.createTempFile(fileName, null);
        }


        // 使用 try-with-resources 语句自动关闭资源
        try (BufferedInputStream in = new BufferedInputStream(new URL(fileUrl).openStream());
             FileOutputStream out = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[1024];
            int len;

            // 读取数据并写入到临时文件
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            // 处理异常，例如删除创建的临时文件
            tempFile.delete();
            throw e;
        }

        return tempFile;
    }

    /**
     *  获取文件名
     */
    private static String extractFileName(URL url) throws Exception {
        String path = url.getPath();
        int lastSlashIndex = path.lastIndexOf('/');
        String fileNameWithExt = path.substring(lastSlashIndex + 1);

        int dotIndex = fileNameWithExt.lastIndexOf('.');
        String baseName;
        if (dotIndex > 0) {
            // 如果有扩展名，移除扩展名
            baseName = fileNameWithExt.substring(0, dotIndex);
        } else {
            // 如果没有扩展名，直接使用文件名
            baseName = fileNameWithExt;
        }

        return baseName;
    }

    /**
     *  获取文件名后缀
     */

    public static String getFileExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex != -1 && lastIndex + 1 < fileName.length()) {
            return fileName.substring(lastIndex + 1);
        }
        return ""; // 如果没有扩展名，返回空字符串
    }
    /**
     * 修改素材库
     *
     * @param qwMaterial 素材库
     * @return 结果
     */
    @Override
    public int updateQwMaterial(QwMaterial qwMaterial)
    {
        qwMaterial.setUpdateTime(DateUtils.getNowDate());
        return qwMaterialMapper.updateQwMaterial(qwMaterial);
    }

    /**
     * 批量删除素材库
     *
     * @param materialIds 需要删除的素材库主键
     * @return 结果
     */
    @Override
    public int deleteQwMaterialByMaterialIds(Long[] materialIds)
    {
        return qwMaterialMapper.deleteQwMaterialByMaterialIds(materialIds);
    }

    /**
     * 删除素材库信息
     *
     * @param materialId 素材库主键
     * @return 结果
     */
    @Override
    public int deleteQwMaterialByMaterialId(Long materialId)
    {
        return qwMaterialMapper.deleteQwMaterialByMaterialId(materialId);
    }
}
