<?php

namespace addons\shopro\controller;

use think\Db;
use app\admin\model\shopro\Share as ShareModel;

class Share extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function add()
    {

        if (!$this->request->isPost()) {
            $this->error('');
        }

        $params = $this->request->only(['shareId', 'spm', 'page', 'query', 'from', 'platform']);
        custom_log('[share.add] 解析请求参数: ' . json_encode($params, JSON_UNESCAPED_UNICODE), 0, 'share');

        $user = auth_user();
        $userId = $user->id ?? 0;
        custom_log('[share.add] 用户认证通过, user_id=' . $userId, $userId, 'share');

        $shareInfo = ShareModel::log($user, $params);
        if ($shareInfo) {
            $logData = method_exists($shareInfo, 'toArray') ? $shareInfo->toArray() : json_decode(json_encode($shareInfo), true);
            custom_log('[share.add] 分享记录写入成功, 记录详情: ' . json_encode($logData, JSON_UNESCAPED_UNICODE), $userId, 'share');
        } else {
            custom_log('[share.add] 分享记录写入失败(返回false/空，可能原因: spm为空/shareId无效/自己点自己/5分钟内重复/sharing不存在)', $userId, 'share', 'warning');
        }

        $this->success("");
    }

    /**
     * 查看分享记录
     */
    public function index()
    {
        $user = auth_user();
        $logs = ShareModel::with(['user' => function ($query) {
            return $query->field(['id', 'nickname', 'avatar']);
        }])->where('share_id', $user->id)->paginate($this->request->param('list_rows', 8));

        $this->success('获取成功', $logs);
    }
}
