<?php
/**
 * Created by PhpStorm.
 * User: chenkuan
 * Date: 2017/12/19
 * Time: 上午9:54
 */

namespace frontend\modules\cp\controllers;


use frontend\models\behaviors\NoCSRFBehavior;
use frontend\models\RoleApi;
use yii\helpers\Url;

class RoleController extends BaseController
{
    public function behaviors()
    {
        return [
            'csrf' => [
                'class' => NoCSRFBehavior::className(),
                'controller' => $this,
                'actions' => [
                    'delete'
                ],
            ],
        ];
    }

    /**
     * 角色管理列表
     */
    public function actionList()
    {
        $request = \Yii::$app->request->get();
        $data['pageNumber'] = isset($request['pageNumber']) ? (int)$request['pageNumber'] : 1;
        $data['pageSize'] = isset($request['pageSize']) ? (int)$request['pageSize'] : 20;
        $data['orderBy'] = isset($request['orderBy']) ? $request['orderBy'] : 'id';
        $data['order'] = isset($request['order']) ? $request['order'] : 'asc';
        $data['keyword'] = isset($request['keyword']) ? $request['keyword'] : '';
        $data['searchBy'] = isset($request['searchBy']) ? $request['searchBy'] : 'name';

        $api = new RoleApi();
        $rs = $api->getRoleList($data);
        return $this->renderPartial('list', [
            'data' => $rs['data'],
            'vars' => $data,
        ]);
    }

    /**
     * 添加角色管理类别
     */
    public function actionAdd()
    {
        $isAddAction = true;
        $role = [];
        return $this->renderPartial('add', [
            'role' => $role,
            'isAddAction' => $isAddAction,
        ]);
    }

    /**
     * 新增/修改
     */
    public function actionSave()
    {
        $request = \Yii::$app->request->post();
        $request['authorityList'] = isset($request['authorityList']) ? (array)$request['authorityList'] : '';

        $api = new RoleApi();
        $rs = $api->saveRole($request);
        if ($rs['code'] == 1) {
            return $this->redirect(['list']);
        } else {
            if (empty($request['id'])) {
                $redirectUrl = Url::to(['/cp/role/add']);
            } else {
                $redirectUrl = Url::to(['/cp/role/edit?id='.$request['id']]);
            }
            return $this->redirect(['error/index?redirectUrl='.$redirectUrl.'&tip='.$rs['message']]);
        }
    }

    /**
     * 修改页面
     */
    public function actionEdit()
    {
        $data['id'] = \Yii::$app->request->get('id');
        $api = new RoleApi();
        $rs = $api->getRoleDetail($data);
        return $this->renderPartial('add', [
            'role' => $rs['data'],
            'isAddAction' => false,
            'userId' => $data['id'],
        ]);
    }

    /**
     * 删除
     */
    public function actionDelete()
    {
        $data['ids'] = \Yii::$app->request->post('ids', '');
        $api = new RoleApi();
        $rs = $api->deleteRole($data);
        return $this->asJson($rs);
    }
}
