<?php

namespace app\adminapi\controller;

use app\adminapi\model\AuthGroup;
use app\adminapi\model\AuthGroupAccess;
use app\common\controller\AdminApi;
use app\adminapi\model\Admin;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Validate;

/**
 * 管理员管理
 */
class AdminManager extends AdminApi
{
    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenApiGroupIds = [];
    protected $childrenAdminIds = [];

    protected $groupdata = [];

    protected $addressCityList = [];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Admin;

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
//        var_dump($this->childrenGroupIds);



        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $this->groupdata = $groupdata;
//        $this->addressCityList = $this->model->getAddressCityList();
    }



    /**
     * 查看列表
     *
     * @ApiMethod (GET)
     * @ApiParams (name="limit", type="int", required=true, description="每页条数")
     * @ApiParams (name="page", type="int", required=true, description="页数")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="mobile", type="int", required=true, description="手机号码")
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        $where = [];
        $limit =  $this->request->get("limit/d",10);
        $username =  $this->request->get("username/s","");
        if($username){
            $where['username'] = ['like',"%{$username}%"];
        }

        $nickname =  $this->request->get("nickname/s","");
        if($nickname){
            $where['nickname'] = ['like',"%{$nickname}%"];
        }

        $mobile =  $this->request->get("mobile/s","");
        if($mobile){
            $where['mobile'] = ['like',"%{$mobile}%"];
        }

//        if(!$where)$where = [[]];



            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
                ->column('id,name');
            $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                ->field('uid,group_id')
                ->select();

            $adminGroupName = [];
            foreach ($authGroupList as $k => $v) {
                if (isset($groupName[$v['group_id']])) {
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
                }
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }

            $list = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->field(['password', 'salt', 'token'], true)
                ->order("id desc")
                ->paginate($limit);

            foreach ($list as $k => &$v) {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['groups'] = implode(',', array_keys($groups));
                $v['groups_text'] = implode(',', array_values($groups));

            }
            unset($v);
           $items = $list->items();
        foreach ($items as $k => &$vv) {
            $vv['groups_ids'] =  implode(',',array_column($vv['groups'], 'id'));
        }


        $result = array("total" => $list->total(), "data" => $items);

        $this->success("查询成功！",$result);

    }



    /**
     * 添加管理员(GET为查询可添加的权限组信息)
     *
     * @ApiMethod (POST|GET)
     * @ApiParams (name="email", type="int", required=true, description="电子邮箱")
     * @ApiParams (name="password", type="int", required=true, description="登录密码")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="mobile", type="int", required=true, description="手机号码")
     * @ApiParams (name="group", type="string", required=true, description="api权限组ids，多值逗号隔开")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = [];

            $params["email"] = $this->request->post("email/s");
            $params["password"] = $this->request->post("password/s");
            $params["username"] = $this->request->post("username/s");
            $params["nickname"] = $this->request->post("nickname/s");
            $params["mobile"] = $this->request->post("mobile/s");
            $group = $this->request->post("group/s","");
            $group = explode(',', $group);

            if ($params) {
                Db::startTrans();
                try {
                    if (!Validate::is($params['password'], '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
                    $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $result = $this->model->validate('Admin.add')->save($params);
                    if ($result === false) {
                        exception($this->model->getError());
                    }

//                    $apigroup = $this->request->post("apigroup/a");

                    //过滤不允许的组别,避免越权
                    $group = array_intersect($this->childrenGroupIds, $group);
                    if (!$group) {
                        exception(__('The parent group exceeds permission limit'));
                    }


//                    $apigroup = array_intersect($this->childrenApiGroupIds, $apigroup);
//                    if (!$apigroup) {
//                        exception(__('The parent group exceeds permission limit'));
//                    }



                    $dataset = [];
                    foreach ($group as $value) {
                        $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                    }
                    (new AuthGroupAccess)->saveAll($dataset);


//                    $dataset = [];
//                    foreach ($apigroup as $value) {
//                        $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
//                    }
//                    (new \app\admin\model\api\AuthGroupAccess())->saveAll($dataset);

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $this->success("获取权限组信息成功",[
                'group'=>$this->groupdata
            ]);
        }
    }





    /**
     * 编辑管理员
     *
     * @ApiMethod (POST)
     * @ApiRoute    (/adminapi/admin_manager/edit/ids/{ids})
     * @ApiParams (name="ids", type="string", required=true, description="需要编辑的ids")
     * @ApiParams (name="email", type="int", required=true, description="电子邮箱")
     * @ApiParams (name="password", type="int", required=true, description="登录密码")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="mobile", type="int", required=true, description="手机号码")
     * @ApiParams (name="group", type="string", required=true, description="api权限组ids，多值逗号隔开1")
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row->id, $this->childrenAdminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {

            $params = [];

            $params["email"] = $this->request->post("email/s");
            $params["password"] = $this->request->post("password/s");
            $params["username"] = $this->request->post("username/s");
            $params["nickname"] = $this->request->post("nickname/s");
            $params["mobile"] = $this->request->post("mobile/s");
            $group = $this->request->post("group/s","");
            $group = explode(',', $group);
            if ($params) {
                Db::startTrans();
                try {
                    if ($params['password']) {
                        if (!Validate::is($params['password'], '\S{6,30}')) {
                            exception(__("Please input correct password"));
                        }
                        $params['salt'] = Random::alnum();
                        $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
                    } else {
                        unset($params['password'], $params['salt']);
                    }
                    //这里需要针对username和email做唯一验证
                    $adminValidate = \think\Loader::validate('Admin');
                    $adminValidate->rule([
                        'username' => 'require|regex:\w{3,30}|unique:admin,username,' . $row->id,
                        'email'    => 'require|email|unique:admin,email,' . $row->id,
                        'mobile'   => 'regex:1[3-9]\d{9}|unique:admin,mobile,' . $row->id,
                        'password' => 'regex:\S{32}',
                    ]);
                    $result = $row->validate('Admin.edit')->save($params);
                    if ($result === false) {
                        exception($row->getError());
                    }

                    // 先移除所有权限
//                    model('AuthGroupAccess')->where('uid', $row->id)->delete();
                    \app\adminapi\model\AuthGroupAccess::where('uid', $row->id)->delete();

//                    $group = $this->request->post("group/a");
//                    $apigroup = $this->request->post("apigroup/a");

                    // 过滤不允许的组别,避免越权
                    $group = array_intersect($this->childrenGroupIds, $group);
                    if (!$group) {
                        exception(__('The parent group exceeds permission limit'));
                    }

//                    $apigroup = array_intersect($this->childrenApiGroupIds, $apigroup);
//                    if (!$apigroup) {
//                        exception(__('The parent group exceeds permission limit'));
//                    }


                    $dataset = [];
                    foreach ($group as $value) {
                        $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                    }
                    (new AuthGroupAccess)->saveAll($dataset);


//                    $dataset = [];
//                    foreach ($apigroup as $value) {
//                        $dataset[] = ['uid' => $row->id, 'group_id' => $value];
//                    }
//                    (new \app\admin\model\api\AuthGroupAccess())->saveAll($dataset);

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

    }


    /**
     * 查看详情
     *
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="string", required=true, description="管理员ID")
     */
    public function detail()
    {
        $admin_id = $this->auth->id;
        $id = $this->request->get('id/d');

        try{
            $row = $this->model->detail($id,$show_field=[],["token","salt","password","logintime","loginip"]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }


        $this->success('查询成功', [
            'row' => $row,
            'groupids' => $groupids,
        ]);
    }




    /**
     * 删除
     * @ApiRoute    (/adminapi/admin_manager/del/ids/{ids})
     * @ApiParams (name="ids", type="string", required=true, description="需要删除的ids")
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $ids = array_intersect($this->childrenAdminIds, array_filter(explode(',', $ids)));
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function ($query) use ($childrenGroupIds) {
                $query->name('api_auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_values(array_diff($deleteIds, [$this->auth->id]));
                if ($deleteIds) {
                    Db::startTrans();
                    try {
                        $this->model->destroy($deleteIds);
                        AuthGroupAccess::where('uid', 'in', $deleteIds)->delete();
                        \app\admin\model\AuthGroupAccess::where('uid', 'in', $deleteIds)->delete();
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    $this->success();
                }
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('You have no permission'));
    }



}