<?php

namespace frontend\modules\api\controllers;

use common\components\AjaxException;
use common\models\BaseMenu;
use common\models\BaseRole;
use common\models\BaseRoleClientRules;
use common\services\MenuService;
use common\services\RoleService;
use frontend\modules\api\components\BaseAdminController;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\Response;

class PermissionController extends BaseAdminController
{
    /**
     * 路由列表
     * @param int $current
     * @param int $page
     * @return Response
     */
    public function actionRoute(int $current = 1, int $page = 10)
    {
        //公共部分
        $query = BaseMenu::find()
            ->limit($page)
            ->offset(($current - 1) * $page);
        //排序
        $this->initSequence($query);
        //主要筛选条件
        $query = $this->addConditionToQuery("id", $query);
        $query = $this->addConditionToQuery("url", $query, true);
        $query = $this->addConditionToQuery("name", $query, true);
        $query = $this->addConditionToQuery("type", $query);
        $query = $this->addConditionToQuery("status", $query);
        //组合数据
        $data['data'] = $query->asArray()->all();
        $data['total'] = $query->count();
        return $this->asJson($data);
    }

    /**
     * 刷新路由
     * @return Response
     */
    public function actionRouteRefresh()
    {
        $data = Yii::$app->request->post();
        $arr = [];
        $defaultArr = [
            "/",
            "/login",
            "/register",
            "/redirect",
            "/permission",
            "/permission/index",
            "/permission/role",
            "/permission/route",
            "/:pathMatch(.*)",
            "/redirect/:path(.*)",
        ];
        //获取客户端权限
        if ($data['menu']) {
            $i = 0;
            foreach ($data['menu'] as $value) {
                if (in_array($value['path'], $defaultArr)) {
                    continue;
                }
                $arr[$i]['url'] = $value['path'];
                $arr[$i]['name'] = $value['name'];
                $i++;
            }
        }
        foreach ($arr as $value) {
            //如果没有则插入
            $mInfo = BaseMenu::findOne(['url' => $value['url']]);
            if ($mInfo) {
                //如果有，则修改
                $mInfo->name = $value['name'];
                $mInfo->save();
            } else {
                //插入
                $params = [
                    'url' => $value['url'],
                    'name' => $value['name'],
                    'type' => 2,
                    'status' => 1,
                ];
                $insertInfo = new BaseMenu($params);
                $insertInfo->save();
            }
        }
        //找父级
        $all = BaseMenu::find()
            ->select("url,parentid,status")
            ->where(['status' => 1])
            ->orderBy("url asc")
            ->asArray()
            ->all();
        foreach ($all as $key => $value) {
            $newUrl = $value['url'];
            $n = mb_substr_count($newUrl, '/');
            if ($n > 0) {
                $urlArray = explode('/', $newUrl);
                $parentUrl = "";
                foreach ($urlArray as $urlArrayKey => $url) {
                    if ($urlArrayKey >= $n) {
                        break;
                    }
                    if ($urlArrayKey == 0) {
                        $parentUrl .= $url;
                    } else {
                        $parentUrl .= "/" . $url;
                    }
                }
                $thatOne = BaseMenu::findOne(['url' => $parentUrl]);
                $parent_id = $thatOne->id;
                $thisOne = BaseMenu::findOne(['url' => $value['url']]);
                $thisOne->parentid = $parent_id;
                $thisOne->save();
            }
        }
        //返回
        return $this->asJson($arr);
    }

    /**
     * 读取路由
     * @return Response
     */
    public function actionRouteList()
    {
        //公共部分
        $query = BaseMenu::find()
            ->select('id,url,name,parentid,status')
            ->where(['status' => 1])
            ->orderBy("url asc");
        $data['route'] = MenuService::getMenuObjData($query->all());
        return $this->asJson($data);
    }

    /**
     * 路由修改
     * @param $url
     * @param $name
     * @param $status
     * @return Response
     */
    public function actionRouteUpdate($url, $name, $status)
    {
        $info = BaseMenu::findOne(['url' => $url]);
        if ($info) {
            $info->name = $name;
            $info->status = $status;
            $info->save();
        }
        $data = [];
        return $this->asJson($data);
    }

    /**
     * 角色列表
     * @param int $current
     * @param int $page
     * @return Response
     */
    public function actionRole(int $current = 1, int $page = 10)
    {
        //公共部分
        $query = BaseRole::find()
            ->where("id > 1")
            ->limit($page)
            ->offset(($current - 1) * $page);
        //排序
        $this->initSequence($query);
        //主要筛选条件
        $query = $this->addConditionToQuery("id",  $query);
        $query = $this->addConditionToQuery("name",$query, true);
        $query = $this->addConditionToQuery("status",  $query);
        //组合数据
        $data['data'] = $query->asArray()->all();
        $rules = '';
        //拼接数据
        foreach ($data["data"] as $recordKey => $record) {
            /** @var BaseRoleClientRules $roleMenuInfo */
            $roleMenuInfo = BaseRoleClientRules::find()
                ->select("rules")
                ->where(['role_id' => $record['id']])
                ->one();
            if ($roleMenuInfo) {
                $data['data'][$recordKey]['rules'] = implode(",", json_decode($roleMenuInfo->rules, true));
            } else {
                $data['data'][$recordKey]['rules'] = "";
            }
        }
        $data['total'] = $query->count();
        return $this->asJson($data);
    }

    /**
     * 角色合集
     * @return Response
     */
    public function actionRolesList()
    {
        //公共部分
        $query = BaseRole::find()
            ->select("id,name")
            ->where("id > 1")
            ->orderBy("id desc");
        //组合数据
        $data = $query->asArray()->all();
        $arr = [];
        foreach ($data as $k => $v) {
            $arr[$k] = $v;
        }
        $data['roles'] = $arr;
        return $this->asJson($data);
    }

    /**
     * 角色新增
     * @param $name
     * @param $code
     * @param $status
     * @return Response
     * @throws AjaxException
     */
    public function actionRoleAdd($name, $code, $status)
    {
        RoleService::add($name, $code, $status);
        return $this->asJson();
    }

    /**
     * 角色资料和权限修改
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionRoleUpdate()
    {
        RoleService::update();
        $data = [
            'id' => $_GET['id'],
        ];
        return $this->asJson($data);
    }
}