<?php
// 表中存在软删除时,调用该模块,实现树行结构
namespace App\Models;

use Dcat\Admin\Traits\ModelTree;


trait NewModelTree
{
    use ModelTree;
    protected function buildSelectOptions(array $nodes = [], $parentId = 0, $prefix = '', $space = '&nbsp;', $cid = 0)
    {
        $d = '├─';
        $prefix = $prefix ?: $d . $space;

        $options = [];

        if (empty($nodes)) {
            if ($cid > 0) {
                $where = ['deleted_at' => null, 'c_id' => $cid];
            } else {
                $where = ['deleted_at' => null];
            }
            $nodes = self::where($where)->orderBy('order', 'desc')->get()->toArray();
        }
        foreach ($nodes as $index => $node) {
            if ($node[$this->getParentColumn()] == $parentId) {

                $currentPrefix = $this->hasNextSibling($nodes, $node[$this->getParentColumn()], $index) ? $prefix : str_replace($d, '└─', $prefix);

                $node[$this->getTitleColumn()] = $currentPrefix . $space . $node[$this->getTitleColumn()];

                $childrenPrefix = str_replace($d, str_repeat($space, 6), $prefix) . $d . str_replace([$d, $space], '', $prefix);

                $children = $this->buildSelectOptions($nodes, $node[$this->getKeyName()], $childrenPrefix);

                $options[$node[$this->getKeyName()]] = $node[$this->getTitleColumn()];

                if ($children) {
                    $options += $children;
                }
            }
        }
        return $options;
    }
}