<?php
defined('IN_WEB') or die('Include Error!');
/**
 * 玩家相关操作,分担member类
 */
class ModelUser
{
    protected $payOrderLimit = 10; //订单历史记录上限
    protected $bindRwd = 50000;//绑定奖励

    /**
     * 删除账号
     * @param array $uidList
     * @return int
     * Created by: Owen
     * Created on: 2020/12/30 15:04
     */
    public function delAccount($uidList = array()){
        if( !is_array($uidList) ){
            return -1;
        }
        foreach ($uidList as $uid) {
            $tb   = otable::taccount();
            $fb   = oo::commonOprDb('account')->getOne("SELECT * FROM {$tb} WHERE uid='{$uid}' LIMIT 1",MYSQLI_ASSOC);
            $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
            if(!empty($fb)){//FB
                $siteUid = $fb['siteuid'];
                oo::commonOprRedis('user')->delete(okeys::account($siteUid));
                $tb = otable::taccount();
                oo::commonOprDb('account')->query("DELETE FROM {$tb} WHERE siteuid='{$siteUid}' LIMIT 1");
            }
            if($userInfo['login_plat'] == 1){
                $tb  = otable::mobile();
            }else if($userInfo['login_plat'] == 2){
                $tb  = otable::openudid();
            }
            $bool = oo::commonOprDb('userinfo')->query("DELETE FROM {$tb} WHERE uid = {$uid}");
            $bool && oo::commonOprDb('userinfo')->query("DELETE FROM ".otable::DeviceId()." WHERE uid = {$uid}");
            if($bool){
                oo::commonOprModel('member')->getUserInfo($uid, NULL, TRUE, ['sstatus' => 2]);
                $tb      = otable::DeleteUserLog();
                $sid     = $userInfo['login_plat'];
                $siteUid = $userInfo['siteuid'];
                $mac     = $userInfo['mac'];
                $fbToken = $userInfo['token'];
                $time    = time();
                oo::commonOprDb('userinfo')->query("INSERT INTO {$tb} (uid, sid, siteUid, mac, fbToken, time) VALUES('{$uid}','{$sid}','{$siteUid}','{$mac}','{$fbToken}',{$time})");
                oo::commonOprRedis('common')->delete([
                    okeys::richestKing($uid),
                    okeys::richestKingTo($uid),
                    okeys::EnemyID($uid),
                    okeys::EnemyList($uid),
                    okeys::LevelLock($uid),
                    okeys::AttackLock($uid),
                    okeys::UserAssets($uid),
                    okeys::levelAttackLock($uid),
                    okeys::applyFriend($uid),
                    okeys::slotLock($uid),
                    okeys::newcomerProtection($uid),
                    okeys::StealHistory($uid),
                    okeys::StealedNum($uid),
                    okeys::Adreward($uid),
                    okeys::redPointLock($uid,'Task'),
                    okeys::Symbol($uid),
                    okeys::chatLock($uid),
                    okeys::recall($uid),
                ]);
                oo::commonOprRedis('common')->hDel(okeys::spinsFirebase(),$uid);
                oo::commonOprRedis('common')->hDel(okeys::beginGuide(),$uid);
                oo::commonOprRedis('common')->hDel(okeys::AttackedNum(),$uid);
                $this->clearSteal($uid);
                $this->clearEnemy($uid);
            }
        }
        return 1;
    }

    /**
     * Notes:清除偷取相关缓存
     * User: wsc
     * Time: 2020/3/28 16:11
     * @param $uid
     */
    public function clearSteal($uid){
        oo::commonOprModel('steal')->clearBindKing($uid);//清理king绑定关系
        oo::commonOprModel('steal')->clearOtherBind($uid);//清理其他与$uid绑定的关系
    }
    public function clearEnemy($uid){
        $key1 = okeys::userLevelOrig($uid);//用户等级orig信息
        $key2 = okeys::EnemyListCache($uid);//用户随机可攻击用户缓存
        $key3 = okeys::defaultAttactList($uid);//用户默认攻击列表
        oo::commonOprRedis('Userinfo')->delete($key1);
        oo::commonOprRedis('Userinfo')->delete($key2);
        oo::commonOprRedis('Userinfo')->delete($key3);
    }

    /**
     *	记录token, 推送需要使用token
     */
    public function recordPushToken($param){
        $uid   = oo::functions()->uint($param['uid']);
        $token = oo::functions()->escape($param['token']);
        $sid   = oo::functions()->uint($param['sid']);
        $lang = oo::getDefinedLang($uid);
        $time  = time();
        $tb    = otable::xg_push();
        $ret   = oo::commonOprDb('common')->getOne("SELECT * FROM {$tb} WHERE uid={$uid} LIMIT 1",MYSQLI_ASSOC);
        $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
        $accountType = intval($userInfo['isFb']);
        if(!empty($ret)){
            $sql = "UPDATE {$tb} SET token='{$token}',sid='{$sid}',lang='{$lang}',updatetime='{$time}',accountType='{$accountType}' WHERE uid={$uid} LIMIT 1";
            $ret = oo::commonOprDb('common')->query($sql);
        }else{
            if(funs::concurrentLock($uid,'pushToken')){
                $sql = "INSERT INTO {$tb}(uid, token, sid, updatetime, lang, accountType) VALUES ({$uid},'{$token}',{$sid},{$time},'{$lang}','{$accountType}')";
                $ret = oo::commonOprDb('common')->query($sql);
                funs::delConcurrentLock($uid,'pushToken');
            }
        }
        if($ret && !IS_DEBUF){
            oo::commonOprModel('firebase')->refreshUserTopicByLang($uid);
        }
        return json_encode(array('code' => 1));
    }



