<?php


namespace App\Modules\User\Services;

use App\Consts\SysConsts;
use App\Modules\BaseService;
use App\Modules\User\Models\QappUser;
use App\Modules\User\Models\User;
use DB;
use Exception;
use Tymon\JWTAuth\Facades\JWTAuth;
use Redis;

/**
 * 
 * @method static \App\Modules\User\Models\QappUser setGolableUserStatic(int $uid) 设置快应用用户信息（全局）
 * @method static void getGolableUserStatic() 获取快应用用户信息（全局）
 * @method static \App\Modules\User\Models\QappUser loginStatic(array $data) 快应用用户登录
 * @method static bool bindPhoneStatic(int $uid, string $phone) 绑定手机号
 */
class QappUserService
{
    use BaseService;

    /**
     * 获取快应用用户
     */
    public function login(array $data)
    {
        $device_no = $data['device_no'];
        $qapp_user = $this->getQAppUserByDeviceNo($device_no);
        if (!$qapp_user) {
            $qapp_user = $this->createQuickAppUser($data);
        }
        $user = $qapp_user->user;
        $uid = $user->id;
        $time = strtotime("+1 month");
        $token = JWTAuth::fromUser($user);
        if ($data['send_order_id']) {
            UserService::setUserSendOrderStatic($uid, $data['send_order_id']);
        }
        return compact('token', 'time', 'uid');
    }

    public function getGolableUser()
    {
        $qapp_user = app()->make('qapp_user');
        return $qapp_user;
    }

    /**
     * 绑定手机号
     */
    public function bindPhone(int $uid, string $phone)
    {
        $is_exists = QappUser::where('phone', $phone)->exists();
        if ($is_exists) {
            return false;
        } else {
            $qapp_user = QappUser::where('uid', $uid)->first();
            if ($qapp_user->phone) {
                return false;
            } else {
                try {
                    DB::beginTransaction();
                    $qapp_user->phone = $phone;
                    $qapp_user->save();
                    $reward = 100;
                    User::where('id', $uid)->update(
                        [
                            'balance' => DB::raw('balance+' . $reward),
                            'reward_balance' => DB::raw('reward_balance+' . $reward)
                        ]
                    );
                    DB::commit();
                } catch (Exception $e) {
                    myLog('bindPhone')->error($e->getMessage());
                }
                return true;
            }
        }
    }

    public function setGolableUser(int $uid)
    {
        $user_info = $this->getQAppUserByUid($uid);
        $qapp_user = app()->make('qapp_user');
        $qapp_user->id = $user_info->id;
        $qapp_user->uid = $user_info->uid;
        $qapp_user->send_order_id = $user_info->send_order_id;
        $qapp_user->device_no = $user_info->device_no;
        $qapp_user->device_info = $user_info->device_info;
        $qapp_user->phone = $user_info->phone;
        $qapp_user->user = $user_info->user;
    }

    /**
     * 根据设备号获取快应用用户信息
     */
    public function getQAppUserByDeviceNo(string $device_no)
    {
        $qapp_user = QappUser::where('device_no', $device_no)->first();
        if ($qapp_user) {
            $user = User::find($qapp_user->uid);
            $qapp_user->user = $user;
        }
        return $qapp_user;
    }

    /**
     * 根据uid获取快应用用户信息
     */
    public function getQAppUserByUid(int $uid)
    {
        $qapp_user = QappUser::where('uid', $uid)->first();
        if ($qapp_user) {
            $user = User::find($uid);
            $qapp_user->user = $user;
            $qapp_user->send_order_id = UserService::getUserSendOrderStatic($uid);
        }
        return $qapp_user;
    }


    /**
     * 创建快应用用户信息
     */
    public function createQuickAppUser(array $data)
    {
        try {
            DB::beginTransaction();
            $user = $this->createUser($data);
            $uid = $user->id;
            $device_no = $data['device_no'];
            $data = compact('device_info');
            $unique_key = compact('device_no', 'uid');
            $qapp_user = QappUser::firstOrCreate($unique_key, $data);
            $qapp_user->user = $user;
            DB::commit();
            return $qapp_user;
        } catch (Exception $e) {
            myLog('create_user')->error($e->getMessage());
        }
    }

    /**
     * 创建用户
     */
    private function createUser(array $data)
    {
        $openid = $data['device_no'];
        $unionid = $data['device_no'];
        $register_ip = _getIp();
        $distribution_channel_id = env('QUICKAPP_SITE');
        $send_order_id = $data['send_order_id'];
        $unique_key = compact('unionid', 'distribution_channel_id');
        $data = compact('openid', 'register_ip', 'send_order_id');
        return User::firstOrCreate($unique_key, $data);
    }
}
