<?php
/**
 *
 * Created by PhpStorm.
 * User: fenggaoyuan
 * Email: 253869997@qq.com
 * Date: 2018/7/26
 * Time: 11:35
 */

namespace app\api\logic\app;

use app\api\model\User;
use think\Config;
use app\api\model\UserOauth;
use think\Db;
use app\common\tools\wechatUtil;

class UserLogic
{
    /**
     * @author: Airon
     * @time:   2018年5月
     * description
     * @param $mobile
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function checkUser($mobile)
    {
        $bool = User::build()->where(['mobile' => $mobile, 'is_banned' => 0])->find();
        return empty($bool) ? false : true;
    }

    /**
     * @author: Airon
     * @time:   2018年5月
     * description 公众号登录
     * @param $data
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function publicLogin($data)
    {
        $config = config('wechat');
        $result = wechatUtil::getAccessToken($config['PublicAppID'], $config['PublicAppSecret'], $data['jscode']);

        $result = json_decode($result, true);

        if (!empty($result['errcode'])) {
            ResponseDirect( "jsCode验证失败",403);
        }

        $user_info = wechatUtil::getUserInfo($result['access_token'], $result['openid']);

        if(empty($user_info)){
            ResponseDirect( "login Error",403);
        }

        $user_info = json_decode($user_info, true);
        $unionid = empty($result['unionid'])?"":$result['unionid'];
        $result = [];
        $result['unionid'] = $unionid;
        $result['oauth_type'] = "wechat_public";
        $result['oauth_id'] = $user_info['openid'];

        $user = UserOauth::build()
            ->where(['oauth_id' => $result['oauth_id']])
            ->find();


        if (!empty($user)) {
            return ['uuid'=>$user['uuid']];
        }

        $result['uuid'] = uuid();
        $result['create_time'] = timeToDate();
        $bool_1 = UserOauth::build()->insert($result);

        if (empty($bool_1)) {
            return false;
        }

        return ['uuid' => $result['uuid']];
    }

}