    /**
     * 获取绑定奖励
     * @return int
     */
    public function getBindRwd()
    {
        return $this->bindRwd;
    }


//    /**
//     * 游客绑定FB和LINE
//     * @param $uid
//     * @param $token
//     * @param $flag 1 fb 2 line
//     * @param $mobile_request -- mac地址
//     * @return array
//     */
//    public function visitorBind($uid, $token, $flag, $mobile_request)
//    {
//        if(empty($uid) || empty($token) || !in_array($flag, [1,2])){
//            oo::logs()->debug3('-1 参数错误: uid:'.$uid.' token:'.$token.' flag:'.$flag.' mobile_request:'.$mobile_request, 'visitorBind.php');
//            return oo::res(-1);
//        }
//        $mac = $this->getMac($mobile_request);
//        if(empty($mac)) {
//            oo::logs()->debug3('-1 参数错误: uid:'.$uid.' token:'.$token.' flag:'.$flag.' mac:'.$mac, 'visitorBind.php');
//            return oo::res(-1);
//        }
//
//        //查看是否已绑定
//        $isBind = $this->isVisitorBind($uid);
//        if($isBind > 0) {
//            oo::logs()->debug3('-3 已绑定过: uid:'.$uid.' token:'.$token.' flag:'.$flag.' mac:'.$mac, 'visitorBind.php');
//            return oo::res(-3);//已绑定过
//        }
//
//        if($flag == 1) {//FB
//            $res = $this->bindFB($token, $uid, $mac);
//        }else {//line
//            $res = $this->bindLINE($token, $uid, $mac);
//        }
//
//        if($res < 0) {
//            return oo::res($res);
//        }
//        $platid  = $res;
//
//        //写入绑定对应表
//        $table = otable::visitorbind();
//        $now = time();
//        $bindSql = "INSERT INTO {$table} (uid, platid, flag, mac, updatetime) VALUES ({$uid}, '{$platid}', {$flag}, '{$mac}', {$now})";
//        $ret = oo::commonOprDb('userinfo')->query($bindSql);
//        if(!$ret){
//            oo::logs()->debug3('-6 操作失败: uid:'.$uid.' token:'.$token.' flag:'.$flag.' mac:'.$mobile_request, 'visitorBind.php');
//            return oo::res(-4);//操作失败
//        }
//
//        return oo::res(1);
//    }


    /**
     * 游客是否已绑定FB或者LINE
     * @param $uid
     * @return bool
     */
    public function isVisitorBind($uid)
    {
        $table = otable::visitorbind();
        $sql = "SELECT * FROM {$table} WHERE uid = {$uid} LIMIT 1";
        $ret = oo::commonOprDb('userinfo')->getOne($sql, 1);
        if(isset($ret['uid']) && $ret['uid'] > 0) {
            return intval($ret['flag']);
        }
        return 0;
    }

    /**
     * 绑定FB
     * @param $token
     * @param $arr_poker
     * @param $uid
     * @param $mac
     * @return int
     */
    public function bindFB($token, $uid, $mac)
    {
        oo::facebooksdk4()->setAccessToken($token);
        $userinfo = oo::facebooksdk4()->getMe();
        if(empty($userinfo) || !isset($userinfo['id']) || empty($userinfo['id'])) {
            oo::logs()->debug3('-2 获取用户信息失败: uid:'.$uid.' token:'.$token.' flag:1 mac:'.$mac, 'visitorBind.php');
            return -2;//获取用户信息失败
        }
        $platid = $userinfo['id'];//FB平台ID

        //是否是FB用户
        $fbInfo = oo::commonOprModel('member')->getAccount($platid);
        if(!is_int($fbInfo) && $fbInfo != 0) {
            oo::logs()->debug3('-3 已经是FB用户了: uid:'.$uid.' token:'.$token.' flag:1 mac:'.$mac, 'visitorBind.php');
            return -3;//已经是FB用户了
        }

        $ret = oo::commonOprModel('member')->setAccount($platid, $uid);
        if ($ret != 0) {
            oo::logs()->debug3('-4 写入FB用户表失败: uid:'.$uid.' token:'.$token.' flag:1 mac:'.$mac, 'visitorBind.php');
            return -4;//写入FB用户表失败
        }

        return $platid;
    }

//    /**
//     * 获取mac地址
//     * @param $mobile_request
//     * @return int|string
//     */
//    public function getMac($mobile_request)
//    {
//
//        /* 统计机器码 */
//        if (empty($mobile_request)) {
//            return '';
//        }
//
//        $code = base64_decode($mobile_request);
//        if (empty($code)) {
//            return '';
//        }
//
//        $arr = explode('_', $code);
//        if (count($arr) !== 2) {
//            return '';
//        }
//
//        $secret = $arr[1];
//        if ($secret !== 'superant') {
//            return '';
//        }
//
//        if (DEVICEID == 2) {//苹果
//            $mac = $arr[0];
//        } else {
//            $mac = $this->getMacId($arr[0]);
//        }
//
//        return $mac;
//    }
//
//
//    public function getMacId($macAddr) {
//        $macAddr = trim($macAddr);
//        if(strlen($macAddr) > 30){
//            return 0;
//        }
//        $match = array();
//        if (!preg_match("/^[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i", $macAddr, $match)) {
//            return 0;
//        }
//        $str = strtr($macAddr, array(':' => ''));
//        $hexadecimal = '0x'.$str;
//        $macid = base_convert($hexadecimal, 16, 10);
//        return $macid;
//    }

    //查看玩家信息
    public function showUserInfo($uid)
    {
        $data = [];
        $arr = ['uid','nick','sex','s_picture','signature','u_flag','avatarBox','avatar'];
        //玩家基本信息
        $data['vipInfo'] = oo::commonOprModel('newvip')->getVipInfo($uid);
        $memberInfo = oo::commonOprModel('member')->getUserInfo($uid,$arr,false,NULL);
        $memberInfo['avatarBox'] = empty($memberInfo['avatarBox'])?[]:json_decode($memberInfo['avatarBox']);
        $memberInfo['avatarBox'] = $memberInfo['avatarBox'] ?? [];
        $memberAssets  = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $memberAssets['coins'] = $memberAssets['money'];
        unset($memberAssets['money']);
        $data = array_merge($data, $memberInfo, $memberAssets);
      	$data['avatar'] = (in_array($data['avatar'],$data['avatarBox']))?intval($data['avatar']):0;
       	unset($data['mac']);
        unset($data['token']);
        unset($data['locale']);
        return $data;
    }


