<?php

namespace app\mobile\controller;

use app\common\model\UserModel;
use app\mobile\MobileBaseController;

class Login extends MobileBaseController
{
    public function login()
    {
        return redirect('https://www.jucai.gov.cn/api/auth/wechat_auth?url=' . urlencode(url('/mobile/login/wechatBack')));
    }

    /**
     * 微信回调
     */
    public function wechatBack()
    {
        $param   = input('param.');
        $open_id = $param['openid'];

        //登录
        $user = UserModel::where(['openid' => $open_id])->find();
        if (empty($user)) {
            $user = UserModel::create([
                'nickname'  => $param['nickname'],
                'avatar'    => $param['headimgurl'],
                'openid'    => $open_id,
                'unionid'   => $param['unionid'],
                'logintime' => time(),
                'loginip'   => request()->ip(),
            ]);
        } else {
            $user->logintime = time();
            $user->loginip   = request()->ip();
            $user->save();
        }

        session('mobile.user.id', $user['id']);

        $back_url = '/';
        if (session('?back_url')) {
            $back_url = session('back_url');
            session('back_url', null);
        }

        return redirect($back_url);
    }

    public function login1()
    {
        session('mobile.user.id', 1);
        $back_url = '/';
        if (session('?back_url')) {
            $back_url = session('back_url');
            session('back_url', null);
        }
        return redirect($back_url);
    }

    public function logout()
    {
        session('mobile.user.id', null);
        return '退出';
    }
}
