<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace qcbase\controllers;

use Yii;
use qcbase\models\Menu;
use yii\helpers\Url;
use yii\data\ActiveDataProvider;

/**
 * 后台菜单控制器
 * 
 * @author  hulimin http://blog.u-bo.com
 * @since 0.1
 */
class MenuController extends Controller
{

    public function actions()
    {
        return [
            'create' => [
                'class' => 'qcbase\actions\Create',
            ],
            'view' => [
                'class' => 'qcbase\actions\View',
            ],
            'update' => [
                'class' => 'qcbase\actions\Update',
            ],
            'sort' => [
                'class' => 'qcbase\actions\Sort',
            ],
        ];
    }

    /**
     * 菜单列表页管理
     */
    public function actionIndex()
    {
        $appArr = [
            'qcbase' => [
                'name' => '后台基础框架',
                'value' => 'admin',
                'id' => 0,
            ],
            'home' => [
                'name' => '前台oa系统',
                'value' => 'home',
                'id' => 0,
            ]
        ];
        //搜索
//		$request = Yii::$app->request;
//		$keywords = $request->get('keywords');
//		if (!empty($keywords)) {
//			$field = $request->get('search_field');
//			$query->where(['like', $field, $keywords]);
//		}
        foreach ($appArr as $k => $value) {
            $map = [
                'parent_id' => $value['id'],
                'app_name' => $value['value'],
            ];
            $memu = Menu::find()
                ->where($map)
                ->asArray()
                ->one();
            if (!empty($memu)) {
                $appArr[$k]['expandStatus'] = 0; //存在子菜单,默认不展开
            } else {
                $appArr[$k]['expandStatus'] = 1; //无子菜单，展开
            }
        }
        return $this->render('index', [
                'appArr' => $appArr,
                'model' => new Menu(),
        ]);
    }

    /**
     * 菜单删除
     */
    public function actionDelete()
    {
        $id = Yii::$app->request->get('id');
        $ids = Yii::$app->request->post('delete');
        $type = Yii::$app->request->get('type');
        $session = Yii::$app->getSession();
        $res = [];
        if (empty($id) && empty($ids)) {
            $res = [
                'status' => 0,
                'key' => 'error',
                'info' => '要删除的对象不存在'
            ];
        } else {
            !empty($id) && $ids[] = $id;
            foreach ($ids as $id) {
                if (!$model = call_user_func([(new Menu()), 'findOne'], $id)) {
                    $res = [
                        'status' => 0,
                        'key' => 'error',
                        'info' => 'ID为' . $id . '的对象不存在'
                    ];
                    break;
                } else {
                    $childCount = Menu::find()->where(['parent_id' => $id])->count();
                    if ($childCount) {
                        $res = [
                            'status' => 0,
                            'key' => 'error',
                            'info' => '请先删除' . $id . '的子菜单'
                        ];
                        break;
                    }
                }
                $model->delete();
            }
            if (empty($res)) {
                $res = [
                    'status' => 1,
                    'key' => 'success',
                    'info' => '删除成功'
                ];
            }
        }
        if ($type == 'ajaxdelete') {
            return \Yii::createObject([
                    'class' => 'yii\web\Response',
                    'format' => \yii\web\Response::FORMAT_JSON,
                    'data' => $res,
            ]);
        } else {//ajax请求删除
            $session->setFlash($res['key'], $res['info']);
            return $this->flash();
        }
    }