    /**
     * 刷新体力操作
     * @param $uid
     * @param $multiple
     * @return array|float|int
     * Created by: Owen
     * Created on: 2020/1/9 16:08
     */
    public function refreshSpins($uid,$multiple){
        if( empty($uid) ){
            $data = array('code' => -1, 'desc' => '参数错误');
            return $data;
        }
        $getUserInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $levelId     = intval($getUserInfo['levelId']);
        if((intval($getUserInfo['spins']) - (1 * $multiple)) >=0 ){
            $userSpins =  intval($getUserInfo['spins']) - (1 * $multiple);
        }else{
            $userSpins =  0;
        }

        $setTime  = oo::commonOprModel('readconfig')->getCon('basic','restoreTime'); // 定义多久
        $setSpins = oo::commonOprModel('member')->getUserLevelUpLimit($uid,'recovery'); // 恢复多少
        $maxSpins = oo::commonOprModel('member')->getLevelUpLimit($levelId,'spins') ?? 50;

        $curTime  = time();

        //体力返回
        $keys = okeys::userRestoreTime($uid);
        $is_Restore = oo::commonOprRedis('common')->get($keys);
        //当获取后的体力大于50 或者 当前用户大于50
        if($userSpins >= $maxSpins){
            //先判断有没有在计时的数据 有的话把时间改为 0* 剩余时间 记录暂停
            if($is_Restore){
                //切割 时间戳*剩余时间
                $time = explode('*',$is_Restore);
                if($time[0] > 0 && $time[1] > 0){
                    //当前时间减去上一次记录的时间戳
                    //剩余时间
                    $last_time = $time[1] - ($curTime - $time[0]);//计算剩余时间 暂停处理 剩余时间-（当前时间-上一次记录时间戳）
                    if($last_time > 0){
                        $val = '0*'.$last_time;
                        oo::commonOprRedis('common')->set($keys, $val);
                    }else{
                        oo::commonOprRedis('common')->delete($keys);
                    }
                }
            }
        }else{
            //需要恢复体力
            if($is_Restore){
                //切割 时间戳*剩余时间
                $time = explode('*',$is_Restore);
                //判断是不是从上次暂停倒计时开始计时
                if($time[0] == 0){
                    //修改为当前时间戳并且继续倒计时
                    $val =  $curTime.'*'.$time[1];
                    oo::commonOprRedis('common')->set($keys, $val);
                    $lastTimes =  $setTime;
                }else{
                    $speedUp = "";
                    if(count($time) > 2){
                        $bet = $time[3];
                        $speedUpLastTime = $time[2];
                        if($curTime < $speedUpLastTime){
                            $temp_lastTime = ($curTime-$time[0]);
                            $speedUp = "*{$speedUpLastTime}";
                        }else{
                            $temp_lastTime = $curTime - $speedUpLastTime +  (($speedUpLastTime - $time[0]));
                        }
                    }else{
                        $temp_lastTime = $curTime-$time[0]; // 当前请求时间 - 上次存库时间   100
                    }
                    $lastTime = $time[1] - $temp_lastTime; //60 -100   -40
                    if($lastTime <= 0){
                        //倒计时结束 加体力 并且重新开始一个倒计时 因为体力还没满
                        //给用户加体力
                        //还有个计算  当前剩余时间 - 上次剩余时间  / 60
                        if($temp_lastTime > $lastTime){
                            $oneAddSpins = $setSpins;
                        }
                        $oneSpins     = floor(abs($lastTime) / $setTime);  //22
                        $oneAddSpins += $setSpins * $oneSpins; //110  //加的体力  3 + 0
                        //加倍恢复
                        $bet = oo::commonOprRedis('common')->get(okeys::SpeedUpSpins($uid))?oo::commonOprRedis('common')->get(okeys::SpeedUpSpins($uid)):1;
                        $oneAddSpins = $oneAddSpins*$bet;

                        $oneResidue   = $setTime - (abs($lastTime) - ($oneSpins * $setTime));  //10 //余下的时间
                        if($oneAddSpins>=$maxSpins || ($userSpins+$oneAddSpins) >= $maxSpins){
                            oo::commonOprRedis('common')->delete($keys); //停止计时
                            $changeNum = max($maxSpins - $getUserInfo['spins'],0);
                            oo::commonOprModel('member')->optProperty($uid,['spins'=>$changeNum],"+",111,"自动恢复");
                        }else{
                            oo::commonOprModel('member')->optProperty($uid,['spins'=>$oneAddSpins],'+',111,"自动恢复2=>原始体力:".$getUserInfo['spins']."bet:{$bet},恢复体力:".$oneAddSpins.",数据原始值".$is_Restore);
                            if($oneResidue && $oneResidue != 'null'){
                                $val = $curTime.'*'.$oneResidue; //test
                                $lastTimes =  $oneResidue;
                            }else{
                                $val = $curTime.'*'.$setTime;
                                $lastTimes =  $setTime;
                            }
                            oo::commonOprRedis('common')->set($keys, $val.$speedUp);
                        }
                    }else{
                        $val = $curTime.'*'.$lastTime;
                        oo::commonOprRedis('common')->set($keys, $val.$speedUp);
                        $lastTimes  =  $lastTime;
                    }
                }
            }else{
                $val = $curTime.'*'.$setTime;
                $lastTimes =  $setTime;
                oo::commonOprRedis('common')->set($keys, $val);
            }
        }

        $lastTimess = $lastTimes;
        return $lastTimess;
    }

