package com.dora.service.impl;

import com.dora.entity.WechatNewsArticle;
import com.dora.service.WeChatAccessTokenService;
import com.dora.service.WeChatMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage.WxArticle;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * 微信消息发送服务实现
 * 
 * @author dora
 * @date 2024/12/01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WeChatMessageServiceImpl implements WeChatMessageService {

    private final WxMpService wxMpService;
    private final WeChatAccessTokenService accessTokenService;

    @Override
    public boolean sendTextMessage(String openid, String content) {
        try {
            WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT()
                    .toUser(openid)
                    .content(content)
                    .build();
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
            log.info("发送文本消息成功 - openid: {}", openid);
            return true;
        } catch (WxErrorException e) {
            log.error("发送文本消息异常 - openid: {}, error: {}", openid, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendNewsMessage(String openid, List<WechatNewsArticle> articles) {
        if (articles == null || articles.isEmpty()) {
            log.warn("发送图文消息失败，文章列表为空 - openid: {}", openid);
            return false;
        }

        try {
            // 微信客服消息API限制，一次最多8条图文
            if (articles.size() > 8) {
                log.warn("图文消息数量超过8条，将自动截取前8条发送 - openid: {}", openid);
                articles = articles.subList(0, 8);
            }

            List<WxArticle> wxArticles = articles.stream()
                    // 过滤掉标题或URL为空的无效文章
                    .filter(article -> StringUtils.hasText(article.getTitle()) && StringUtils.hasText(article.getUrl()))
                    .map((WechatNewsArticle article) -> {
                        WxArticle wxArticle = new WxArticle();
                        wxArticle.setTitle(article.getTitle());
                        wxArticle.setDescription(article.getDigest());
                        wxArticle.setUrl(article.getUrl());
                        wxArticle.setPicUrl(article.getThumbUrl());
                        return wxArticle;
                    })
                    .collect(Collectors.toList());
            
            if (wxArticles.isEmpty()) {
                log.warn("发送图文消息失败，所有文章都因缺少标题或URL被过滤 - openid: {}", openid);
                return false;
            }

            WxMpKefuMessage kefuMessage = WxMpKefuMessage.NEWS()
                    .toUser(openid)
                    .articles(wxArticles)
                    .build();
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
            log.info("发送图文消息成功 - openid: {}", openid);
            return true;
        } catch (WxErrorException e) {
            log.error("发送图文消息异常 - openid: {}, error: {}", openid, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendImageMessage(String openid, String mediaId) {
        try {
            WxMpKefuMessage kefuMessage = WxMpKefuMessage.IMAGE()
                    .toUser(openid)
                    .mediaId(mediaId)
                    .build();
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
            log.info("发送图片消息成功 - openid: {}", openid);
            return true;
        } catch (WxErrorException e) {
            log.error("发送图片消息异常 - openid: {}, error: {}", openid, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendVoiceMessage(String openid, String mediaId) {
        try {
            WxMpKefuMessage kefuMessage = WxMpKefuMessage.VOICE()
                    .toUser(openid)
                    .mediaId(mediaId)
                    .build();
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
            log.info("发送语音消息成功 - openid: {}", openid);
            return true;
        } catch (WxErrorException e) {
            log.error("发送语音消息异常 - openid: {}, error: {}", openid, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendVideoMessage(String openid, String mediaId, String thumbMediaId, String title, String description) {
        try {
            WxMpKefuMessage kefuMessage = WxMpKefuMessage.VIDEO()
                    .toUser(openid)
                    .mediaId(mediaId)
                    .thumbMediaId(thumbMediaId)
                    .title(title)
                    .description(description)
                    .build();
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
            log.info("发送视频消息成功 - openid: {}", openid);
            return true;
        } catch (WxErrorException e) {
            log.error("发送视频消息异常 - openid: {}, error: {}", openid, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendMusicMessage(String openid, String title, String description, String musicUrl, String hqMusicUrl, String thumbMediaId) {
        try {
            WxMpKefuMessage kefuMessage = WxMpKefuMessage.MUSIC()
                    .toUser(openid)
                    .title(title)
                    .description(description)
                    .musicUrl(musicUrl)
                    .hqMusicUrl(hqMusicUrl)
                    .thumbMediaId(thumbMediaId)
                    .build();
            wxMpService.getKefuService().sendKefuMessage(kefuMessage);
            log.info("发送音乐消息成功 - openid: {}", openid);
            return true;
        } catch (WxErrorException e) {
            log.error("发送音乐消息异常 - openid: {}, error: {}", openid, e.getMessage());
            return false;
        }
    }
}
