<?php

namespace App\Services\Smm;
use App\Services\Contracts\SmmPlatformInterface;
use Illuminate\Http\Request;
use Facebook\Facebook;


class FacebookService implements SmmPlatformInterface
{
    public $fb = null;
    public $pageAccessToken = null;

    public function __construct() {
        $this->fb = new Facebook([
            'app_id' => env('SSM_FACEBOOK_APP_ID'), // 替换为您的App ID
            'app_secret' => env('SSM_FACEBOOK_APP_SECRET'), // 替换为您的App Secret
            'default_graph_version' => 'v22.0', // 使用当前版本
        ]);
        //$this->pageAccessToken = $pageAccessToken;
    }

    /*
     * OAuth 2.0 授权登录
     * 返回授权地址：https://example.com/fb-callback.php
     */
    public function login()
    {
        // 实现Facebook登录逻辑
        $helper = $this->fb->getRedirectLoginHelper();
        $permissions = ['public_profile','email'];
        $distSiteUrl = env('DIST_SITE_URL');
        $loginUrl = $helper->getLoginUrl(env('DIST_SITE_URL').'/open/callback/facebook', $permissions);
        return ['status'=>true, 'data' => ['url'=>$loginUrl]];
    }

    /*
     * OAuth 2.0 授权回调
     * 授权成功后，得到access_token，refresh_token等信息, 保存到数据库中
     * 授权成功后，返回回调需要的数据
     */
    public function loginCallback(Request $request)
    {
        // 实现Facebook回调处理
        $helper = $this->fb->getRedirectLoginHelper();
        try {
            $accessToken = $helper->getAccessToken();
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            return ['status' => false, 'data' => 'Graph API错误：' . $e->getMessage()];
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            return ['status' => false, 'data' => 'SDK错误：' . $e->getMessage()];
        }
        if (isset($accessToken)) {
            // 可选：将短期令牌转换为长期令牌（有效期约60天）
            $oAuth2Client = $this->fb->getOAuth2Client();
            $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
            $useriInfo = $this->getFacebookUser($longLivedAccessToken);
            return ['status' => true, 'data' => ['access_token' => $longLivedAccessToken,'user_name'=>$useriInfo['name'],'user_id'=>$useriInfo['id']]];
        } else {
            return ['status' => false, 'data' => '无法获取访问令牌'];
        }
    }

    public function postImage($message,$imagePath) {
        try {
            $response = $this->fb->post(
                '/me/photos',
                [
                    'source' => $this->fb->fileToUpload($imagePath), // 上传图片文件
                    'message' => $message,                    // 添加描述
                ],
                $this->userAccessToken
            );
            $graphNode = $response->getGraphNode();
            return ['status' => true, 'data' => ['id' => $graphNode['id']]];
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            $errorMsg  = 'Graph API错误：' . $e->getMessage();
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            $errorMsg = 'SDK错误：' . $e->getMessage();
        }
        return ['status'=>false,'data' => $errorMsg];
    }


    public function postVideo($message,$videoPath) {
        try {
            $response = $this->fb->post(
                '/me/videos',
                [
                    'source' => $this->fb->fileToUpload($videoPath), // 上传视频文件
                    'title' => $message,                        // 添加标题
                    'description' => '',            // 添加描述
                ],
                $this->userAccessToken
            );
            $graphNode = $response->getGraphNode();
            return ['status' => true, 'data' => ['id' => $graphNode['id']]];
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            $errorMsg = 'Graph API错误：' . $e->getMessage();
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            $errorMsg = 'SDK错误：' . $e->getMessage();
        }
        return ['status'=>false,'data' => $errorMsg];
    }

    public function getComments($postId) {

    }

    public function replyToComment($commentId) {

    }

    public function deleteComment($commentId) {

    }


    /**
     * 获取Facebook用户信息
     * @param string $accessToken
     * @return array [
     *     'name' => string,
     *     'id' => string,
     *     'error' => string|null
     * ]
     */
    public function getFacebookUser($accessToken)
    {
        try {
            // 验证并设置访问令牌
            $this->fb->setDefaultAccessToken($accessToken);

            // 发送请求获取用户信息
            $response = $this->fb->get('/me?fields=name,id');
            $userNode = $response->getGraphUser();

            return [
                'name' => $userNode->getName(),
                'id' => $userNode->getId(),
                'error' => null
            ];

        } catch (FacebookResponseException $e) {
            // API 响应错误处理
            return [
                'name' => null,
                'id' => null,
                'error' => 'Graph API Error: ' . $e->getMessage()
            ];
        } catch (FacebookSDKException $e) {
            // SDK 错误处理
            return [
                'name' => null,
                'id' => null,
                'error' => 'SDK Error: ' . $e->getMessage()
            ];
        } catch (Exception $e) {
            // 其他错误处理
            return [
                'name' => null,
                'id' => null,
                'error' => 'General Error: ' . $e->getMessage()
            ];
        }
    }


}
