package org.jeecg.modules.adweb.marketing.facebook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookEndpoints;
import com.restfb.Version;

import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.adweb.marketing.facebook.entity.AdwebImFacebook;
import org.jeecg.modules.adweb.marketing.facebook.mapper.AdwebImFacebookMapper;
import org.jeecg.modules.adweb.marketing.facebook.service.IFacebookService;
import org.jeecg.modules.adweb.marketing.facebook.vo.FacebookChatVO;
import org.jeecg.modules.adweb.marketing.facebook.vo.FacebookMessageVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Zenas
 */
@Service
@Slf4j
public class FacebookServiceImpl extends ServiceImpl<AdwebImFacebookMapper, AdwebImFacebook> implements IFacebookService {

    @Resource
    private AdwebImFacebookMapper facebookMapper;
    @Override
    public List<FacebookChatVO> getChatList(String siteCode) {
        // 根据siteCode从Facebook API获取聊天列表
        // 根据站点code获取用户的access token
        String userAccessToken = getUserAccessTokenBySiteCode(siteCode);
        try {
            // 1.获取Page ID
            // 创建一个Facebook客户端实例
            DefaultFacebookClient client = new DefaultFacebookClient(Version.LATEST);
            FacebookEndpoints endpoints =
                    new FacebookEndpoints() {
                        @Override
                        public String getGraphEndpoint() {
                            return "http://facebook-proxy.adwebcloud.com";
                        }
                    };

            client = (DefaultFacebookClient) client.createClientWithAccessToken(userAccessToken);
            client.setFacebookEndpointUrls(endpoints);

            String response = client.fetchObject("me/accounts", String.class);
            log.info("me/accounts: response={}", response);
            Gson gson = new Gson();
            // String转json对象
            JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
            String pageId = jsonObject.get("data").getAsJsonArray().get(0).getAsJsonObject().get("id").getAsString();
            String pageAccessToken = jsonObject.get("data").getAsJsonArray().get(0).getAsJsonObject().get("access_token")
                    .getAsString();

            // 2.获取CONVERSATION-ID
            client = (DefaultFacebookClient) client.createClientWithAccessToken(pageAccessToken);
            client.setFacebookEndpointUrls(endpoints);
            response = client.fetchObject(pageId + "/conversations", String.class);
            log.info("pageId/conversations: response={}", response);
            jsonObject = gson.fromJson(response, JsonObject.class);
            List<String> conversationIdList = new ArrayList<>();
            for (int i = 0; i < jsonObject.get("data").getAsJsonArray().size(); i++) {
                conversationIdList.add(jsonObject.get("data").getAsJsonArray().get(i).getAsJsonObject().get("id").getAsString());
            }
            if (conversationIdList.isEmpty()) {
                return null;
            }
            // 获取每个conversationId下最新的消息
            List<FacebookChatVO> facebookChatVOS = new ArrayList<FacebookChatVO>();
            for (int i = 0; i < conversationIdList.size(); i++) {
                FacebookChatVO facebookChatVO = new FacebookChatVO();
                response = client.fetchObject(conversationIdList.get(i) + "?fields=messages", String.class);
                log.info("conversationId/messages: response={}", response);
                jsonObject = gson.fromJson(response, JsonObject.class);
                String messageId = jsonObject.get("messages").getAsJsonObject().get("data").getAsJsonArray().get(0).getAsJsonObject().get("id").getAsString();
                // 获取messageId下的消息 获取每个conversationId下最新的消息
                response = client.fetchObject(messageId + "?fields=id,created_time,from,to,message", String.class);
                log.info("messageId: response={}", response);
                jsonObject = gson.fromJson(response, JsonObject.class);
                facebookChatVO.setId(jsonObject.get("id").getAsString());
                facebookChatVO.setName(jsonObject.get("from").getAsJsonObject().get("name").getAsString());
                facebookChatVO.setLastMessage(jsonObject.get("message").getAsString());
                facebookChatVO.setLastMessageTime(jsonObject.get("created_time").getAsString());
                ArrayList<String> messageIdList = new ArrayList<>();
                for (int j = 0; j < jsonObject.get("messages").getAsJsonObject().get("data").getAsJsonArray().size(); j++) {
                    messageIdList.add(jsonObject.get("messages").getAsJsonObject().get("data").getAsJsonArray().get(j).getAsJsonObject().get("id").getAsString());
                }
                if (messageIdList.isEmpty()) {
                    return null;
                }
                List<FacebookMessageVO> facebookMessageVOS = new ArrayList<>();
                for (int k = 0; k < messageIdList.size(); k++) {
                    response = client.fetchObject(messageIdList.get(k) + "?fields=id,created_time,from,to,message", String.class);
                    log.info("messageId: response={}", response);
                    jsonObject = gson.fromJson(response, JsonObject.class);FacebookMessageVO facebookMessageVO = new FacebookMessageVO();
                    facebookMessageVO.setId(jsonObject.get("id").getAsString());
                    facebookMessageVO.setSender(jsonObject.get("from").getAsJsonObject().get("name").getAsString());
                    facebookMessageVO.setAvatar(jsonObject.get("to").getAsJsonObject().get("name").getAsString());
                    facebookMessageVO.setContent(jsonObject.get("message").getAsString());
                    facebookMessageVO.setTime(jsonObject.get("created_time").getAsString());
                    facebookMessageVOS.add(facebookMessageVO);
                }
                log.info("facebookMessageVOS: {}", facebookMessageVOS);
                facebookChatVO.setMessageVOList(facebookMessageVOS);
                facebookChatVOS.add(facebookChatVO);
            }
            return facebookChatVOS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<FacebookMessageVO> getChatDetail(String siteCode, String conversationId) {
        // 根据站点code获取用户的access token
        String userAccessToken = getUserAccessTokenBySiteCode(siteCode);
        try {
            // 1.获取Page ID
            // 创建一个Facebook客户端实例
            DefaultFacebookClient client = new DefaultFacebookClient(Version.LATEST);
            FacebookEndpoints endpoints =
                    new FacebookEndpoints() {
                        @Override
                        public String getGraphEndpoint() {
                            return "http://facebook-proxy.adwebcloud.com";
                        }
                    };

            client = (DefaultFacebookClient) client.createClientWithAccessToken(userAccessToken);
            client.setFacebookEndpointUrls(endpoints);

            String response = client.fetchObject("me/accounts", String.class);
            log.info("me/accounts: response={}", response);
            Gson gson = new Gson();
            // String转json对象
            JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
            String pageAccessToken = jsonObject.get("data").getAsJsonArray().get(0).getAsJsonObject().get("access_token")
                    .getAsString();

            // 2.获取CONVERSATION-ID
            client = (DefaultFacebookClient) client.createClientWithAccessToken(pageAccessToken);
            client.setFacebookEndpointUrls(endpoints);
            response = client.fetchObject(conversationId + "?fields=messages", String.class);
            log.info("conversationId/messages: response={}", response);
            // 获取每个conversationId下所有消息
            ArrayList<String> messageIdList = new ArrayList<>();
            jsonObject = gson.fromJson(response, JsonObject.class);
            for (int i = 0; i < jsonObject.get("messages").getAsJsonObject().get("data").getAsJsonArray().size(); i++) {
                messageIdList.add(jsonObject.get("messages").getAsJsonObject().get("data").getAsJsonArray().get(i).getAsJsonObject().get("id").getAsString());
            }
            if (messageIdList.isEmpty()) {
                return null;
            }
            List<FacebookMessageVO> facebookMessageVOS = new ArrayList<>();
            for (int i = 0; i < messageIdList.size(); i++) {
                response = client.fetchObject(messageIdList.get(i) + "?fields=id,created_time,from,to,message", String.class);
                log.info("messageId: response={}", response);
                jsonObject = gson.fromJson(response, JsonObject.class);FacebookMessageVO facebookMessageVO = new FacebookMessageVO();
                facebookMessageVO.setId(jsonObject.get("id").getAsString());
                facebookMessageVO.setSender(jsonObject.get("from").getAsJsonObject().get("name").getAsString());
                facebookMessageVO.setAvatar(jsonObject.get("to").getAsJsonObject().get("name").getAsString());
                facebookMessageVO.setContent(jsonObject.get("message").getAsString());
                facebookMessageVO.setTime(jsonObject.get("created_time").getAsString());
                facebookMessageVOS.add(facebookMessageVO);
            }
            log.info("facebookMessageVOS: {}", facebookMessageVOS);
            return facebookMessageVOS;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private String getUserAccessTokenBySiteCode(String siteCode) {
        // 根据siteCode从数据库获取用户的access token
        QueryWrapper<AdwebImFacebook> adwebImFacebookQueryWrapper = new QueryWrapper<>();
        adwebImFacebookQueryWrapper.eq("site_code", siteCode);
        AdwebImFacebook adwebImFacebook = facebookMapper.selectOne(adwebImFacebookQueryWrapper);
        return adwebImFacebook.getAccessToken();
    }
}