<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Session;
use Spatie\EloquentSortable\Sortable;
use Illuminate\Database\Eloquent\Scope;

use App\Distributor\Scopes;
class DistProductCategory extends Model implements Sortable
{
    use HasDateTimeFormatter,
        ModelTree {
        ModelTree::boot as treeBoot;
    }
	use HasDateTimeFormatter;
    protected $table = 'dist_product_category';

    //名称
    protected $titleColumn = 'name';
    //排序
    protected $orderColumn = 'order';
    //父级
    protected $parentColumn = 'parent_id';


    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];

    protected $fillable = [
        'name', 'parent_id', 'order','enabled','dist_id','slug', // 假设已有的可填充字段
    ];


    protected $distributor = null;


    public function __construct()
    {

//        // 获取当前登录的分销商/经销商
//        $distributor=Session::get('distributor');
//
//
//
//            // 过滤分销商
//        if ($distributor) {
//
//                $this->dist_id =$distributor->id;
//        }
//


    }

    protected static function boot()
    {
        var_dump('ufoxguo');
        parent::boot();

        static::addGlobalScope(new VerifiedDistId());
    }

//    protected static function booted()
//    {
//
//        static::addGlobalScope('dist_id', function (Builder $builder) {
//            // 获取当前登录的分销商/经销商
//            $distributor=Session::get('distributor');
//
//            // 过滤分销商
//            if (!$distributor) {
//                $builder->where('dist_id', $distributor->id); // 替换为你的条件
//            }
//        });
//
//    }

    /*
     * 关联产品参数
     */
    public function distProductParameter()
    {
        return $this->hasOne(DistProductParameter::class,'id','parameter_id');
    }


    public static function selectOptions(\Closure $closure = null)
    {
        $options = (new static())->withQuery($closure)->buildSelectOptions();
        return collect($options)->all();
    }
    public function getAllCategories($parentId = null)
    {
        // Retrieve categories with the specified parentId, or all if no parentId is specified
        $query = self::query();

        if ($parentId !== null) {
            $query->where('parent_id', $parentId);
        }

        $categories = $query->orderBy($this->orderColumn)->get();

        // If you want a hierarchical structure, you can recursively build it
        $categories->each(function ($category) {
            $category->children = $category->getAllCategories($category->id);
        });

        return $categories;
    }

}