<?php

namespace crmeb\subscribes;

use app\models\user\User;
use app\models\user\WechatUser;
use think\facade\Cookie;
use app\admin\model\system\SystemAttachment;
use app\admin\model\user\UserBill;
use app\models\user\UserLevel;
use app\models\user\UserNotice;
use crmeb\services\async\task\AsyncClass;
use think\facade\Log;
use think\facade\Config;

/**
 * 用户事件
 * Class UserSubscribe
 * @package crmeb\subscribes
 */
class UserSubscribe
{

    public function handle()
    {

    }

    /**
     * 管理员后台给用户添加金额 AdminAddMoney
     * @param $event
     */
    public function onAdminAddMoney($event)
    {
        list($user, $money) = $event;

        Log::warning('EVENT admin add money ' . $money . ' to ' . $user['uid']);
    }

    /**
     * 微信授权成功后 WechatOauthAfter
     * @param $event
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function onWechatOauthAfter($event)
    {
        list($openid, $wechatInfo, $spreadId, $login_type) = $event;

        if (!User::be(['uid' => $spreadId])) $spreadId = 0;

        $wechatInfo['nickname'] = filter_emoji($wechatInfo['nickname']);
        Cookie::set('is_login', 1);
        if (isset($wechatInfo['unionid']) && $wechatInfo['unionid'] != '' && ($uid = WechatUser::where('unionid', $wechatInfo['unionid'])->where('user_type', '<>', 'h5')->value('uid'))) {
            WechatUser::edit($wechatInfo, $uid, 'uid');
            if (!User::be(['uid' => $uid])) {
                $wechatInfo = WechatUser::where('uid', $uid)->find();
                User::setWechatUser($wechatInfo, $spreadId);
            } else {
                if ($login_type) $wechatInfo['login_type'] = $login_type;
                User::updateWechatUser($wechatInfo, $uid);
            }
        } else if ($uid = WechatUser::where(['openid' => $wechatInfo['openid']])->where('user_type', '<>', 'h5')->value('uid')) {
            WechatUser::edit($wechatInfo, $uid, 'uid');
            if ($login_type) $wechatInfo['login_type'] = $login_type;
            User::updateWechatUser($wechatInfo, $uid);
        } else {
            if (isset($wechatInfo['subscribe_scene'])) unset($wechatInfo['subscribe_scene']);
            if (isset($wechatInfo['qr_scene'])) unset($wechatInfo['qr_scene']);
            if (isset($wechatInfo['qr_scene_str'])) unset($wechatInfo['qr_scene_str']);
//            $isLogin = request()->isLogin();
//            $bind = false;
//            if($isLogin){
//                $loginUid = request()->user();
//                $isUser = $loginUid ? request()->tokenData()->type === 'user' : false;
//                $bind = $loginUid && $isUser && !$loginUid->openid && !User::be(['openid' => $wechatInfo['openid']]);
//                //微信用户绑定 h5用户
//                if ($bind) {
//                    $wechatInfo['uid'] = $loginUid->uid;
//                };
//            }
            $wechatInfo = WechatUser::create($wechatInfo);
//            if ($isLogin && $bind)
//                User::where('uid', $wechatInfo['uid'])
//                    ->limit(1)->update(['openid' => $wechatInfo['openid']]);
//            else
            User::setWechatUser($wechatInfo, $spreadId);
        }
        $uid = WechatUser::openidToUid($openid, 'openid');
        // 设置推广关系
        User::setSpread($spreadId, $uid);

        User::where('uid', $uid)
            ->limit(1)->update(['last_time' => time(), 'last_ip' => app('request')->ip()]);
    }

    /**
     * 用户登录成功 UserLogin
     * @param $event
     */
    public function onUserLogin($event)
    {
        list($userInfo) = $event;
        $request = app('request');
        User::edit(['last_time' => time(), 'last_ip' => $request->ip()], $userInfo->uid, 'uid');

        // 对现存用户处理，用于过渡
        AsyncClass::push('tw\async\tasks\UserTaskClass', [], 'generate_user_poster', [$userInfo->uid]);
        Log::debug('EVENT user ' . $userInfo->uid . ' login.');
    }

