package org.jeecg.modules.adweb.marketing.facebook.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.restfb.*;

import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.api.vo.Result;
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.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Tag(name = "Facebook - 帐号，广告，报表数据等")
@RestController
@RequestMapping("/marketing/facebook")
@Slf4j
public class FaceBookController {
    
    @Autowired private IFacebookService facebookService;

    @Resource private AdwebImFacebookMapper facebookMapper;

    /** 获取站点绑定的Facebook account */
    @GetMapping("/account/get")
    public Result<AdwebImFacebook> getFacebookAccount(@RequestParam String siteCode) {
        log.info("getFacebookAccount: siteCode={}", siteCode);
        AdwebImFacebook imFacebook =
                facebookService.getOne(
                        new LambdaQueryWrapper<AdwebImFacebook>().eq(AdwebImFacebook::getSiteCode, siteCode),
                        false);
        log.info("getFacebookAccount: imFacebook={}", imFacebook);
        return Result.ok(imFacebook);
    }

    /** 为站点绑定Facebook account */
    @PostMapping("/account/add")
    @ResponseBody
    public Result<String> addFacebookAccount(
            @RequestParam String siteCode,
            @RequestParam String customerId,
            @RequestParam(required = false) String refreshToken) {
        AdwebImFacebook facebook =
                facebookService.getOne(
                        new LambdaQueryWrapper<AdwebImFacebook>().eq(AdwebImFacebook::getSiteCode, siteCode),
                        false);
        facebook = Optional.ofNullable(facebook).orElse(new AdwebImFacebook());

        facebook.setSiteCode(siteCode);
        facebook.setCustomerId(customerId);
        facebook.setAccessToken(refreshToken);
        facebookService.saveOrUpdate(facebook);

        return Result.ok("添加成功");
    }

    /** 获取Facebook聊天列表 */
    @GetMapping("/chat/list")
    public Result<List<FacebookChatVO>> getFacebookChatList(@RequestParam String siteCode) {
        log.info("getFacebookChatList: siteCode={}", siteCode);
        List<FacebookChatVO> chatList = facebookService.getChatList(siteCode);
        log.info("getFacebookChatList: chatList={}", chatList);
        return Result.ok(chatList);
    }

    @GetMapping("/chat/detail")
    public Result<List<FacebookMessageVO>> getFacebookChatDetail(@RequestParam String siteCode, @RequestParam String conversationId) {
        log.info("getFacebookChatDetail: siteCode={}, conversationId={}", siteCode, conversationId);
        List<FacebookMessageVO> chatDetailList = facebookService.getChatDetail(siteCode, conversationId);
        log.info("getFacebookChatDetail: chatDetailList={}", chatDetailList);
        return Result.ok(chatDetailList);
    }

    

    public static void main(String[] args) {
        // 替换为你的App ID和App Secret
        String appId = "961285249321302";
        String appSecret = "57b38cafc19b10f23eda72ecfc465810";
        String userAccessToken = "EAANqSKnQSVYBOzxamdbMucs9YIo6M8TXPWq4wZCZCTCaZApswM4dUiHBrZBQZCrZArhXiiVb3Pv5WamLra8QAPHGOJabIZCuVZCYWdS1Q4yzxWC8ZCtZBZBozwOz4zZAWHZC2QWXDUukCIYS2oegw1C3mDG50XXdRLLnhypOLGkoVMn1t024UnZCxGmzp7K8nOsXeCi3E65vYjK5a2VHgWuH4IyAZDZD";

        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);
            String conversationId = jsonObject.get("data").getAsJsonArray().get(0).getAsJsonObject().get("id").getAsString();
            // 3.获取MESSAGES-ID
            response = client.fetchObject(conversationId + "?fields=messages", String.class);
            log.info("conversationId/messages: response={}", response);
            // 4.获取MESSAGE详情
            jsonObject = gson.fromJson(response, JsonObject.class);
            String messageId = jsonObject.get("messages").getAsJsonObject().get("data").getAsJsonArray().get(0).getAsJsonObject().get("id").getAsString();
            response = client.fetchObject(messageId + "?fields=id,created_time,from,to,message", String.class);
            log.info("messageId: response={}", response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}