<?php

namespace App\Admin\Repositories;

use App\Models\DistAppearanceTemplate as Model;
use Dcat\Admin\Repositories\EloquentRepository;

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

    public static function getContent($id)
    {
        $data = Model::where('id', $id)->first();
        if ($data) {
            return $data->content;
        }
        return '';
    }
    public static function getTemplateTree($appearance_id,$dist_id)
    {
        $data = Model::where('appearance_id', $appearance_id)->where('dist_id', $dist_id)->get(['id', 'file_name', 'parent_id','file_type','file_path']);
        return self::buildTree($data->toArray(),0);
    }

    public static function buildTree(array $elements, $parentId = 0) {
        $branch = [];

        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = self::buildTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }

    /*
     * 保存模板内容
     */
    public static function saveContent($id, $content)
    {
        $data = Model::where('id', $id)->first();
        if ($data) {
            $data->content = $content;
            $data->save();
            return true;
        }
        return false;
    }
}
