<?php
namespace app\admin\behavior;
use app\common\model\UserRelation;
use app\common\model\User as UserModel;

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

        if (!UserModel::where(['id' => $spreadId])->find()) $spreadId = 0;

        $wechatInfo['nickname'] = filter_emoji($wechatInfo['nickname']);

        if (isset($wechatInfo['unionid']) && $wechatInfo['unionid'] != '' && ($uid = UserRelation::where('unionid', $wechatInfo['unionid'])->where('login_type', '<>', 0)->value('user_id'))) {
            UserRelation::where('user_id',$uid)->update($wechatInfo);
            if (!UserRelation::where(['user_id' => $uid])->find()) {
                $wechatInfo = UserRelation::where('user_id', $uid)->find();
                UserModel::setWechatUser($wechatInfo, $spreadId);
            } else {
                if ($login_type) $wechatInfo['login_type'] = $login_type;
                UserModel::updateWechatUser($wechatInfo, $uid);
            }
        } else if ($uid = UserRelation::where(['openid' => $wechatInfo['openid']])->where('login_type', '<>', 0)->value('user_id')) {
            UserRelation::where('user_id',$uid)->update($wechatInfo);
            if ($login_type) $wechatInfo['login_type'] = $login_type;
            UserModel::updateWechatUser($wechatInfo, $uid);
        } else {
            $wechatInfo['login_type'] = $login_type;
            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']);
            UserModel::setWechatUser($wechatInfo, $spreadId);
        }
        $uid = UserRelation::openidToUid($openid, 'openid');
        // 设置推广关系
        UserModel::setSpread($spreadId, $uid);
        return true;
    }
}