    /**
     * 检查是否能成为会员 UserLevelAfter
     * @param $event
     */
    public function onUserLevelAfter($event)
    {
        list($userUid) = $event;
        try {
            if(UserLevel::setLevelComplete($userUid)) {
                event('UserLevelUp', $event);
            }
        } catch (\Exception $e) {

        }
    }

    /**
     * 用户成为推广员 UserBecomedPromoter
     */
    public function onUserBecomedPromoter($event)
    {
        list($user) = $event;
        AsyncClass::push('tw\async\tasks\UserTaskClass', [], 'generate_user_poster', [$user['uid']]);
        Log::debug('EVENT user' . $user['uid'] . ' has becomed promoter');
    }
    
    /**
     * 用户升级成功 UserLevelUp
     */
    public function onUserLevelUp($event)
    {
        list($userUid) = $event;
        $userinfo = User::get($userUid);

        Log::debug("EVENT user " . $userUid . ' update to level ' . $userinfo['level']);
    }

    /**
     * 新用戶注冊 UserRegistered
     */
    public function onUserRegistered($event)
    {
        list('user' => $user) = $event;

        $res = UserBill::income('新用户送钱活动', $user['uid'], 'now_money', 'brokerage', $user['now_money'], $user['uid'], $user['now_money'], '新用户送' . $user['now_money'] . '元');
        if (!$res) {
            Log::error('user ' . $user['uid'] . 'registered send money ' . $user['now_money'] . ' failed.');
        }
        Log::debug('EVENT new user registered:' . $user['uid']);
    }

    /**
     * 首次下訂單 UserFirstOrder
     */
    public function onUserFirstOrder($event)
    {
        list('order' => $order) = $event;

        Log::debug('EVENT user ' . $order['uid'] . ' first order:' . $order['id']);
    }

    /**
     * 用戶提現 UserRequestWithdrawal
     */
    public function onUserRequestWithdrawal($event)
    {
        list('user' => $user, 'info' => $info) = $event;

        Log::debug('EVENT user ' . $user['uid'] . ' withdraw ' . mapped_implode(',', $info));
    }

    /**
     * 後臺批準提現 UserExtractSucc
     */
    public function onUserExtractSucc($event)
    {
        list($extract) = $event;
        $icon = Config::get('app.header_cs_2', '');
        list($extract_type, $account) = get_extract_name($extract);
        UserNotice::sendNoticeTo($extract['uid'], '您的提现申请已处理',
                '您申请提现 ' . $extract['extract_price']
                . ' 元到' . $extract_type . '帐号' . $account
                . '已转账，请耐心等待您的收款账户系统确认后核对金额。衷心感谢您对美天旺的信任和支持。如有问题，请联系客服。', $icon);
    }
    /**
     * 後臺拒絕提現 UserExtractFail
     */
    public function onUserExtractFail($event)
    {
        list($extract, $fail_msg) = $event;
        $icon = Config::get('app.header_cs_2', '');
        list($extract_type, $account) = get_extract_name($extract);
        UserNotice::sendNoticeTo($extract['uid'], '您的提现申请已处理',
        '您申请提现 ' . $extract['extract_price']
        . ' 元到' . $extract_type . '帐号' . $account
        . '未能成功执行，原因:' . $fail_msg['message'] . '。请联系客服处理。', $icon);
    }

    /**
     * 首次挖礦得到弊 UserFirstDig
     */
    public function onUserFirstDig($event)
    {

    }

    /**
     * 用户提币 UserWithdrawalCoin
     */
    public function onUserWithdrawalCoin($event)
    {

    }

    /**
     * 用户参加活动 UserActivity
     */
    public function onUserActivity($event)
    {
        
    }
}