    /**
     * 刷新体力操作
     * @param $uid
     * @param $multiple
     * @return array|float|int
     * Created by: Owen
     * Created on: 2020/1/9 16:08
     */
    public function refreshSpinsOld($uid,$multiple){
        if( empty($uid) ){
            $data = array('code' => -1, 'desc' => '参数错误');
            return $data;
        }
        $getUserInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $levelId     = intval($getUserInfo['levelId']);
        if((intval($getUserInfo['spins']) - (1 * $multiple)) >=0 ){
            $userSpins =  intval($getUserInfo['spins']) - (1 * $multiple);
        }else{
            $userSpins =  0;
        }

        $setTime  = oo::commonOprModel('readconfig')->getCon('basic','restoreTime'); // 定义多久
        $setSpins = oo::commonOprModel('member')->getUserLevelUpLimit($uid,'recovery'); // 恢复多少
        $maxSpins = oo::commonOprModel('member')->getLevelUpLimit($levelId,'spins') ?? 50;

        $curTime  = time();

        //体力返回
        $keys = okeys::userRestoreTime($uid);
        $is_Restore = oo::commonOprRedis('common')->get($keys);
        //当获取后的体力大于50 或者 当前用户大于50
        if($userSpins >= $maxSpins){
            //先判断有没有在计时的数据 有的话把时间改为 0* 剩余时间 记录暂停
            if($is_Restore){
                //切割 时间戳*剩余时间
                $time = explode('*',$is_Restore);
                if($time[0] > 0 && $time[1] > 0){
                    //当前时间减去上一次记录的时间戳
                    //剩余时间
                    $last_time = $time[1] - ($curTime - $time[0]);//计算剩余时间 暂停处理 剩余时间-（当前时间-上一次记录时间戳）
                    if($last_time > 0){
                        $val = '0*'.$last_time;
                        oo::commonOprRedis('common')->set($keys, $val);
                    }else{
                        oo::commonOprRedis('common')->delete($keys);
                    }
                }
            }
        }else{
            //需要恢复体力
            if($is_Restore){
                //切割 时间戳*剩余时间
                $time = explode('*',$is_Restore);
                //判断是不是从上次暂停倒计时开始计时
                if($time[0] == 0){
                    //修改为当前时间戳并且继续倒计时
                    $val =  $curTime.'*'.$time[1];
                    oo::commonOprRedis('common')->set($keys, $val);
                    $lastTimes =  $setTime;
                }else{
                    $speedUp = "";
                    if(count($time) > 2){
                        $bet = $time[3];
                        $speedUpLastTime = $time[2];
                        if($curTime < $speedUpLastTime){
                            $temp_lastTime = ($curTime-$time[0]) * $bet;
                            $speedUp = "*{$speedUpLastTime}*$bet";
                        }else{
                            $temp_lastTime = $curTime - $speedUpLastTime +  (($speedUpLastTime - $time[0]) * $bet);
                        }
                    }else{
                        $temp_lastTime = $curTime-$time[0]; // 当前请求时间 - 上次存库时间   100
                    }
                    $lastTime = $time[1] - $temp_lastTime; //60 -100   -40
                    if($lastTime <= 0){
                        //倒计时结束 加体力 并且重新开始一个倒计时 因为体力还没满
                        //给用户加体力
                        //还有个计算  当前剩余时间 - 上次剩余时间  / 60
                        if($temp_lastTime > $lastTime){
                            $oneAddSpins = $setSpins;
                        }
                        $oneSpins     = floor(abs($lastTime) / $setTime);  //22
                        $oneAddSpins += $setSpins * $oneSpins; //110  //加的体力  3 + 0
                        $oneResidue   = $setTime - (abs($lastTime) - ($oneSpins * $setTime));  //10 //余下的时间
                        if($oneAddSpins>=$maxSpins || ($userSpins+$oneAddSpins) >= $maxSpins){
                            oo::commonOprRedis('common')->delete($keys); //停止计时
                            $changeNum = max($maxSpins - $getUserInfo['spins'],0);
                             oo::commonOprModel('member')->optProperty($uid,['spins'=>$changeNum],"+",111,"自动恢复");
                        }else{
                            oo::commonOprModel('member')->optProperty($uid,['spins'=>$oneAddSpins],'+',111,"自动恢复2=>原始体力:".$getUserInfo['spins'].",恢复体力:".$oneAddSpins.",数据原始值".$is_Restore);
                            if($oneResidue && $oneResidue != 'null'){
                                $val = $curTime.'*'.$oneResidue; //test
                                $lastTimes =  $oneResidue;
                            }else{
                                $val = $curTime.'*'.$setTime;
                                $lastTimes =  $setTime;
                            }
                            oo::commonOprRedis('common')->set($keys, $val.$speedUp);
                        }
                    }else{
                        $val = $curTime.'*'.$lastTime;
                        oo::commonOprRedis('common')->set($keys, $val.$speedUp);
                        $lastTimes  =  $lastTime;
                    }
                }
            }else{
                $val = $curTime.'*'.$setTime;
                $lastTimes =  $setTime;
                oo::commonOprRedis('common')->set($keys, $val);
            }
        }

        $lastTimess = $lastTimes;
        return $lastTimess;
    }

    /**
     * 判断控制
     * @param $uid
     * @return string
     * Created by: Owen
     * Created on: 2020/5/15 11:51
     */
    public function getUserVersion($uid){
        $userInfo = oo::commonOprModel('member')->getUserInfo($uid, ['version'], false);
        return $userInfo['version']??'1.0.0';
    }

    /**
     * 判断控制
     * @param $uid
     * @return string
     * Created by: Owen
     * Created on: 2020/5/15 11:51
     */
    public function getUserChannel($uid){
        $userInfo = oo::commonOprModel('member')->getUserInfo($uid, ['channel'], false);
        return intval($userInfo['channel']);
    }

