<?php

namespace Modules\User\Traits;

use App\Models\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Modules\User\Models\UserDynamic;

trait WithUserDynamic
{

    /**
     * Notes: 关联动态数据
     *
     * @Author: 玄尘
     * @Date: 2023/3/17 13:59
     * @return MorphMany
     */
    public function userDynamics(): MorphMany
    {
        return $this->morphMany(UserDynamic::class, 'orderable');
    }

    /**
     * Notes: 我的动态
     *
     * @Author: 玄尘
     * @Date: 2023/3/17 14:00
     * @return mixed
     */
    public function dynamics()
    {
        return $this->hasMany(UserDynamic::class);
    }

    /**
     * Notes: 添加动态
     *
     * @Author: 玄尘
     * @Date: 2023/3/17 14:01
     * @param  Model  $model
     * @param  int  $user_id
     * @param  int  $operator_id  操作人
     * @param  string|null  $remark
     * @param  array|null  $source
     * @return Builder|\Illuminate\Database\Eloquent\Model
     */
    public function addDynamic(
        Model $model,
        int $user_id = 0,
        int $operator_id = 0,
        string $remark = null,
        array $source = null
    ) {
        return UserDynamic::query()
            ->create([
                'user_id'        => $user_id,
                'operator_id'    => $operator_id,
                'orderable_type' => get_class($model),
                'orderable_id'   => $model->getKey(),
                'remark'         => $remark,
                'source'         => $source,
            ]);
    }
}