<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-25 17:23
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace app\system\controller;

use app\BaseViewController;
use app\model\api\OrderInfo;
use app\model\system\Order;
use app\model\system\Product;
use app\model\system\SystemAdmin;
use app\model\system\SystemMenu;
use app\Request;
use library\exceptions\GeneralException;
use library\lib\hupun;
use library\lib\weixina;
use library\services\UtilService;
use library\utils\Captcha;
use library\utils\Qiniu;
use think\facade\Db;

class Login extends BaseViewController
{

    /**
     * 用户登录端
     * @param Request $request
     */
    public function index(Request $request)
    {
        [$account, $pwd, $imgcode] =  UtilService::getMore([
            ['account','','empty','请输入登录账户'],
            ['pwd','','empty','请输入登录密码'],
            ['imgcode','','empty','验证码不能为空'],
        ],$request,true);
        if (!(new Captcha)->check($imgcode)) {
            return app('json')->fail('验证码错误，请重新输入');
        }
        //获取登录
        $adminInfo = SystemAdmin::login($account,$pwd);
        if(empty($adminInfo)) {
            return app('json')->fail(SystemAdmin::getErrorInfo('用户名错误，请重新输入'));
        }
        //生成令牌
        $token = SystemAdmin::createToken($adminInfo, 'admin');
        if(empty($token)) {
            return app('json')->fail(SystemAdmin::getErrorInfo());
        }
        //获取管理菜单
        $menuMenu = new SystemMenu();
        $menus = $menuMenu->getRoute($adminInfo->role_id);
        return app('json')->success([
            'token' => $token['token'],
            'expires_time' => $token['params']['exp'],
            'menus' => $menus,
            'user_info' => [
                'id'        => $adminInfo->getData('id'),
                'username'  => $adminInfo->getData('username'),
                'name'      => $adminInfo->getData('name'),
                'avatar'    => $adminInfo->getData('avatar')
            ],
        ]);
    }

    /**
     * 用户发生退出
     */
    public function logut(Request $request){
        echo 'a';
        var_dump($request->post());exit;
    }


    /**
     * 验证码
     * @return \app\adminapi\controller\Login|\think\Response
     */
    public function captcha()
    {
        return (new Captcha())->create();
    }

    /**
     * 绑定数据
     */
    public function system_bind(Request $request){
        $token = $request->get('token');
        if(empty($token)) {
            $this->assign('error','token 错误,请重新扫码绑定!');
            return $this->display('binderror');
        }
        $token = str_replace(" ","+",$token);
        $str = crypto_decrypt(base64_decode($token),'md5_token');
        if(empty($str)) {
            $this->assign('error','token 错误,请重新扫码绑定!');
            return $this->display('binderror');
        }
        $strAr = explode('|',$str);
        if(count($strAr) != 2) {
            $this->assign('error','数据出错！');
            return $this->display('binderror');
        }
        $w = $this->weixinLogin();
        if(!$w[1]) {
            return $w[0];
        }
        $this->assign('user',$w[0]);
        $this->assign('token',$token);
        return $this->display('bindqrcode');
    }


    public function system_bind_data(Request $request){
        $token = $request->post('token');
        if(empty($token)) {
            return app('json')->fail('token 错误,请重新扫码绑定!');
        }
        $token = str_replace(" ","+",$token);
        $str = crypto_decrypt(base64_decode($token),'md5_token');
        if(empty($str)) {
            return app('json')->fail('token 错误,请重新扫码绑定!');
        }
        $w = $this->weixinLogin();
        if(!$w[1]) {
            return $w[0];
        }
        $userInfo = $w[0];
        $count = Db::name("weixin_push_user")
                    ->where('sassid',0)
                    ->where('openid',$userInfo['openid'])
                    ->count();
        if($count <= 0) {
            $d['type'] = 'system';
            $d['sassid'] = 0;
            $d['uid'] = 0;
            $d['time'] = time();
            $d['avatar'] = $userInfo['headimgurl'];
            $d['nickname'] = $userInfo['nickname'];
            $d['openid'] = $userInfo['openid'];
            Db::name("weixin_push_user")->insert($d);
        }

        return app('json')->success('操作成功');
    }


    public function bindsuccess(){
       return $this->display();
    }

    /**
     * 微信登录板顶
     */
    private function weixinLogin() {
        $weixinUser = cookie('weix_userinfo');
        if(!empty($weixinUser)) return [unserialize($weixinUser),true];
        $domain = \request()->url();
        cookie('w_url',$domain);
        $weixinA = new weixina;
        return [$weixinA->oauth('login'),false];
    }

}