    /**
     * 获取用户登录设备
     * @param $uid
     * @return int
     * Created by: Owen
     * Created on: 2020/4/28 17:42
     */
    public function getUserLoginPlat($uid){
        $userinfo   = oo::commonOprModel('member')->getUserInfo($uid);
        $login_plat = ($userinfo['login_plat'])??1;
        return $login_plat;
    }

  	public function getAvatar($uid){
        $userinfo = oo::commonOprModel('member')->getUserInfo($uid);
        $data['avatar'] = $userinfo['avatar'];
        $data['avatarBox'] = json_decode($userinfo['avatarBox'],true);;
        return $data;
    }

    /**
     * 派发头像框
     * @param $uid
     * @param $scardId //0默认1,初级vip,2感恩节,3圣诞节,4中级vip,5高级vip,6至尊,7感恩節（新）
     * @return mixed
     * Created by: Owen
     * Created on: 2020/3/4 11:14
     */
    public function rewardAvatarBox($uid,$scardId){
        $userinfo = oo::commonOprModel('member')->getUserInfo($uid);
        $avatarBox = json_decode($userinfo['avatarBox'],true);
        $avatarBox[] = $scardId;
        $avatarBox = array_unique($avatarBox);
        $avatarBox = json_encode($avatarBox,JSON_NUMERIC_CHECK);
        $updateInfo['savatarBox'] = $avatarBox;
        oo::commonOprModel('member')->getUserInfo($uid, NULL, TRUE,$updateInfo);
        $userinfo = oo::commonOprModel('member')->getUserInfo($uid);
        $data['avatar'] = intval($scardId);
        $data['avatarBox'] = json_decode($userinfo['avatarBox'],true);
        return $data;
    }

    /**
     * Notes:初始化rechestking
     * User: wsc
     * Time: 2020/6/28 12:29
     * @param $uid
     * @param int $multiple
     * @return false|string
     */
    public function getRichestKing($uid,$multiple = 0,$new=false){
        //获取偷取对象统计,该统计取消
        //oo::commonOprModel('statistics')->getRichestKingSta($uid);
        $multiple = oo::commonOprRedis('usercache')->get(okeys::curUserBet($uid));
        if(!$multiple){
            oo::commonOprRedis('usercache')->setex(okeys::curUserBet($uid),1,3600*2);
        }
        if($new){
            oo::commonOprModel('steal')->clearBindKing($uid);//清理老的rechestking
        }
        if(oo::commonOprModel('Workerman')->isUidOnline($uid)){
            $version = $this->getUserVersion($uid);
            if(!oo::compareVersion($version,'1.8.1')){
                $attacks = oo::commonOprModel('level')->getStealData($uid);
            }else{
                $attacks = oo::commonOprModel('steal')->getStealData($uid);
            }
            if($attacks){
                $nick = oo::commonOprModel('member')->getUserFirstName($attacks['nick']);
                //快速推
                oo::commonOprModel('Workerman')->push($uid,ocmd::$SVR_PLAYER_RAID_INFO,array('levelId'=>$attacks["levelId"],'nick'=>$nick,'vip'=>$attacks['vip'],'vipLv'=>$attacks['vipLv'],'vipExpire'=>$attacks['vip_expire'],'avatar'=>intval($attacks['avatar']),'url'=>$attacks['s_picture'],'coins'=>intval($attacks['coins'])),true);
                return json_encode(['code'=>1, 'msg'=>'Triggers the successful retrieval of the object']);
            }else{
                return json_encode(['code'=>-2, 'msg'=>'No attacks object']);
            }
        }else{
            return json_encode(['code'=>-3, 'msg'=>'UnOnline']);
        }
    }

    /**
     * 检查 游客 FB 账号
     * @param $macType
     * @param $macAddress
     * @param $token
     * @param int $uid
     * @return array|bool
     * Created by: Owen
     * Created on: 2020/5/22 16:18
     */
    public function checkAccountSynchronize($userPlat,$macAddress,$token,$uid = 0,$deviceId = ""){
        if(empty($macAddress) || empty($token)){
            return false;
        }
        $ret = $this->loginByMac($userPlat,$macAddress,$deviceId);
        if(empty($ret)){
            return false;
        }
        $info = [] ;
        $uidArr = [
            'guest'   => $ret['uid'],
            'facebook'=> $uid
        ];
        foreach ($uidArr as $key=>$row){
            $userInfo   = oo::commonOprModel('member')->getUserInfo($row);
            $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($row);
            $lastTime   = ($key == "facebook") ? (oo::commonOprRedis('common')->get(okeys::FbAccountSynListTime($uid)) ?? (int)$userInfo['lasttime']) : (int)$userInfo['lasttime'];
            $info[$key] = [
                'uid'       => (int)$row,
                'nick'      => $userInfo['nick'],
                's_picture' => $userInfo['s_picture'],
                'avatar'    => (int)$userInfo['avatar'],
                'star'      => $assetsInfo['star'],
                'levelId'   => (int)$assetsInfo['levelId'],
                'vipLv'     => (int)$userInfo['vipLv'],
                'lastTime'  => $lastTime
            ];
        }
        return count($info)>=2 ? $info : false;
    }

