package org.dromara.mp.service.impl;

import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.*;
import org.dromara.mp.service.WxMpMaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

/**
 * 微信公众号素材管理服务实现类
 *
 * @author pengles
 */
@Service
public class WxMpMaterialServiceImpl implements WxMpMaterialService {

    private static final Logger logger = LoggerFactory.getLogger(WxMpMaterialServiceImpl.class);

    @Autowired
    private WxMpService wxMpService;

    @Override
    public WxMediaUploadResult uploadTempMedia(String mediaType, File file) {
        try {
            WxMediaUploadResult result = wxMpService.getMaterialService().mediaUpload(mediaType, file);
            logger.info("上传临时素材成功: {}", result.getMediaId());
            return result;
        } catch (WxErrorException e) {
            logger.error("上传临时素材失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public InputStream downloadTempMedia(String mediaId) {
        try {
            File file = wxMpService.getMaterialService().mediaDownload(mediaId);
            logger.info("下载临时素材成功: {}", mediaId);
            return file.toURI().toURL().openStream();
        } catch (Exception e) {
            logger.error("下载临时素材失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public WxMpMaterialUploadResult uploadMaterial(String mediaType, File file) {
        try {
            WxMpMaterial material = new WxMpMaterial();
            material.setFile(file);
            material.setName(file.getName());

            WxMpMaterialUploadResult result = wxMpService.getMaterialService().materialFileUpload(mediaType, material);
            logger.info("上传永久素材成功: {}", result.getMediaId());
            return result;
        } catch (WxErrorException e) {
            logger.error("上传永久素材失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public boolean deleteMaterial(String mediaId) {
        try {
            boolean result = wxMpService.getMaterialService().materialDelete(mediaId);
            logger.info("删除永久素材成功: {}", mediaId);
            return result;
        } catch (WxErrorException e) {
            logger.error("删除永久素材失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem getMaterial(String mediaId) {
        try {
            WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem item =
                    wxMpService.getMaterialService().materialFileBatchGet("news", 0, 1)
                            .getItems().stream()
                            .filter(i -> mediaId.equals(i.getMediaId()))
                            .findFirst()
                            .orElse(null);

            if (item != null) {
                logger.info("获取永久素材成功: {}", mediaId);
            } else {
                logger.warn("未找到永久素材: {}", mediaId);
            }
            return item;
        } catch (WxErrorException e) {
            logger.error("获取永久素材失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public WxMpMaterialFileBatchGetResult getMaterialList(String type, int offset, int count) {
        try {
            WxMpMaterialFileBatchGetResult result = wxMpService.getMaterialService().materialFileBatchGet(type, offset, count);
            logger.info("获取素材列表成功: 类型={}, 数量={}", type, result.getItemCount());
            return result;
        } catch (WxErrorException e) {
            logger.error("获取素材列表失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public WxMpMaterialCountResult getMaterialCount() {
        try {
            WxMpMaterialCountResult result = wxMpService.getMaterialService().materialCount();
            logger.info("获取素材总数成功: 图片={}, 语音={}, 视频={}, 图文={}",
                    result.getImageCount(), result.getVoiceCount(), result.getVideoCount(), result.getNewsCount());
            return result;
        } catch (WxErrorException e) {
            logger.error("获取素材总数失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public String uploadImg(File file) {
        try {
            WxMediaImgUploadResult result = wxMpService.getMaterialService().mediaImgUpload(file);
            logger.info("上传图文消息图片成功: {}", result.getUrl());
            return result.getUrl();
        } catch (WxErrorException e) {
            logger.error("上传图文消息图片失败: {}", e.getMessage(), e);
            return null;
        }
    }
}