    /**
     * ajax获取子菜单
     */
    public function actionGetMenuList()
    {
        $model = new Menu();
        $request = Yii::$app->request;
        $app_name = $request->post('app_name');
        $id = $request->post('id');
        $level = $request->post('level');
        $map = [
            'app_name' => $app_name,
            'parent_id' => $id,
        ];
        $order = [
            'sort' => SORT_ASC,
            'menu_id' => SORT_ASC
        ];
        $level++; //增一级
        $leftPx = $level * 8;
        $menuList = $model->getMenu($map, $order);
        $json = [
            'data' => '',
            'status' => 0
        ];
        if (!empty($menuList)) {
            foreach ($menuList as $k => $r) {
                $mapChild = [
                    'parent_id' => $r['menu_id'],
                    'app_name' => $app_name,
                ];
                $memuChild = $model->find()
                    ->where($mapChild)
                    ->asArray()
                    ->one();
                if (!empty($memuChild)) {
                    $deleteUrl = 'javascript:;';
                    $classInfo = 'link-undelete gray';
                    $expandInfo = "<span  style='margin-left:{$leftPx}px'class='plus_icon'></span><span data-id='{$r['menu_id']}' data-app_name='{$app_name}'  class='J_start_icon  away_icon expandChild' title='点击展开'  data-expand-status='0' data-level='{$level}' ></span>";
                } else {
                    $deleteUrl = Url::to(['menu/delete', 'id' => $r['menu_id']]);
                    $classInfo = 'menu-delete';
                    $expandInfo = "<span class='plus_icon' style='margin-left:{$leftPx}px' ></span><span data-id='{$r['menu_id']}' data-app_name='{$app_name}'  class='J_start_icon  start_icon'  data-expand-status='1' data-level='{$level}' ></span>";
                }

                $str_is_auth = ($r['is_auth'] == Menu::ISAUTH_ENABLE) ? "权限认证+菜单" : "只作为菜单";
                $str_status = ($r['status'] == Menu::STATUS_ENABLE) ? '<font color="green">显示</font>' : '<font color="red">隐藏</font>';
                $str_operation = "<a href='javascript:void(0);' data-href='" . Url::to(['menu/view',
                        'id' => $r['menu_id']]) . "' class='editByIframe' data-id='editMenu{$r['menu_id']}' data-title='编辑菜单-{$r['name']}'>编辑</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='javascript:void(0);' data-href='" . Url::to(['menu/create',
                        'app_name' => $r['app_name'],
                        'menu_id' => $r['menu_id']]) . "' class='editByIframe' data-id='createMenu' > 添加子菜单</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href ='" . $deleteUrl . "' class = '" . $classInfo . "' >删除</a>";
                $json['data'].=<<<HTML
				<tr data-class-id="{$r['menu_id']}" data-parent-class="{$id}">
                <td><input type="checkbox" name="delete[]" class="box-delete" value="{$r['menu_id']}" /></td>
				<td><input type="text" size="4" value="{$r['sort']}" class="input" name="sort[{$r['menu_id']}]" /></td>
				<td>{$r['menu_id']}</td>
                <td>{$expandInfo}{$r['name']}</td>
                <td>{$r['module']}</td>
                <td>{$r['controller']}</td>
                <td>{$r['action']}</td>
                <td>{$str_is_auth}</td>
                <td>{$str_status}</td>
                <td align="center">{$str_operation}</td>
HTML;
            }
            $json['status'] = 1;
        }
        return \Yii::createObject([
                'class' => 'yii\web\Response',
                'format' => \yii\web\Response::FORMAT_JSON,
                'data' => $json,
        ]);
    }

    /**
     * 获取应用下菜单
     */
    public function actionGetAppMenu()
    {
        $appName = Yii::$app->request->get('app_name');
        $parentId = Yii::$app->request->get('parent_id');
        $disabledId = Yii::$app->request->get('disabled_id');
        $menuData = Menu::getMenuTree(trim($appName), intval($parentId), intval($disabledId));
        return \Yii::createObject([
                'class' => 'yii\web\Response',
                'format' => \yii\web\Response::FORMAT_JSON,
                'data' => $menuData,
        ]);
    }

    /**
     * 菜单搜索
     */
    public function actionSearchMenu()
    {
        $model = new Menu();
        $query = call_user_func([$model, 'find']);
        //搜索
        $request = Yii::$app->request;
        $keywords = $request->get('keywords');
        if (!empty($keywords)) {
            $field = $request->get('search_field');
            $query->where(['like', $field, $keywords]);
        }
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);
        if (!empty($provider->models)) {
            foreach ($provider->models as $menu) {
                $appArr = Menu::getAppName();
                $menu->name = $menu->name . "<span style='color:gray'>[" . $appArr[$menu->app_name] . "]";
            }
        }
        return $this->render('searchMenu',
                [
                'get' => $request->get(),
                'model' => $model,
                'models' => $provider->models,
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 批量修复权限节点
     */
    public function actionUpdateAuth()
    {
        if (Yii::$app->request->isPost) {
            $id = Yii::$app->request->post('id');
            $auth_url = Yii::$app->request->post('auth_url');
            $auth_description = Yii::$app->request->post('name');
            $json = [
                'status' => 1,
                'msg' => '"' . $auth_description . '"节点更新成功！',
            ];
            if (!empty($auth_url)) {
                $result = \qcbase\models\Auth::authItem($auth_url, $auth_description, 1, $auth_url);
                if ($result == FALSE) {
                    $json = [
                        'status' => 0,
                        'msg' => '"' . $auth_description . '"节点更新失败！',
                    ];
                }
            }
            $info = Menu::find()
                ->where(['and', 'is_auth=1', 'menu_id>' . $id])
                ->orderBy(['menu_id' => SORT_ASC])
                ->asArray()
                ->one();
            if (!empty($info)) {
                $json['menu_id'] = $info['menu_id'];
                $json['name'] = $info['name'];
                $json['auth_url'] = $info['auth_url'];
            } else {
                $json['status'] = 2;
                $json['info'] = '节点修复完毕！';
            }
            return \Yii::createObject([
                    'class' => 'yii\web\Response',
                    'format' => \yii\web\Response::FORMAT_JSON,
                    'data' => $json,
            ]);
        } else {
            $info = Menu::find()
                ->where(['is_auth' => 1])
                ->orderBy(['menu_id' => SORT_ASC])
                ->asArray()
                ->one();
            return $this->render('updateAuth', [
                    'info' => $info
            ]);
        }
    }

    public function actionUpdateAllMenu()
    {
        if (\home\models\Menu::repairMenu()) {
            return $this->flash('更新成功！', 'success');
        } else {
            return $this->flash('更新失败，请稍后再试！', 'error');
        }
    }
}