    /**
     * @param $transformType 1 => 使用 FB 進度 2 => 使用 游客 進度
     * @param $macAddress
     * @param $token
     * @param int $uid
     * @param int $visitorUid
     * @return mixed
     * Created by: Owen
     * Created on: 2020/5/22 16:32
     */
    public function accountSynchronize($transformType,$macAddress,$token,$uid,$visitorUid,$deviceId){
        $macAddress = explode('_',base64_decode($macAddress));
        if(empty($macAddress) || empty($macAddress[0]) || $macAddress[1] != 'superant'){
            return oo::response(-1);
        }
        $userPlat       = self::getUserLoginPlat($visitorUid);
        $macAddressTemp = $this->getSiteIdByMac($userPlat,$macAddress[0]);
        $ret = $this->loginByMac($userPlat,$macAddressTemp,$deviceId);
        if(empty($ret)){
            $userPlat = ($userPlat == 1) ? 2 : 1;
            $macAddressTemp  = $this->getSiteIdByMac($userPlat,$macAddress[0]);
            $ret = $this->loginByMac($userPlat,$macAddressTemp,$deviceId);
            if(empty($ret)){
                return oo::response(-2,[],'游客賬號異常');
            }
        }
        if($visitorUid != $ret['uid']){
            return oo::response(-2,[],'MAC地址與UID不一致');
        }
        $visitorUid = $ret['uid'];
        $fbUserInfo = json_decode(funs::sendCurlPastThird('https://graph.facebook.com/me?access_token='.$token.'&fields=id,name,email,first_name,gender,locale,location,birthday,hometown,picture.height(200).width(200)'),true);
        if(empty($fbUserInfo)){
            return oo::response(-2,[],"FB 數據異常");
        }
        $siteUid = intval($fbUserInfo['id']);
        oo::commonOprRedis('user')->delete(okeys::account($siteUid));
        $account = oo::commonOprModel('member')->getAccount($siteUid);
        if(empty($account)){
            return oo::response(-2,[],"FB 賬號異常");
        }
        $fbUid = $account['uid'];
        if($uid != $fbUid){
            return oo::response(-2,['serverFbUid'=>$fbUid,'ClientFbUid'=>$uid],"FB UID 異常");
        }
        if($transformType == 2){
            $setAccountBool = oo::commonOprModel('member')->updateAccount($siteUid, $uid , $visitorUid);
            if($setAccountBool){
                $bool = $this->disconnectUidByMac($userPlat,$visitorUid,$macAddressTemp,$deviceId);
                $bool && oo::commonOprModel('member')->getUserInfo($visitorUid, NULL, TRUE, [
                    'ssiteuid'     =>$siteUid,
                    'snick'        =>isset($fbUserInfo['name'])  ? $fbUserInfo['name'] : $uid,
                    'ssex'         =>$fbUserInfo['gender']       ?? 'f',
                    'semail'       =>isset($fbUserInfo['email']) ? $fbUserInfo['email'] : '',
                    'ss_picture'   =>'https://graph.facebook.com/'.$siteUid.'/picture',
                    'sm_picture'   =>'https://graph.facebook.com/'.$siteUid.'/picture?type=normal',
                    'sb_picture'   =>'https://graph.facebook.com/'.$siteUid.'/picture?type=large',
                    'slocale'      =>isset($fbUserInfo['locale'])? $fbUserInfo['locale'] : '',
                    'slocationid'  =>isset($fbUserInfo['location']['id'])   ? $fbUserInfo['location']['id']   : '',
                    'slocationname'=>isset($fbUserInfo['location']['name']) ? $fbUserInfo['location']['name'] : '',
                    'shometownid'  =>isset($fbUserInfo['hometown']['id'])   ? $fbUserInfo['hometown']['id']   : '',
                    'shometownname'=>isset($fbUserInfo['hometown']['name']) ? $fbUserInfo['hometown']['name'] : '',
                ]) && oo::commonOprModel('member')->getUserInfo($uid, NULL, TRUE, [
                    'sstatus' => 3
                ]);

                /** 判断是否有IOS 与 FB 绑定的UID 与 FB 一起转到游客UID*/
                if($userPlat == 2){
                    $tb = otable::openudid();
                    $appleAuthAccountInfo = oo::commonOprDb('common')->getOne("SELECT * FROM {$tb} WHERE uid='{$fbUid}' AND openudid LIKE '%.%.%' LIMIT 1",MYSQLI_ASSOC);
                    if(!empty($appleAuthAccountInfo)){
                        $openudid = $appleAuthAccountInfo['openudid'];
                        oo::commonOprDb('common')->query("UPDATE {$tb} SET uid='{$visitorUid}' WHERE uid = {$fbUid} AND openudid='{$openudid}' LIMIT 1");
                        $this->setTransformLog(['sid'=> $userPlat, 'uid'=> $fbUid, 'transformType'=> 4, 'visitorUid'=> $visitorUid, 'visitorMac'=> $macAddressTemp, 'fbUid'=> $fbUid, 'fbSiteUid'=> $siteUid, 'fbToken'=> $openudid, 'time'=>time()]);
                    }
                }
            }
        }else if($transformType == 1){
            $bool = $this->disconnectUidByMac($userPlat,$visitorUid,$macAddressTemp,$deviceId);
            $bool && oo::commonOprModel('member')->getUserInfo($visitorUid, NULL, TRUE, ['sstatus' => 3]);
        }else{
            return oo::response(-2);
        }
        if($bool){
            $sqlBool = $this->setTransformLog(['sid'=> $userPlat, 'uid'=> $uid, 'transformType'=> $transformType, 'visitorUid'=> $visitorUid, 'visitorMac'=> $macAddressTemp, 'fbUid'=> $fbUid, 'fbSiteUid'=> $siteUid, 'fbToken'=> $token, 'time'=>time()]);
        }
        return $bool&&$sqlBool? oo::response(1) : oo::response(-2);
    }

