<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\MenuT;
use common\models\PermissionsT;
use common\models\UserT;
use Yii;
use yii\web\Response;

class PermissionsController extends \yii\web\Controller
{
    public $my = null;
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';

    public function init()
    {
        parent::init();

        $cookie = Yii::$app->request->cookies;
        $user_id = MyLib::encrypt($cookie->get('aid'),'DECODE');

        if($user_id != 0)
        {
            $this->my = UserT::findOne(['id'=>$user_id]);
        } else {
            Yii::$app->response->redirect('/common/login')->send();
            exit;
        }
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionIndexJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $items = PermissionsT::find()->all();

        $data = [];
        $data['total'] = count($items);
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        if($id > 0) {
            $info = PermissionsT::findOne(['id'=>$id]);
        } else {
            $info = new PermissionsT();
        }

        return $this->render('edit',[
            'info' => $info
        ]);
    }

    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $name = $request->post('name');

            if($name == '') {
                $result['msg'] = '请输入名称!';
                return $result;
            }

            $tran = PermissionsT::getDb()->beginTransaction();

            try {
                $row = null;
                if($id > 0) {
                    $row = PermissionsT::findOne(['id'=>$id]);
                } else {
                    $row = new PermissionsT();
                }
                $row->name = $name;
                $row->save();

                $tran->commit();
            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $id = $request->post('id',0);

            if($id > 0) {
                $tran = PermissionsT::getDb()->beginTransaction();
                try {
                    $row = PermissionsT::findOne(['id'=>$id]);
                    $row->unlinkAll('menus',true);
                    $row->delete();

                    $tran->commit();
                } catch(\Exception $e) {
                    $tran->rollBack();
                    throw $e;
                }

                $result['success'] = true;
                $result['msg'] = '删除成功';
            }
        }
        return $result;
    }

    public function actionPermission()
    {
        $request = Yii::$app->request;
        if($request->isPost) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $result = array();
            $result['success'] = false;
            $result['msg'] = '保存失败';

            $id = $request->post('group_id',0);
            $menu_ids = $request->post('menu_ids',array());

            $tran = PermissionsT::getDb()->beginTransaction();

            try {
                $row = null;
                if($id > 0) {
                    $row = PermissionsT::findOne(['id'=>$id]);
                } else {
                    return $result;
                }

                $row->unlinkAll('menus',true);
                foreach($menu_ids as $menu_id) {
                    $menu_item = MenuT::findOne(['id'=>$menu_id]);
                    $row->link('menus',$menu_item);
                    $tmp_total = $row->getMenus()->where('id='.$menu_item->parent_id)->count();
                    if($tmp_total == 0) {
                        $parent = $menu_item->parent;
                        if($parent)
                            $row->link('menus',$parent);
                    }
                }

                $tran->commit();
            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }

            $result['success'] = true;
            $result['msg'] = '保存成功';
            return $result;
        }

        $id = $request->get('id',0);
        $permissions_info = PermissionsT::findOne(['id'=>$id]);
        $menus = $permissions_info->menus;
        $menu_ids = array();
        foreach($menus as $item) {
            $menu_ids[] = $item->id;
        }
        $menu_items = MenuT::find()
            ->where('parent_id=0')
            ->orderBy('order_id','asc')
            ->all();

        return $this->render('permission',[
            'permissions_info' => $permissions_info,
            'menu_items' => $menu_items,
            'permissions_id' => $id,
            'menu_ids' => $menu_ids
        ]);
    }
}
