<?php

namespace app\adminapi\controller;


use app\adminapi\model\Admin as AdminModel;
use app\adminapi\model\AuthRule;
use app\common\controller\AdminApi;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use think\Config;
use think\Cookie;
use think\Hook;


/**
 * 基础后台接口
 */
class Admin extends AdminApi
{

    protected $model = null;


    protected $noNeedLogin = ['login',"init"];
    protected $noNeedRight = ["logout","menu","check_auth","have_auth"];


    /**
     * 初始化操作
     * @access protected
     */
    public function _initialize()
    {
        $this->model = new AdminModel;
        parent::_initialize();

        $auth = $this->auth;
        //监听注册登录退出的事件
        Hook::add('admin_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('adminid', $user->id, $expire);
            Cookie::set('admintoken', $auth->getToken(), $expire);
        });
        Hook::add('admin_register_successed', function ($user) use ($auth) {
            Cookie::set('adminid', $user->id);
            Cookie::set('admintoken', $auth->getToken());
        });
        Hook::add('admin_delete_successed', function ($user) use ($auth) {
            Cookie::delete('adminid');
            Cookie::delete('admintoken');
        });
        Hook::add('admin_logout_successed', function ($user) use ($auth) {
            Cookie::delete('adminid');
            Cookie::delete('admintoken');
        });


    }



    /**
     * 管理员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }



    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
//        //设置contenttype不为表单格式防止触发宝塔防火墙
//        header('Content-Type:application/json; charset=utf-8');
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
//        $password = $this->request->post('datatime');

        $this->auth->logout();
        $this->success(__('Logout successful'));
    }


    /**
     * 管理员菜单
     *
     * @ApiMethod (GET)
     * @ApiParams (name="is_tree", type="string", required=true, description="是否是树形结构")
     */
    public function menu()
    {
        $admin_id = $this->auth->id;
        $is_tree = $this->request->get('is_tree');

        $menulist = (new AuthRule)->getMenulist($admin_id,["ismenu"=>1],$is_tree);

        $this->success('查询成功', $menulist);
    }


    /**
     * 权限校验（接口校验版-用于前端自行显示隐藏）
     * 返回null为无权限
     * @ApiMethod (GET)
     * @ApiParams (name="auth_name", type="string", required=true, description="请求路径或权限标识")
     */
    public function check_auth()
    {
        $admin_id = $this->auth->id;
        $auth_name = $this->request->get('auth_name',"") ?: "***";
        $check = (new AuthRule)->authCheck($admin_id,$auth_name);

        $this->success('权限校验结果返回', $check);
    }




    /**
     * 权限校验（直接返回拥有的所有权限，前端自行比对判断）
     *
     * @ApiMethod (GET)
     */
    public function have_auth()
    {
        $admin_id = $this->auth->id;
        $check = (new AuthRule)->getAllRules($admin_id);

        $this->success('权限列表返回', $check);
    }



    /**
     * 分离后台加载初始化
     *
     * @ApiParams (name="lng", type="string", required=true, description="经度")
     * @ApiParams (name="lat", type="string", required=true, description="纬度")
     */
    public function init()
    {

            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/adminapi/admin/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
//                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
    }



    /**
     * 上传文件
     * @ApiMethod (POST)
     * @ApiParams (name="file", type="File", required=true, description="文件流")
     * @ApiParams (name="category", type="string", required=true, description="分类标识：category1=非机密类1,category2=非机密类2,cert=证件机密类,code=二维码类,user=用户普通上传")
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $category = $this->request->post("category",'user');
//        var_dump($category);die;
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");

            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {

                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);

                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {

                $upload = new Upload($file,$category);
                $attachment = $upload->upload();

//                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage().$e->getFile().$e->getLine());
            } catch (\Exception $e) {
                $this->error($e->getMessage().$e->getFile().$e->getLine());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }


}