    /**
     * fb 绑定
     * @param $uid
     * @param $macAddress
     * @param $fbToken
     * @return string
     * Created by: Owen
     * Created on: 2020/8/24 19:23
     */
    public function accountBind($uid,$macAddress,$fbToken,$del,$deviceId){
        $macAddress = explode('_',base64_decode($macAddress));
        if(empty($macAddress) || empty($macAddress[0]) || $macAddress[1] != 'superant'){
            return oo::response(-1);
        }
        $userPlat = self::getUserLoginPlat($uid);
        $actionMacAddress = $this->getSiteIdByMac($userPlat,$macAddress[0]);
        $ret = $this->loginByMac($userPlat,$actionMacAddress,$deviceId);
        if(empty($ret)){
            return oo::response(-2,[],'用户不存在');
        }
        if($uid != $ret['uid']){
            return oo::response(-3,[],'MAC 与 uid 不一致');
        }
        $fbUserInfo = json_decode(funs::sendCurlPastThird('https://graph.facebook.com/me?access_token='.$fbToken.'&fields=id,name,email,first_name,gender,locale,location,birthday,hometown,picture.height(200).width(200)'),true);
        if(empty($fbUserInfo)){
            return oo::response(-4,[],"Fb Token 异常");
        }
        $siteUid = intval($fbUserInfo['id']);
        oo::commonOprRedis('user')->delete(okeys::account($siteUid));
        $account = oo::commonOprModel('member')->getAccount($siteUid);

        if($account['uid'] == $ret['uid']){
            return oo::response(-7,[],"账号相同");
        }
        if(!empty($account)){
            $userInfo         = oo::commonOprModel('member')->getUserInfo($account['uid']);
            $userAssetsInfo   = oo::commonOprModel('member')->getUserAssetsInfo($account['uid']);
            $info = [
                'uid'       => (int)$account['uid'],
                'nick'      => $userInfo['nick'],
                's_picture' => $userInfo['s_picture'],
                'avatar'    => (int)$userInfo['avatar'],
                'star'      => $userAssetsInfo['star'],
                'levelId'   => (int)$userAssetsInfo['levelId'],
                'vipLv'     => (int)$userInfo['vipLv'],
                'lastTime'  => (int)$userInfo['lasttime']
            ];
            return oo::response(-5,['fbData'=>$info],"fb 账号已存在");
        }
        $setAccountBool = oo::commonOprModel('member')->setAccount($siteUid, $uid);
        if($setAccountBool == 0){
            $del && $this->disconnectUidByMac($userPlat,$uid,$actionMacAddress,$deviceId);
            $updateInfo = [
                'ssiteuid'      => $siteUid,
                'stoken'        => $fbToken,
                'snick'         => isset($fbUserInfo['name']) ? $fbUserInfo['name'] : $uid,
                'ssex'          => $fbUserInfo['gender'] ?? 'f',
                'semail'        => isset($fbUserInfo['email']) ? $fbUserInfo['email'] : '',
                'ss_picture'    => 'https://graph.facebook.com/' . $siteUid . '/picture',
                'sm_picture'    => 'https://graph.facebook.com/' . $siteUid . '/picture?type=normal',
                'sb_picture'    => 'https://graph.facebook.com/' . $siteUid . '/picture?type=large',
                'slocale'       => isset($fbUserInfo['locale']) ? $fbUserInfo['locale'] : '',
                'slocationid'   => isset($fbUserInfo['location']['id']) ? $fbUserInfo['location']['id'] : '',
                'slocationname' => isset($fbUserInfo['location']['name']) ? $fbUserInfo['location']['name'] : '',
                'shometownid'   => isset($fbUserInfo['hometown']['id']) ? $fbUserInfo['hometown']['id'] : '',
                'shometownname' => isset($fbUserInfo['hometown']['name']) ? $fbUserInfo['hometown']['name'] : '',
            ];
            oo::commonOprModel('member')->getUserInfo($uid, NULL, TRUE, $updateInfo);
            $reward = [
                'money' => intval(oo::commonOprModel('readconfig')->getCon("Game","fbBindCoins")),
                'spins' => intval(oo::commonOprModel('readconfig')->getCon("Game","fbBindSpins")),
            ];
            oo::commonOprModel('member')->optProperty($uid,$reward,'+',109,"游客绑定FB账号");
            /**
             * 被邀请者绑定FB给予邀请者奖励
             */
            oo::commonOprModel('invite')->recordInviteBindFb($uid);
            oo::commonOprModel('ta')->setEventData($uid,'user_setOnce',["account_bind_time"=>time()]);
            return oo::response(1,[
                'nick'      =>$updateInfo['snick'] ,
                'sex'       =>$updateInfo['ssex'] ,
                's_picture' =>$updateInfo['ss_picture'] ,
            ]);
        }
        return oo::response(-6,[],'服务器数据异常');
    }

    /**
     * 根据Mac地址获取SiteId
     * @param $sid
     * @param $identify
     * @param string $superKey
     * @return int|string
     * Created by: Owen
     * Created on: 2021/4/10 9:41
     */
    public function getSiteIdByMac($sid,$identify,$superKey = ""){
        if($sid == 1){
            $mac = funs::macToSiteUid($identify);
            if($mac==0 && !empty($identify) && $identify!='null'){
                $mac= funs::AdvertisementIdToSiteUid($identify);
            }
            if($mac==0 && !empty($superKey)){
                $tb  = otable::super();
                $ret = oo::commonOprDb('account')->getOne("SELECT * FROM {$tb} WHERE superKey='{$superKey}' LIMIT 1",MYSQLI_ASSOC);
                if(empty($ret)){
                    $mac = date('Ymd').time().rand(0,10000);
                    $sql = "INSERT INTO {$tb} (superKey,siteuid) VALUES ('{$superKey}','{$mac}')";
                    oo::commonOprDb('account')->query($sql,false);
                }else{
                    $mac = $ret['siteuid'];
                }
            }
        }else{
            $mac = $identify;
        }
        return $mac;
    }

    /**
     * 设置deviceId 与 uid 关系
     * @param $sid
     * @param $uid
     * @param $deviceId
     * @param $lid
     * Created by: Owen
     * Created on: 2021/4/10 10:54
     */
    public function setUserDeviceId($sid,$uid,$deviceId,$lid){
        $tb = otable::DeviceId();
        $sid = !empty($sid)?$sid:1;
        $lid = !empty($lid)?$lid:2;
        !empty($deviceId) && oo::commonOprDb('userinfo')->query("REPLACE INTO {$tb} (`sid`, `uid`, `deviceId`,`lid`) VALUES ({$sid},{$uid},'{$deviceId}',{$lid})");
    }

