<?php

namespace app\repository;

use app\traits\cms\ArticleTrait;
use app\traits\cms\MenuTrait;
use tauthz\facade\Enforcer;
use think\Model;
use app\service\Repository;

/**
 * CMS 基础功能仓储
 *
 * Class CmsRepository
 * @package app\repository
 * @method self getInstance(Model $model = null) static
 */
class CmsRepository extends Repository
{
    use MenuTrait;
    use ArticleTrait;

    /**
     * xmSelect下拉列表格式处理
     * 如 [['title' => 'aa', 'value' => 1, 'selected' => true, 'prefix' => '&nbsp;&nbsp;&nbsp;&nbsp;']]
     *
     * @param  array  $data  待处理的数据
     * @param  string  $symbol  分隔符号 默认 &nbsp;
     * @param  int  $repeatNum  重复次数 默认4
     * @return array
     */
    public function handleSelectedList(array $data, string $symbol = '&nbsp;', int $repeatNum = 4): array
    {
        $list = [];
        foreach ($data as $item) {
            $level    = $item['level'] ?? 0;
            $arr = $item;
            $arr['children'] = $arr['children'] ?? [];
            $arr['prefix'] = str_repeat($symbol, $level * $repeatNum);
            $list[] = $arr;
        }

        return $list;
    }

    /**
     * 获取后台用户权限列表
     *
     * @param  int  $accountId
     * @return array
     */
    public function getUserRules(int $accountId): array
    {
        $rules = [];
        $roles = Enforcer::getRolesForUser((string)$accountId);
        foreach ($roles as $role) {
            $rules = array_merge($rules, Enforcer::getPermissionsForUser($role));
        }

        $ruleNameList = [];
        foreach ($rules as $rule) {
            if (isset($rule[2])) {
                $ruleNameList[] = $rule[1].':'.$rule[2];
            } else {
                $ruleNameList[] = $rule[1];
            }
        }

        return array_unique($ruleNameList);
    }
}