<?php

namespace App\Distributor\Repositories;

use App\Models\DistProductCategory as Model;

use App\Models\DistProductParameter;
use Dcat\Admin\Repositories\EloquentRepository;
use Illuminate\Support\Facades\Session;

class DistProductCategory extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public function __construct()
    {

    }

    // 调用模型方法
    public static function selectMainOptions(\Closure $closure = null)
    {
        // 获取当前登录的分销商/经销商
        $distributor=Session::get('distributor');

        // 过滤分销商
        if (!$distributor)
        {
            return false;
        }

        $query = Model::query();

        //通过传入条件限制
        if ($closure) {
            $closure($query);
        }

        // 确保查询构造器不为空
        if (!$query) {
            return [];
        }

        // 过滤分销商
        $query->where('dist_id', getDistributorId());

        // 返回键值对数组，并按 'name' 和 'order' 字段排序
        $results = $query->orderBy('name')->orderBy('order')->pluck('name', 'id');

        // 在每个 name 前面加上 '├─'
        $results = $results->map(function ($name) {
            return '├─' . $name;
        });

        return $results->all();

    }

    // 调用模型方法
    public static function selectOptions(\Closure $closure = null)
    {
        $selectOptions = Model::class::selectOptions($closure);

        return $selectOptions;
    }


    public static function getParameter($categoryId)
    {
        $categoryRow =  Model::Class::find($categoryId);
        if ($categoryRow->baseProductParameter) {
            return $categoryRow->baseProductParameter->content;
        } else {
            return "[]";
        }
    }

    /**
     * @param Grid\Model|\Dcat\Admin\Grid\Model $model
     * @return array
     */
    public function get(Grid\Model|\Dcat\Admin\Grid\Model $model)
    {

        // 获取模型对象
        $obj = $this->model();

        $obj = $obj->where('dist_id', getDistributorId());

        // 获取数据
        $tree = $obj->get();

        // 构建树形结构
        $data=buildTree($tree->toArray());
        // 转换成一维数组
        $data=flattenTree($data);

        return $model->makePaginator(
            count($data), // 传入总记录数
            $data // 传入数据二维数组
        );
    }


}
