<?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', 'desc')->orderBy('id', 'desc');
                return $query;
            };
        }

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

    public static function selectMainOptions(\Closure $closure = null)
    {
        if (!$closure) {
            $closure = function ($query) {
                $query =  $query->orderBy('order', 'desc')->orderBy('id', 'desc');
                return $query;
            };
        }
        $selectOptions =  Model::class::selectOptions($closure);
        //只显示2层
        foreach ($selectOptions as $key => $value) {
            if (substr_count($value,'&nbsp;') > 8) {
                unset($selectOptions[$key]);
            }
        }
        return $selectOptions;
    }


    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();
        $treeData = $tree->toArray();
        foreach ($tree as $key => $value) {
            $treeData[$key]['baseProductParameter.name'] = $value->baseProductParameter->name?? '';
        }
        // 构建树形结构
        $data=buildTree($treeData);

        // 转换成一维数组
        $data=flattenTree($data);

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



}
