<?php

namespace app\admin\model\shopro\xhs;

use app\admin\model\shopro\Common;

/**
 * 小红书转化回传日志模型
 */
class ConversionLog extends Common
{
    protected $name = 'xhs_conversion_log';

    protected $updateTime = 'updatetime';
    protected $createTime = 'createtime';
    protected $autoWriteTimestamp = 'integer';

    // 回传状态
    const STATUS_PENDING    = 0; // 待回传
    const STATUS_SUCCESS    = 1; // 回传成功
    const STATUS_FAILED     = 2; // 回传失败
    const STATUS_NO_TRACK   = 3; // 无需回传（无有效 click_id）
    const STATUS_EXPIRED    = 4; // 追踪已过期

    // 最大重试次数（对齐小红书官方要求 30 次）
    const MAX_RETRY = 30;

    /**
     * 状态文本映射
     * @return array
     */
    public function statusList()
    {
        return [
            self::STATUS_PENDING   => '待回传',
            self::STATUS_SUCCESS   => '回传成功',
            self::STATUS_FAILED    => '回传失败',
            self::STATUS_NO_TRACK  => '无需回传',
            self::STATUS_EXPIRED   => '追踪已过期',
        ];
    }

    /**
     * 去重检查：同一 click_id + conversion_type + order_id 不可重复回传
     *
     * @param string $clickId
     * @param string $conversionType
     * @param string $orderId
     * @return bool
     */
    public static function isDuplicated($clickId, $conversionType, $orderId)
    {
        if (empty($clickId) || empty($conversionType)) {
            return false;
        }

        $where = [
            'click_id'        => $clickId,
            'conversion_type' => $conversionType,
        ];

        if (!empty($orderId)) {
            $where['order_id'] = $orderId;
        }

        return self::where($where)->find() ? true : false;
    }
}
