<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */
namespace backendApi\modules\v1\controllers;

use backendApi\modules\v1\models\Admin;
use backendApi\modules\v1\models\AdminForm;
use backendApi\modules\v1\models\AdminRoleForm;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\Log;
use common\helpers\Tool;
use Yii;
use backendApi\modules\v1\models\AdminRole;
use backendApi\modules\v1\models\User;
use yii\helpers\Json;

class AdminController extends BaseController
{
    public $modelClass = User::class;
    public function behaviors() {
        $behaviors = parent::behaviors();
        //$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    /**
     * 管理员列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionIndex(){
        $filter = $this->filterCondition([
            'ADMIN_NAME' => 'A.ADMIN_NAME',
            'REAL_NAME' => 'A.REAL_NAME',
            'REMARK' => 'A.REMARK',
            'ROLE_NAME' => 'AR.ROLE_NAME',
            'IS_ENABLE' => 'A.IS_ENABLE',
            'LOGIN_NUMS' => 'A.LOGIN_NUMS',
            'LAST_LOGIN_IP' => 'A.LAST_LOGIN_IP',
            'LAST_LOGIN_AT' => 'A.LAST_LOGIN_AT',
            'BIND_IP' => 'A.BIND_IP',
            'CREATED_AT' => 'A.CREATED_AT',
            'UPDATED_AT' => 'A.UPDATED_AT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
        ]);

        $condition = $filter['condition'];
        $condition .= ' AND A.IS_DEL=0';
        $params = $filter['params'];
        $data = Admin::lists($condition, $params, [
            'select' => 'A.*,AR.ROLE_NAME,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME UPDATE_ADMIN_NAME',
            'from' => Admin::tableName().' AS A',
            'join' => [
                ['LEFT JOIN', AdminRole::tableName().' AS AR', 'A.ROLE_ID=AR.ID'],
                ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'ADMC.ID=A.CREATE_ADMIN'],
                ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'ADMU.ID=A.UPDATE_ADMIN'],
            ],
            'orderBy' => 'A.CREATED_AT ASC',
        ]);
        return static::notice($data);
    }

    /**
     * 添加管理员
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionAdd(){
        if(Yii::$app->request->isPost) {
            return parent::edit(AdminForm::class, '管理员添加成功', null, null, null, function($formModel, $result){
                // 添加操作日志
                // Log::adminHandle('添加管理员:'.$result->ADMIN_NAME);
            });
        }
        // 获取全部管理员角色
        $adminRoles = Cache::getAdminRole();
        return static::notice(['adminRoles'=>$adminRoles]);
    }

    /**
     * 添加管理员
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionEdit(){
        $id = Yii::$app->request->get('id');
        if(Yii::$app->request->isPost){
            return parent::edit(AdminForm::class, '管理员编辑成功', null, null, null, function($formModel, $result){
                // 添加操作日志
                // Log::adminHandle('编辑管理员:'.$result->ADMIN_NAME);
            });
        }
        $oneData = Admin::findOneAsArray(['ID'=>$id]);
        // 获取全部管理员角色
        $adminRoles = Cache::getAdminRole();
        return static::notice(['oneData'=>['adminName'=>$oneData['ADMIN_NAME'],'realName'=>$oneData['REAL_NAME'],'remark'=>$oneData['REMARK'],'isEnable'=>$oneData['IS_ENABLE']?true:false,'isModifyPassword'=>$oneData['IS_MODIFY_PASSWORD']?true:false,'bindIp'=>$oneData['BIND_IP'],'roleId'=>$oneData['ROLE_ID']], 'adminRoles'=>$adminRoles]);
    }

    /**
     * 重置密码
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionChangePassword(){
        $form = new AdminForm();
        $form->scenario = 'changePassword';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->edit()){
            // Log::adminHandle('管理员'.$result->ADMIN_NAME.'重置密码');
            return static::notice('重置密码成功');
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    /**
     * 删除管理员
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionAdminDelete(){
        $adminForm = new AdminForm();
        $result = static::delete(Admin::class, function ($selected) use ($adminForm) {
            $adminForm->beforeDelete($selected);
            // Log::adminHandle('删除审核修改会员状态信息');
        }, function ($selected) use ($adminForm) {
            $adminForm->delete($selected);
            // Log::adminHandle('删除审核修改会员状态信息');
        }, false);
        return $result;

    }

    /**
     * 获取获取全部管理员角色
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRole(){
        $filter = $this->filterCondition([
            'ROLE_NAME' => 'AR.ROLE_NAME',
            'REMARK' => 'AR.REMARK',
            'CREATED_AT' => 'AR.CREATED_AT',
            'UPDATED_AT' => 'AR.UPDATED_AT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
        ]);

        $condition = $filter['condition'];
        $params = $filter['params'];
        $data = AdminRole::lists($condition, $params, [
            'select' => 'AR.ID,AR.ROLE_NAME,AR.REMARK,AR.CREATED_AT,AR.UPDATED_AT,AR.DONT_DEL,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME UPDATE_ADMIN_NAME',
            'from' => AdminRole::tableName().' AS AR',
            'join' => [
                ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'ADMC.ID=AR.CREATE_ADMIN'],
                ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'ADMU.ID=AR.UPDATE_ADMIN'],
            ],
            'orderBy' => 'AR.CREATED_AT ASC',
        ]);
        return static::notice($data);
    }

    /**
     * 添加管理组
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRoleAdd(){
        if (Yii::$app->request->post()) {
            $formModel = new AdminRoleForm();
            $formModel->scenario = 'add';
            if ($formModel->load(Yii::$app->request->post(), '') && $formModel->add()) {
                return static::notice('添加管理员角色成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 编辑管理组
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRoleEdit(){
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return parent::edit(AdminRoleForm::class, '编辑管理员角色成功', 'edit', ['edit'], null, function ($form, $result) {
                Cache::updateAdminRole();
            });
        }
        // 获得当前会员的用户名等信息
        if (!$role = AdminRole::findOneAsArray('ID=:ID', [':ID' => $id], 'ROLE_NAME,REMARK')) {
            return static::notice('角色不存在', 404);
        }
        return static::notice($role);
    }

    /**
     * 删除管理员角色
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRoleDelete() {
        $adminRoleForm = new AdminRoleForm();
        $result = static::delete(AdminRole::class, function ($selected) use ($adminRoleForm) {
            $adminRoleForm->beforeDelete($selected);
            // Log::adminHandle('删除审核修改会员状态信息');
        }, function ($selected) use ($adminRoleForm) {
            $adminRoleForm->delete($selected);
            // Log::adminHandle('删除审核修改会员状态信息');
        }, true);
        // 更新缓存
        Cache::updateAdminRole();
        return $result;
    }

    /**
     * 权限设置
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRolePermission(){
        $id = Yii::$app->request->get('id');
        $oneAdminRole = AdminRole::findOne($id);

        if (Yii::$app->request->isPost) {
            return parent::edit(AdminRoleForm::class, '设置管理员角色权限成功', 'permission', ['permission'], null, function ($form, $result) {
                Cache::updateAdminRole();
            });
        }
        // 获取全部权限(通过菜单)
        $menuArray = require Yii::getAlias('@backendApi/config/menu.php');
        $permissionArray = [];
        foreach($menuArray as $key=>$value){
            $tempPermission = [];
            if(isset($value['controller']) && $value['controller']){
                $tempPermission['mainPermission'] = [
                    'name' => $value['name'],
                    'path' => $value['controller'].'/*',
                ];
                if($value['action']){
                    $isChecked = false;
                    // 暂时先从文件中取内容
                    $fPath = \Yii::getAlias('@common/runtime/permission/').$oneAdminRole['ID'];
                    if(!file_exists($fPath)){
                        $fPermission = '';
                    } else {
                        $fPermission = file_get_contents($fPath);
                    }
                    if($fPermission){
                        if(in_array($value['controller'].'/'.$value['action'], Json::decode($fPermission))){
                            $isChecked = true;
                        }
                    }
                    $tempPermission['childPermission'][] = [
                        'name' => $value['name'],
                        'path' => $value['controller'].'/'.$value['action'],
                        'isChecked' => $isChecked,
                    ];
                }
                if($value['child']){
                    foreach($value['child'] as $child){
                        if($child['action']){
                            $isChildChecked = false;
                            // 暂时先从文件中取内容
                            $cPath = \Yii::getAlias('@common/runtime/permission/').$oneAdminRole['ID'];
                            if(!file_exists($cPath)){
                                $cPermission = '';
                            } else {
                                $cPermission = file_get_contents($cPath);
                            }
                            if($cPermission){
                                //是否已选状态
                                if(in_array($child['controller'].'/'.$child['action'], Json::decode($cPermission))){
                                    $isChildChecked = true;
                                }
                            }
                            $tempPermission['childPermission'][] = [
                                'name' => $child['name'],
                                'path' => $child['controller'].'/'.$child['action'],
                                'isChecked' => $isChildChecked,
                            ];
                        }
                    }
                }
            }
            $tempPermission['id'] = $key;
            $permissionArray[] = $tempPermission;
        }

        return static::notice($permissionArray);
    }

    /**
     * 列表字段权限设置
     */
    public function actionRoleColumn(){
        $id = Yii::$app->request->get('id');

        if (Yii::$app->request->isPost) {
            return parent::edit(AdminRoleForm::class, '设置管理员角色列表字段权限成功', 'columnPermission', ['columnPermission'], null, function ($form, $result) {
                Cache::updateAdminRole();
            });
        }

        $oneAdminRole = AdminRole::findOneAsArray('ID=:ID', [':ID'=>$id]);
        $columnPermission = isset($oneAdminRole['COLUMN_PERMISSION']) && is_resource($oneAdminRole['COLUMN_PERMISSION']) ? stream_get_contents($oneAdminRole['COLUMN_PERMISSION']) : null;
        $oneRoleColumns = $columnPermission ? Json::decode(base64_decode($columnPermission)) : null;
        // 获取全部可供选择的列表字段
        $allRoleColumns = AdminRole::getAllRoleColumn();
        foreach($allRoleColumns as $key => $roleColumns){
            if($oneRoleColumns && isset($oneRoleColumns[$roleColumns['listClass']])){
                foreach($roleColumns['columns'] as $k => $roleColumn){
                    $allRoleColumns[$key]['columns'][$k]['isChecked'] = in_array($roleColumn['index'], $oneRoleColumns[$roleColumns['listClass']]);
                }
            } else {
                foreach($roleColumns['columns'] as $k => $roleColumn){
                    $allRoleColumns[$key]['columns'][$k]['isChecked'] = false;
                }
            }
        }

        return $allRoleColumns;
    }


}