<?php

namespace Modules\User\Models\Traits;

use Illuminate\Database\Eloquent\Relations\HasMany;
use Modules\User\Models\UserPerf;

trait HasPerf
{
    public function perf(): HasMany
    {
        return $this->hasMany(UserPerf::class);
    }

    /**
     * Notes: description
     *
     * @Author: 玄尘
     * @Date  : 2022/8/30 14:59
     * @param $perf   业绩
     * @param $order  升级订单
     * @param $remark
     */
    public function addPerf($perf = 0, $order, $remark = '订单获得')
    {
        if ($perf) {
            $this->perf()->create([
                'order_type' => $order->getMorphClass(),
                'order_id'   => $order->id,
                'layer'      => $this->relation->layer,
                'parent_id'  => $this->relation->parent_id,
                'bloodline'  => $this->relation->bloodline,
                'perf'       => $perf,
                'remark'     => $remark,
            ]);
        }
    }

    /**
     * Notes: 推荐业绩
     *
     * @Author: 玄尘
     * @Date  : 2022/8/30 14:59
     * @return mixed
     */
    public function recommendPerf()
    {
        return UserPerf::where('user_id', $this->id)
                       ->orWhere('parent_id', $this->id)
                       ->sum('perf');
    }

    /**
     * Notes: 总业绩
     *
     * @Author: 玄尘
     * @Date  : 2022/8/30 15:00
     * @return mixed
     */
    public function allPerf(array $timeBetween = null)
    {
        return UserPerf::where(function ($query) {
            $query->where('user_id', $this->id)
                  ->orWhere('bloodline', 'like', '%,'.$this->id.',%');
        })
                       ->when($timeBetween, function ($query) use ($timeBetween) {
                           $query->whereBetween('created_at', $timeBetween);
                       })
                       ->sum('perf');
    }

}