    /**
     * IOS 授权登录
     * @param $site
     * @param $appleUserId
     * @param $appleIdentityToken
     * @return array
     * Created by: Owen
     * Created on: 2021/4/10 11:33
     */
    public function iosLoginByAppleUserId($siteId,$appleUserId,$appleIdentityToken){
        if(empty($appleIdentityToken)){
            $errArr = ['code'=>0,'uid'=>-1,'line'=>__LINE__,'msg'=>"token empty"];
            funs::errLog($errArr);
            return ['err' => $errArr];
        }
        $ret = oo::commonOprModel('ios')->appleJwtVerify($appleIdentityToken);
        $packages = ['com.astak.crazyspin', 'com.gworld.crazyspinios', 'com.newsky.crazycoin'];
        if(!$ret['status'] || !in_array($ret['data']['aud'], $packages) || $ret['data']['sub'] != $appleUserId){
            $errArr = ['code'=>0,'uid'=>-1,'line'=>__LINE__,'msg'=>$ret['error']];
            funs::errLog($errArr);
            return ['err' => $errArr];
        }
        $isAppleAuthUser = oo::commonOprDb('userinfo')->getOne(sprintf("SELECT * FROM %s WHERE openudid='%s'", otable::openudid(), $appleUserId),MYSQLI_ASSOC);
        if(empty($isAppleAuthUser)){
            $isVisitor = oo::commonOprDb('userinfo')->getOne(sprintf("SELECT * FROM %s WHERE openudid='%s'", otable::openudid(), $siteId),MYSQLI_ASSOC);
            if(!empty($isVisitor)){
                oo::commonOprDb('userinfo')->query(sprintf("INSERT INTO %s (openudid,uid,createtime) VALUES('%s',%d,%d)", otable::openudid(), $appleUserId, $isVisitor['uid'], time()));
            }
        }
        $loginInfo = oo::commonOprDb('userinfo')->getOne(sprintf("SELECT * FROM %s WHERE openudid='%s'", otable::openudid(), $appleUserId),MYSQLI_ASSOC);
        return $loginInfo ;
    }

    /**
     * 游客登录
     * @param $sid
     * @param $siteId
     * @param string $deviceId
     * @return array
     * Created by: Owen
     * Created on: 2021/4/10 15:40
     */
    public function loginByMac($sid,$siteId,$deviceId = ""){
        return $sid == 1 ? $this->androidLoginByMac($siteId,$deviceId) : $this->iosLoginByMac($siteId);
    }

    /**
     * IOS 游客登录
     * @param $siteId
     * @return array
     * Created by: Owen
     * Created on: 2021/4/10 12:01
     */
    public function iosLoginByMac($siteId){
        return oo::commonOprDb('userinfo')->getOne(sprintf("SELECT * FROM %s WHERE openudid='%s'", otable::openudid(), $siteId),MYSQLI_ASSOC);
    }

    /**
     * android 游客登录
     * @param $siteId
     * @param string $deviceId
     * Created by: Owen
     * Created on: 2021/4/10 12:12
     */
    public function androidLoginByMac($siteId,$deviceId = ""){
        $ret = oo::commonOprDb('userinfo')->getOne(sprintf("SELECT * FROM %s WHERE macid='%s'", otable::mobile(), $siteId),MYSQLI_ASSOC);
        if(empty($ret)){
            $ret = oo::commonOprDb('userinfo')->getOne(sprintf("SELECT * FROM %s WHERE deviceId='%s' AND lid='%d'", otable::DeviceId(), $deviceId,2),MYSQLI_ASSOC);
        }
        return $ret;
    }

    /**
     * 断开游客与mac的联系
     * @param $sid
     * @param $uid
     * @param $identify
     * @param string $deviceId
     * @return mixed
     * Created by: Owen
     * Created on: 2021/4/10 15:43
     */
    public function disconnectUidByMac($sid,$uid,$identify,$deviceId = ""){
        if($sid == 1){
            $bool= oo::commonOprDb('common')->query(sprintf("DELETE FROM %s WHERE uid='%d' AND macid='%s'", otable::mobile(), $uid , $identify));
            $bool && !empty($deviceId) && oo::commonOprDb('common')->query(sprintf("DELETE FROM %s WHERE uid='%d' AND deviceId='%s'", otable::DeviceId(),$uid,$deviceId));
        }else{
            $bool= oo::commonOprDb('common')->query(sprintf("DELETE FROM %s WHERE uid='%d' AND openudid='%s'", otable::openudid(), $uid , $identify));
        }
        return $bool;
    }

    /**
     * 账号转换记录
     * @param $insertData
     * @return mixed
     * Created by: Owen
     * Created on: 2021/4/13 11:06
     */
    public function setTransformLog($insertData){
        $tb      = otable::TransformLog();
        $keys    = implode(',',array_keys($insertData));
        $values  = "'".implode("','",array_values($insertData))."'";
        return oo::commonOprDb('common')->query("INSERT INTO {$tb} ({$keys}) VALUES ({$values})");
    }

    /**
     * Notes:用户头像框发放
     * User: wsc
     * Time: 2022/6/30 14:59
     * @param $uid
     * @param $aid
     */
    public function sendUserAvatar($uid,$aid){
        $key =okeys::userAvatar($uid);
        $alist = oo::commonOprRedis('common')->hGetAll($key);
        if(in_array($aid,array_keys($alist))){
            return -1;
        }
        $tb = otable::userAvatar();
        $data =[
            "uid"=>$uid,
            "avatar_id"=>$aid,
            "active"=>1,
            "created_at"=>time(),
        ];
        $sql = funs::db_insertSQL($tb,$data);
        $ret = oo::commonOprDb('common')->query($sql,1);
        $id = oo::commonOprDb('common')->insertID();
        if(!$ret){
            return -2;
        }
        $data['id'] = $id;
        oo::commonOprRedis('common')->hSet($key,$aid,json_encode($data));
        oo::commonOprRedis('common')->expire($key,7*86400);
        return 1;
    }
}
