package com.fs.wxcid.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.fs.common.exception.CustomException;
import com.fs.wxcid.FileToBase64Util;
import com.fs.wxcid.ServiceUtils;
import com.fs.wxcid.dto.common.ApiResponseCommon;
import com.fs.wxcid.dto.login.RequestBaseVo;
import com.fs.wxcid.dto.message.CdnUploadVideoResult;
import com.fs.wxcid.dto.message.MsgItem;
import com.fs.wxcid.dto.message.RevokeMsgRequest;
import com.fs.wxcid.dto.message.SendImageMessageParam;
import com.fs.wxcid.dto.message.SendTextMessageParam;
import com.fs.wxcid.dto.message.SendVideoMessageParam;
import com.fs.wxcid.dto.message.RevokeMsgResult;
import com.fs.wxcid.dto.message.SendImageMessageResult;
import com.fs.wxcid.dto.message.SendMessageResult;
import com.fs.wxcid.dto.message.SendTextMessageRequest;
import com.fs.wxcid.dto.message.SendVideoMessageRequest;
import com.fs.wxcid.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    private final static String BASE_URL = "/message/";
    @Autowired
    private ServiceUtils serviceUtils;

    @Override
    public List<SendMessageResult> sendTextMessage(SendTextMessageParam param) {
        SendTextMessageRequest request = new SendTextMessageRequest();
        List<MsgItem> list = new ArrayList<>();
        MsgItem msgItem = new MsgItem();
        msgItem.setTextContent(param.getTxt());
        list.add(msgItem);
        request.setMsgItem(list);
        ApiResponseCommon<List<SendMessageResult>> response = serviceUtils.sendPost(BASE_URL + "SendTextMessage", RequestBaseVo.builder().accountId(param.getAccountId()).data(request).build(), new TypeReference<ApiResponseCommon<List<SendMessageResult>>>() {});
        // 第二层：检查每条消息是否真正发送成功
        List<SendMessageResult> results = response.getData();
        List<String> failedRecipients = new ArrayList<>();
        for (SendMessageResult result : results) {
            if (!result.isSendSuccess()) {
                failedRecipients.add(result.getToUserName());
            }
        }
        if (!failedRecipients.isEmpty()) {
            String errorMsg = "部分消息发送失败，失败接收人: " + String.join(", ", failedRecipients);
            throw new CustomException("发送文本消息部分失败: " + errorMsg);
        }
        return response.getData();
    }

    @Override
    public List<SendImageMessageResult> sendImageMessage(SendImageMessageParam param) {
        SendTextMessageRequest request = new SendTextMessageRequest();
        List<MsgItem> list = new ArrayList<>();
        MsgItem msgItem = new MsgItem();
        try {
            msgItem.setMsgType(0);
            msgItem.setImageContent(FileToBase64Util.convertImageUrlToBase64(param.getImgUrl()));
            msgItem.setToUserName(param.getToUser());
        }catch (Exception e){
            log.error("发送消息时，图片转换base64错误", e);
            throw new CustomException("图片消息发送失败");
        }
        list.add(msgItem);
        request.setMsgItem(list);
        ApiResponseCommon<List<SendImageMessageResult>> response = serviceUtils.sendPost(BASE_URL + "SendImageNewMessage", RequestBaseVo.builder().accountId(param.getAccountId()).data(request).build(), new TypeReference<ApiResponseCommon<List<SendImageMessageResult>>>() {});
        // 第二层：检查每条消息是否真正发送成功（根据 resp.baseResponse.ret == 0 判断）
        List<SendImageMessageResult> results = response.getData();
        List<String> failedRecipients = new ArrayList<>();
        for (SendImageMessageResult result : results) {
            if (!result.isSendSuccess()) {
                failedRecipients.add(result.getToUserName());
            }
        }
        if (!failedRecipients.isEmpty()) {
            String errorMsg = "部分图片消息发送失败，失败接收人: " + String.join(", ", failedRecipients);
            throw new CustomException("发送图片消息部分失败: " + errorMsg);
        }
        return response.getData();
    }

    @Override
    public RevokeMsgResult revokeMessage(RevokeMsgRequest request) {
        ApiResponseCommon<RevokeMsgResult> response = serviceUtils.sendPost(BASE_URL + "RevokeMsgNew", RequestBaseVo.builder().accountId(request.getAccountId()).data(request).build(), new TypeReference<ApiResponseCommon<RevokeMsgResult>>() {});
        RevokeMsgResult result = response.getData();
        if (result != null && !result.isSuccess()) {
            String errorMsg = result.getSysWording() != null ? result.getSysWording() : "消息撤回失败";
            throw new CustomException(errorMsg);
        }
        return response.getData();
    }

    @Override
    public CdnUploadVideoResult sendVideoMessage(SendVideoMessageParam param) {
        SendVideoMessageRequest request = new SendVideoMessageRequest();
        request.setToUserName(param.getToUser());
        try {
            request.setThumbData(FileToBase64Util.downloadToBytes(param.getThumbUrl()));
            request.setVideoData(FileToBase64Util.downloadToBytes(param.getVideoUrl()));
        } catch (Exception e) {
            log.error("发送视频消息时，文件下载失败", e);
            throw new CustomException("视频消息发送失败");
        }
        ApiResponseCommon<CdnUploadVideoResult> response = serviceUtils.sendPost(
                BASE_URL + "CdnUploadVideo",
                RequestBaseVo.builder().accountId(param.getAccountId()).data(request).build(),
                new TypeReference<ApiResponseCommon<CdnUploadVideoResult>>() {}
        );
        CdnUploadVideoResult result = response.getData();
        if (result != null && result.getRetCode() != null && result.getRetCode() != 0) {
            throw new CustomException("视频上传失败，RetCode=" + result.getRetCode());
        }
        return result;
    }
}