<?php

namespace App\Admin\Repositories;

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

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

    /*
 * 改写列表显示返回的数据
 */
    public function get(Grid\Model|\Dcat\Admin\Grid\Model $model)
    {
        // 获取模型对象
        $obj = $this->model();
        // 获取数据
        $tree = $obj->orderBy('order', 'desc')->orderBy('id', 'asc')->get();
        $treeData = $tree->toArray();

        // 构建树形结构
        $data=buildTree($treeData);

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


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

    public static function selectMainOptions(\Closure $closure = null)
    {
        if (!$closure) {
            $closure = function ($query) {
                $query =  $query->where("enabled", 1)->orderBy('order', 'desc')->orderBy('id', 'asc');
                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 selectOptions(\Closure $closure = null,$lan = 'cn')
    {
        if (!$closure) {
            $closure = function ($query) {
                $query = $query->where('enabled', 1);
                $query =  $query->orderBy('order', 'desc')->orderBy('id', 'asc');
                return $query;
            };
        }
        $model = new Model();
        if ($lan == 'en') {
            $selectOptions =  $model->selectOptionsEn($closure);
        } else {
            $selectOptions =  $model->selectOptions($closure);
        }
        return $selectOptions;
    }



    public static function siteAlbumFolderSelectOptions($inIds) {
        $ids = self::findIdsWithParents($inIds);
        $result = self::selectOptions(function ($query) use ($ids) {
            $query = $query->wherein('id', $ids);
            $query = $query->where('enabled', 1);
            $query =  $query->orderBy('order', 'desc')->orderBy('id', 'asc');
            return $query;
        });
        unset($result[0]);
        return $result;
    }


    public static function siteAlbumFolderSelectOptionsEn($inIds) {
        $ids = self::findIdsWithParents($inIds);
        $result = self::selectOptions(function ($query) use ($ids) {
            $query = $query->wherein('id', $ids);
            $query = $query->where('enabled', 1);
            $query =  $query->orderBy('order', 'desc')->orderBy('id', 'asc');
            return $query;
        },'en');
        unset($result[0]);
        return $result;
    }

    public static function siteAlbumFolderSelectOptionsAll($lang = 'en') {
        $result = self::selectOptions(function ($query) {
            $query = $query->where('enabled', 1);
            $query =  $query->orderBy('order', 'desc')->orderBy('id', 'asc');
            return $query;
        },$lang);
        unset($result[0]);
        return $result;
    }


    /**
     * 递归查找包括 $inIds 在内的所有记录及其父 ID 的记录
     *
     * @param array $inIds 初始 ID 数组
     * @param array $resultIds 结果 ID 数组（递归时使用）
     * @return array
     */
    public static function findIdsWithParents(array $inIds, array &$resultIds = []): array
    {
        $model = new Model();
        // 查询当前 ID 数组对应的记录
        $folders = $model->whereIn('id', $inIds)->get();

        foreach ($folders as $folder) {
            // 如果当前记录的 ID 尚未加入结果数组，则加入
            if (!in_array($folder->id, $resultIds)) {
                $resultIds[] = $folder->id;
            }

            // 如果当前记录有父 ID，则递归查找父记录
            if ($folder->parent_id) {
                self::findIdsWithParents([$folder->parent_id], $resultIds);
            }
        }

        return $resultIds;
    }

    public static function getAllFolderTabs()
    {
        $model = new Model();
        $folders = $model->where('enabled', 1)->orderBy('order', 'desc')->orderBy('id', 'asc')->get();
        $tabs = [];
        foreach ($folders as $folder) {
            $tabs[$folder->id] = json_decode($folder->show_tabs);
        }
        return $tabs;
    }

}
