<?php

namespace App\Services\Webhook;

use App\Dao\Account\AccountDao;
use App\Dao\User\UserDao;
use App\Services\OpenApi\OpenService;
use App\Services\Order\OrderService;

class WebhookService
{
    private $accountDao;
    private $userDao;
    private $openService;

    public function __construct(
        AccountDao  $accountDao,
        UserDao     $userDao,
        OpenService $openService
    )
    {
        $this->accountDao  = $accountDao;
        $this->userDao     = $userDao;
        $this->openService = $openService;
    }

    /**
     * @param $event // 用户咨询私信：trade_event平台校验：verify_webhook
     * @param $data
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handleDouYinEvent($event, $data)
    {
        // 事件判断
        if (!in_array($event, ['verify_webhook', 'trade_event'])) {
            return [];
        }

        // 基本参数
        $clientKey = trim(getProp($data, 'client_key')); // 小程序的 APPID
        $signature = trim(getProp($data, 'signature'));  // 消息签名，用户安全校验
        $eventId   = (int)getProp($data, 'event_id', 0); // 事件 ID 默认 0
        $content   = getProp($data, 'content', []);      //具体内容
        $challenge = getProp($content, 'challenge', '');

        // 用户咨询私信
        if ($event === 'trade_event') {
            // 基本参数
            $orderId       = getProp($content, 'order_id');                    // 订单号
            $openId        = getProp($content, 'customer_uid');                // 用户的 openId
            $serviceOpenId = getProp($content, 'sp_uid');                      // 客服的 openId
            $conversionId  = getProp($content, 'conversation_short_id');       // 会话 ID，加密

            // 获取小程序信息
            $app = $this->accountDao->getMiniAppByAppId($clientKey);
            if ($app) {
                // 获取用户信息
                $user = $this->userDao->getUserByOpenId($openId);
                if (empty($user)) {
                    return compact('challenge');
                }

                // 获取订单信息
                $order = OrderService::getByTikTokOrderId($orderId);
                if (getProp($user, 'id') != getProp($order, 'uid')) {
                    return compact('challenge');
                }

                // 发送私信
                $this->openService->getOpenInstance([
                    'app_id' => getProp($app, 'app_id'),
                    'secret' => getProp($app, 'app_secret'),
                ])->senImMsg($serviceOpenId, [
                    'conversion_id' => $conversionId,              // 会话id
                    'send_url'      => getProp($order, 'pay_url'), // 支付链接
                    'to_user_id'    => $openId,
                    'msg_type'      => 1, // 1-发送支付链接 2-发送支付成功
                ]);
            }
        }

        return compact('challenge');
    }
}