<?php

namespace addons\shopro\controller\user;

use addons\shopro\controller\Common;
use app\admin\model\shopro\xhs\AdTracking as AdTrackingModel;
use app\admin\model\shopro\xhs\ConversionLog as ConversionLogModel;

/**
 * 小红书聚光「种草直达-微信小程序」广告追踪 & 转化回传
 */
class XhsAd extends Common
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 接收追踪参数接口
     * 小程序从广告跳入时调用，存储 click_id 与用户绑定
     *
     * POST /addons/shopro/user.xhs_ad/track
     * @param click_id     string  小红书广告点击唯一标识（必填）
     * @param request_id   string  小红书广告请求 ID
     * @param event_type   string  事件类型（如 122）
     * @param landing_page string  落地页路径
     */
    public function track()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $params = $this->request->only(['click_id', 'request_id', 'event_type', 'landing_page']);
        $this->svalidate($params, '.track');

        $user = auth_user();
        $userId = $user->id ?? 0;

        custom_log('[xhs.track] 收到追踪请求, user_id=' . $userId . ', params=' . json_encode($params, JSON_UNESCAPED_UNICODE), $userId, 'xhs_ad');

        // if (empty($userId)) {
        //     custom_log('[xhs.track] user_id 为空，拒绝记录', $userId, 'xhs_ad', 'warning');
        //     $this->error('用户未登录');
        // }

        if (empty($params['click_id'])) {
            custom_log('[xhs.track] click_id 为空，拒绝记录', $userId, 'xhs_ad', 'warning');
            $this->error('缺少 click_id 参数');
        }

        // 记录/更新追踪信息
        $tracking = AdTrackingModel::record([
            'user_id'      => $userId,
            'click_id'     => $params['click_id'],
            'request_id'   => $params['request_id'] ?? '',
            'event_type'   => $params['event_type'] ?? '',
            'landing_page' => $params['landing_page'] ?? '',
            'platform' => 'BEEVERA WechatMiniProgram',
        ]);

        if (!$tracking) {
            custom_log('[xhs.track] 追踪记录写入失败, user_id=' . $userId, $userId, 'xhs_ad', 'warning');
            $this->error('记录追踪信息失败');
        }

        custom_log('[xhs.track] 追踪记录成功, tracking_id=' . $tracking->id . ', click_id=' . $params['click_id'], $userId, 'xhs_ad');

        $this->success('记录成功', [
            'tracking_id' => $tracking->id,
        ]);
    }

    /**
     * 转化事件记录接口
     * 用户在小程序内完成转化后调用，触发异步回传
     *
     * POST /addons/shopro/user.xhs_ad/conversion
     * @param conversion_type  string  转化类型: register/order/payment/add_wechat（必填）
     * @param value            float   转化金额
     * @param order_id         string  订单号
     */
    public function conversion()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }

        $params = $this->request->only(['click_id', 'conversion_type', 'value', 'order_id']);
        $this->svalidate($params, '.conversion');

        $user = auth_user();
        $userId = $user->id ?? 0;

        custom_log('[xhs.conversion] 收到转化记录请求, user_id=' . $userId . ', params=' . json_encode($params, JSON_UNESCAPED_UNICODE), $userId, 'xhs_ad');

        // if (empty($userId)) {
        //     custom_log('[xhs.conversion] user_id 为空', $userId, 'xhs_ad', 'warning');
        //     $this->error('用户未登录');
        // }

        $clickId = $params['click_id'];
        $conversionType = $params['conversion_type'];
        $value = floatval($params['value'] ?? 0);
        $orderId = $params['order_id'] ?? '';

        // 查询有效追踪记录（用于关联 tracking_id）
        $tracking = AdTrackingModel::getValidByUser($userId);
        $trackingId = $tracking ? $tracking->id : 0;
        $status = ConversionLogModel::STATUS_PENDING;

        // 去重检查
        if (ConversionLogModel::isDuplicated($clickId, $conversionType, $orderId)) {
            custom_log('[xhs.conversion] 重复转化，拒绝记录, click_id=' . $clickId . ', type=' . $conversionType . ', order=' . $orderId, $userId, 'xhs_ad', 'warning');
            $this->error('该转化事件已记录，请勿重复提交');
        }

        $now = time();

        // 写入转化日志
        try {
            $log = ConversionLogModel::create([
                'user_id'         => $userId,
                'tracking_id'     => $trackingId,
                'click_id'        => $clickId,
                'conversion_type' => $conversionType,
                'value'           => $value,
                'order_id'        => $orderId,
                'status'          => $status,
                'retry_count'     => 0,
                'conversion_time' => $now,
                'createtime'      => $now,
                'updatetime'      => $now,
            ]);

            custom_log('[xhs.conversion] 转化日志写入成功, log_id=' . $log->id . ', status=' . $status, $userId, 'xhs_ad');
        } catch (\Exception $e) {
            custom_log('[xhs.conversion] 转化日志写入失败: ' . $e->getMessage(), $userId, 'xhs_ad', 'error');
            $this->error('记录转化事件失败');
        }

        // 如果有有效 click_id，投递异步队列回传
        if ($status === ConversionLogModel::STATUS_PENDING && !empty($clickId)) {
            try {
                $jobData = [
                    'log_id'          => $log->id,
                    'user_id'         => $userId,
                    'click_id'        => $clickId,
                    'conversion_type' => $conversionType,
                    'value'           => $value,
                    'order_id'        => $orderId,
                    'conversion_time' => $now,
                    'platform'        => 'WechatMiniProgram',
                ];

                \think\Queue::push('\addons\shopro\job\XhsConversionReport@exec', $jobData, 'shopro');

                custom_log('[xhs.conversion] 异步队列投递成功, log_id=' . $log->id, $userId, 'xhs_ad');
            } catch (\Exception $e) {
                custom_log('[xhs.conversion] 异步队列投递失败: ' . $e->getMessage(), $userId, 'xhs_ad', 'error');
                // 队列投递失败不阻塞主流程，后续可手动重试
            }
        }

        $this->success('转化事件记录成功', [
            'log_id' => $log->id,
            'status' => $status,
        ]);
    }
}
