<?php

namespace App\Admin\Repositories;

use App\Models\BaseProductCategory as Model;
use App\Models\BaseProductParameter;
use Dcat\Admin\Repositories\EloquentRepository;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Dcat\Admin\Traits\ModelTree;
use Illuminate\Support\Facades\Session;

class BaseProductCategory extends EloquentRepository
{

    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;




    // 调用模型方法
    public static function selectOptions(\Closure $closure = null)
    {
        if (!$closure) {
            $closure = function ($query) {
                $query = $query->where('enabled', 1);
                $query =  $query->orderBy('order', 'asc');
                return $query;
            };
        }

        $selectOptions =  Model::class::selectOptions($closure);
        return $selectOptions;
    }

    public static function selectMainOptions(\Closure $closure = null)
    {
        $query = Model::query();

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

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

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

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

        $all = array_replace([0 => admin_trans_label('root')],$results->all());
        return $all;
    }


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

    /*
     * 改写列表显示返回的数据
     */
    public function get(Grid\Model|\Dcat\Admin\Grid\Model $model)
    {

        // 获取模型对象
        $obj = $this->model();
        // 获取数据
        $tree = $obj->orderBy('order', 'desc')->orderBy('id', 'desc')->get();

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

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

}
