<?php

defined('IN_WEB') or die('Include Error!');
define('MAX_FRIEND_NUM', 300);
define('APPLY_FRIEND_MSG', 0x4200);
define('APPLY_FRIEND_REVIEW', 0x4201);
/**
 * 好友相关逻辑
 */
class ModelFriend{
    /**
     * 获取用户的好友列表
     * @param $uid
     * @param $friends
     * @return int 0,失败; =0,没有记录; >0,有记录
     * Created by: Owen
     * Created on: 2020/9/2 15:15
     */
    public function getUserFriends($uid, &$friends){
        if (!$uid = oo::functions()->uint($uid)) {
            return -1;
        }
        $tb = otable::userfriends($uid);
        $query = "select uid, isapper, notapper, game_list,poker ,updatetime, watchme from {$tb} where uid='{$uid}' limit 1";
        $friends = oo::commonOprDb('userfriends')->getOne($query, MYSQLI_ASSOC);
        if ($friends == false) {
            $friends = array('uid' => $uid, 'isapper' => '', 'notapper' => '', 'game_list' => '', 'updatetime' => 0, 'watchme' => '');
        }
        return 1;
    }

    /**
     * 保存用户的好友列表
     * @param $uid
     * @param null $array
     * @return int
     * Created by: Owen
     * Created on: 2020/9/2 15:16
     */
    public function setUserFriends($uid, $array = NULL){
        if (!$uid) return -1;
        if (empty($array)) return 0;
        $data = array(
            'isapper'    => $array['sisapper'],
            'notapper'   => $array['snotapper'],
            'poker'      => $array['spoker'],
            'updatetime' => (int)$array['iupdatetime'],
        );
        $data['isapper']  = oo::functions()->escape($data['isapper']);
        $data['notapper'] = oo::functions()->escape($data['notapper']);
        $data['poker']    = oo::functions()->escape($data['poker']);
        $tb    = otable::userfriends($uid);
        $query = "insert into {$tb} (uid,isapper,notapper,poker,updatetime) values ('{$uid}','{$data['isapper']}','{$data['notapper']}','{$data['poker']}','{$data['updatetime']}')";
        $ret   = oo::commonOprDb('userfriends')->query($query);
        return $ret ? 0 : -2;
    }

    /**
     * 获取上次好友召回时间
     * @param int $uid
     * @param int $toUid
     * @return int
     */
    public function getCallBackTime($uid, $toUid) {
        return (int)oo::commonOprRedis('common')->hGet(okeys::callBackFriend($uid), $toUid);
    }

    /**
     * 获取上次好友列表召回时间
     */
    public function getListCallBackTime($uid, $toUids) {
        return oo::commonOprRedis('common')->hMGet(okeys::callBackFriend($uid), $toUids);
    }

    /**
     * 获取召回奖励物品
     * @param array
     */
    public function callbackConf() {
        $tmp = oo::commonOprRedis('common')->get(okeys::callbackConfig());
        //如果空数据返回一个默认值
        $config = [];
        if(!empty($tmp)){
            $config = (array)json_decode($tmp, true);
        }
        if(empty($config['level'])){
            $config['level'] = 2;
        }
        if(empty($config['reward'])){
            $config['reward'] = ['props' => [['propsId' => 15, 'num' => 30], ['propsId' => 2, 'num' => 1]]];
        }
        return $config;
    }

    public function canCallback($userInfo, $levelId, $lastCallbackTime = 0, array $conf = array()) {
        if(empty($conf)){
            $conf = oo::commonOprModel('friend')->callbackConf();
        }
        //好友等级太低，不能召回
        if($levelId < $conf['level']){
            return false;
        }

        //召回好友只支持fb玩家
        if(empty($userInfo['isFb'])){
            return false;
        }

        if($userInfo['lasttime'] + 15 * 24 * 3600 > time()){
            return false;
        }

        if($lastCallbackTime && $lastCallbackTime >= time()){
            return false;
        }
        return true;
    }

    /**
     * 获取好友数量进度奖励配置
     */
    public function friendsProgressRewardConf() {
        $key = okeys::friendProgressRewardConfig();
        $tmp = oo::commonOprRedis('common')->hgetall($key);
        $data = [];
        if(empty($tmp)){
            $tb = otable::friendProgressConfig();
            $sql = "SELECT * FROM {$tb} ORDER BY num asc";
            $tmp  =oo::commonOprDb('config')->getAll($sql, MYSQLI_ASSOC);
            foreach($tmp as $k => $v){
                $v['reward'] = json_decode($v['reward'], true);
                $data[] = $v;
            }
            oo::commonOprRedis('common')->set($key, json_encode($data));
        }else{
            $data = json_decode($tmp, true);
        }
        return $data;
    }

    /**
     * 获取我的好友数量进度及奖励
     * @param int $uid
     * @return array
     */
    public function getUserFriendsProgress($uid) {
        $step = (int)oo::commonOprRedis('common')->get(okeys::friendProgressReward($uid));
        $config = $this->friendsProgressRewardConf();
        $data = ['step' => $step];
        if($step + 1 <= count($config)){
            $data['reward'] = $config[$step]['reward'];
            $data['num'] = $config[$step]['num'];
        }else{
            $data['reward'] = [];
        }

        $coins = 0;
        if(!empty($data['reward']['coins'])){
            $coins = oo::commonOprModel('goods')->getGoodCoins($uid, $data['reward']['coins']['coins']);
            $coins = intval($coins * $data['reward']['coins']['bet']);
            unset($data['reward']['coins']);
        }

        if(empty($data['reward']['props'])){
            if($coins > 0){
                $data['reward']['props'] = [
                    ['propsId' => 14, 'num' => $coins],
                ];
            }
            return $data;
        }
        $coinsAdded = false;
        foreach($data['reward']['props'] as $k => $val){
            if($val['propsId'] == 14){
                $coinsAdded = true;
            }
            if($coins > 0 && $val['propsId'] == 14){
                $val['num'] += $coins;
                $data['reward']['props'][$k] = $val;
                break;
            }
        }
        if(!$coinsAdded && $coins > 0){
            $data['reward']['props'][] = ['propsId' => 14, 'num' => $coins];
        }

        return $data;
    }

    /**
     * 更新召回可领奖标志
     * @param int $uid
     */
    public function dealCallBackFriend($uid){
        $fids = $this->getBeCallBackList($uid);
        foreach($fids as $fid){
            //添加召回我的好友可领奖标志
            oo::commonOprRedis('common')->sAdd(okeys::callBackReward($fid), $uid);
            //推送消息
            oo::commonOprModel('Workerman')->push($fid,ocmd::$send['Friend_callback'], ['type' => 11]);
            //发送消息到message
            $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
            oo::commonOprModel('message')->addMessage($fid,$uid,$userInfo['nick'],$userInfo['s_picture'],0,11,0);
            //30天过期
            oo::commonOprRedis('common')->expire(okeys::callBackReward($fid), oo::redisRandomExpire(24 * 3600 * 30));
        }
    }

    /**
     * 获取当前是否有新召回的好友
     * @param int $uid
     * @return int (0|1)
     */
    public function hasNewCallback($uid) {
        return oo::commonOprRedis('common')->sSize(okeys::callBackReward($uid)) ? 1 : 0;
    }

    /**
     * 获取玩家召回奖励
     * @param int $uid
     * @return array
     */
    public function getCallbackListInfo($uid) {
        $data = [];
        $list = oo::commonOprRedis('common')->sMembers(okeys::callBackReward($uid));

        if(empty($list)){
            return [];
        }
        $listArr = [];
        foreach($list as $v){
            $userInfo = oo::commonOprModel('member')->getUserInfo($v);
            $listArr[] = [
                'nick'      => $userInfo['nick'],
                's_picture' => $userInfo['s_picture'],
                'uid'       => $v,
            ];
        }
        $data['list'] = $listArr;
        $tmp = $this->callbackConf();
        $reward = $tmp['reward'];

        $coins = 0;
        if(!empty($reward['coins'])){
            $coins = oo::commonOprModel('goods')->getGoodCoins($uid,$reward['coins']['coins']);
            $coins = intval($coins * $reward['coins']['bet']);
            unset($reward['coins']);
        }
        $count = count($list);
        $coinsAdded = false;
        foreach($reward['props'] as $k => $val){
            if($val['propsId'] == 14){
                $coinsAdded = true;
            }
            if($coins > 0 && $val['propsId'] == 14){
                $val['num'] = intval(($val['num'] + $count) * $coins);
            }else{
                $val['num'] = $val['num'] * $count;
            }
            $reward['props'][$k] = $val;
        }
        if(!$coinsAdded && $coins > 0){
            if(empty($reward['props'])){
                $reward['props'] = [];
            }
            $reward['props'][] = ['propsId' => 14, 'num' => intval($coins * $count)];
        }
        $data['reward'] = $reward;
        return $data;
    }

    /**
     * 获取召回我的好友id列表
     * @param int $uid
     * @return array
     */
    public function getBeCallBackList($uid) {
        $expire = strtotime(date('Y-m-d', strtotime('-3 days')));
        $ret = oo::commonOprRedis('common')->zRangeByScore(okeys::beCallBackFriend($uid), $expire, time());
        //3天之前点击召回的玩家不给奖励
        if(!empty($ret) && count($ret) > 10){
            //大于10个记录后手动删除过期邀请id数据
            oo::commonOprRedis('common')->zDeleteRangeByScore(okeys::beCallBackFriend($uid), 0, $expire - 1);
        }
        return (array)$ret;
    }

    /**
     * 更新召回好友记录
     * @param int $uid
     * @param int $toUid
     * @return array
     */
    public function callbackFriend($uid, $toUid) {
        $expire = strtotime(date('Y-m-d', strtotime('+1 days')));
        oo::commonOprRedis('common')->hSet(okeys::callBackFriend($uid), $toUid, $expire);
        oo::commonOprRedis('common')->expireAt(okeys::callBackFriend($uid), oo::redisRandomExpire($expire)); //1天过期
        //添加被召回记录,领奖用
        $bexpire = strtotime(date('Y-m-d', strtotime('+3 days')));
        oo::commonOprRedis('common')->zAdd(okeys::beCallBackFriend($toUid), time(), $uid);
        oo::commonOprRedis('common')->expireAt(okeys::beCallBackFriend($toUid), oo::redisRandomExpire($bexpire)); //3天过期
        return ['fid' => $toUid, 'expire' => $expire];
    }

    /**
     * 更新用户的好友列表
     * @param $uid
     * @param array 需要保存的数组字段
     * @return int <0,失败; =0,成功
     * Created by: Owen
     * Created on: 2020/9/2 15:17
     */
    public function updateUserFriends($uid, $array = NULL){
        if (!$uid) return -1;
        if (empty($array)) return 0;
        $updateStr = "";
        if (isset($array['sisapper'])) {
            $array['sisapper'] = oo::functions()->escape($array['sisapper']);
            $updateStr .= "isapper='{$array['sisapper']}',";
        }
        if (isset($array['snotapper'])) {
            $array['snotapper'] = oo::functions()->escape($array['snotapper']);
            $updateStr .= "notapper='{$array['snotapper']}',";
        }
        if (isset($array['spoker'])) {
            $array['spoker'] = oo::functions()->escape($array['spoker']);
            $updateStr .= "poker='{$array['spoker']}',";
        }
        if (isset($array['iupdatetime'])) {
            $array['iupdatetime'] = (int)$array['iupdatetime'];
            $updateStr .= "updatetime='{$array['iupdatetime']}',";
        }
        if (empty($updateStr)) {
            return 0;
        } else {
            $updateStr = rtrim($updateStr, ',');
        }
        $tb = otable::userfriends($uid);
        $query = "update {$tb} set {$updateStr} where uid='{$uid}' limit 1";
        $ret = oo::commonOprDb('userfriends')->query($query);
        oo::commonOprRedis('userinfo')->delete(okeys::userfriends($uid,'fb'));
        oo::commonOprRedis('userinfo')->delete(okeys::userfriends($uid,'all'));
        //更新干掉缓存，待获取时再更新缓存
        return $ret ? 0 : -2;
    }


    /**
     *    单个玩家赠送礼物   暂定每天每人只能送一次  每次1个体力 50K金币  系统给
     * @param uid 用户uid  fuid 赠送好友uid  gid =1金币 2体力 3卡片
     */
    public function sendPropToFriend($uid = 0, $fuid = 0, $gid = 0)
    {
        $data = array('code' => -1);
        if (!$uid || !$fuid) {
            return $data;
        }

        $hadSend = $this->checkSendPropToFri($uid, $fuid, $gid);
        if ($hadSend) {
            $data['code'] = -2;
            $data['msg'] = '您已经赠送过该好友了。';
            return $data;
        }

        $info = oo::commonOprModel('member')->getUserInfo($uid);
        if (empty($info)) {
            $data['code'] = -4;
            return $data;
        }

        $key = okeys::userSendFri($uid, $fuid, $gid);
		oo::commonOprRedis('common')->setex($key,1, oo::todayDeadline());
        $nows = time();
        $table = otable::gift($fuid);
        $exp = strtotime(date('Y-m-d H:i:s', strtotime('+3day')));
        $sql = " INSERT INTO {$table} VALUES (NULL,$fuid, $gid, 2, 0 , $nows, $exp,$uid,NULL)";
        $insertRs = oo::commonOprDb('usergift')->query($sql);
        if (!$insertRs) {
            oo::logs()->debug3($sql, 'addUserGift.log');
            return false;
        }

        $today = strtotime(date("Y-m-d"), time()); //当天开始时间戳
        $end = $today + 60 * 60 * 24; //当天结束时间戳
        $table = otable::gift($uid);
        $sql = "SELECT * FROM " . $table . " WHERE  uid =" .$uid . "  AND gid= " . $gid . " AND fid = " . $fuid . "  AND gtime>={$today} AND gtime <= " . $end;
        $usergiftList = oo::commonOprDb('usergift')->getOne($sql, MYSQLI_ASSOC); //

        $data['code'] = 1;
        $data['msg'] = '赠送成功';
        $data['data']['gid'] = $gid;
        if($gid == 1){
            $data['data']['num'] = oo::commonOprModel('readconfig')->getCon('FriendProp','money');
        }else if($gid == 2){
            $data['data']['num'] = oo::commonOprModel('readconfig')->getCon('FriendProp','spins');
        }
        $data['state'] = ($usergiftList)?2:0;
        oo::commonOprModel('Workerman')->push($fuid,ocmd::$redPoint,['type'=>5]);
		
		//赠送情况统计
        oo::commonOprModel('statistics')->giveSta($gid==1?'money':'spins','Send',$uid,$data['data']['num']);

        return $data;
    }

    /**
     *    单个好友道具领取  0已赠送 1赠送 2领取
     * $uid 自己的id $fuid 好友的uid $gid 类型id
     */
    public function FriendPropReceive($uid, $fuid, $gid)
    {
        $data = array('code' => -1);
        if (!$uid || !$gid || !$fuid) {
            return $data;
        }
        //先查出这个用户的状态是否有可领取的道具
        //领取当天的所有道具
        $receive = $this->checkReceive($uid, $gid,$fuid);//可以领取的uid  redis改变状态
        $table = otable::gift($uid);
        $nows = time();
        $sql = "SELECT * FROM " . $table . " WHERE  uid =" . $uid . "  AND gid= " . $gid . " AND fid = " . $fuid . "  AND is_receive=0 AND expire >= " . $nows . " ORDER BY gtime DESC,id DESC  ";
        $friList = oo::commonOprDb('usergift')->getOne($sql, 1);
		$version = oo::commonOprModel('user')->getUserVersion($uid);
        if ($receive) {
            foreach ($receive as $k => $v) {
                if ($v['id'] == $friList['id']) {
                    //可以领取
                    if ($gid == 1) {
                        //金币
                        $money_num = oo::commonOprModel('readconfig')->getCon('FriendProp','money');
                        $max = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMax($gid),$uid));
                        if($max>=$money_num*200){
                            $money_num = 0;
                        }else{
                            oo::commonOprModel('member')->optProperty($uid, array('money' => $money_num), '+',50, '好友赠送金币');
                            oo::commonOprRedis('common')->hSet(okeys::friendGiftMax($gid),$uid,$max+$money_num);
                        }
                    } else if ($gid == 2) {
                        //体力
                        $spins_num = oo::commonOprModel('readconfig')->getCon('FriendProp','spins');
                        $max = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMax($gid),$uid));
                        if($max>=$spins_num*200){
                            $spins_num = 0;
                        }else{
                            oo::commonOprModel('member')->optProperty($uid, array('spins' => $spins_num), '+',50, '好友赠送体力');
                            oo::commonOprRedis('common')->hSet(okeys::friendGiftMax($gid),$uid,$max+$spins_num);
                        }
                    } else if ($gid == 3) {
                        //卡片
                    }
                    $data['code'] = 1;
                    $data['msg'] = '领取成功';
                    $data['money_num'] = isset($money_num) ? $money_num : 0;
                    $data['spins_num'] = isset($spins_num) ? $spins_num : 0;
                    // 判斷我是否有給他贈送禮物
                    $today = strtotime(date("Y-m-d"), time()); //当天开始时间戳
                    $end = $today + 60 * 60 * 24; //当天结束时间戳
                    $table = otable::gift($uid);
                    $sql = "SELECT * FROM " . $table . " WHERE  uid =" .$uid . "  AND gid= " . $gid . " AND fid = " . $fuid . "  AND gtime>={$today} AND gtime <= " . $end;
                    $usergiftList = oo::commonOprDb('usergift')->getOne($sql, MYSQLI_ASSOC); //
                    $flag = ($usergiftList)?0:1;
                    $data['state'] = $flag;
                    $tempKey = okeys::userSendFri($fuid,$uid,$gid);;
                    oo::commonOprRedis('common')->delete($tempKey);
                    oo::commonOprModel('gift')->updateUserGift($v['id'], $uid, $gid);
					
					//领取情况统计
                    if($gid == 1){
                    	$num = $data['money_num'];
                    }else{
                    	$num = $data['spins_num'];
                    }
                    oo::commonOprModel('statistics')->giveSta($gid==1?'money':'spins','Receive',$uid,$num);
                }
            }
        } else {
          	oo::commonOprRedis('common')->delete(okeys::userSendFri($fuid,$uid,$gid));
            $data['code'] = -2;
            $data['msg'] = '失败';
        }

        return $data;
    }

    /**
     *    一键批量领取并赠送赠送好友  卡片除外  暂时game_list好友
     */
    public function sendPropToFriends($uid = 0, $gid = 0)
    {
        $data = array('code' => -1);
        if (!$uid || !$gid) {
            return $data;
        }

        //获取好友列表
        $friendList = $this->getUserAllFriend($uid);
        if (!is_array($friendList)) {
            $data['code'] = -2;
            $data['msg'] = '您的好友列表为空！';
            return $data;
        }
        //领取当天的所有道具
        $receive = $this->checkReceive($uid, $gid);//可以领取的uid
        if ($receive) {
            $count_num = count($receive); //统计数量
            if ($gid == 1) {
                //金币
                $money_num  = oo::commonOprModel('readconfig')->getCon('FriendProp','money');
                $action_num = $count_num * $money_num;
                $max  = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMax($gid),$uid));
                $temp = $money_num*200 - $max;
                if($temp>=$action_num){
                    oo::commonOprModel('member')->optProperty($uid, array('money' => $action_num), '+',50, '好友赠送金币');
                    oo::commonOprRedis('common')->hSet(okeys::friendGiftMax($gid),$uid,$max+$action_num);
                    oo::commonOprModel('Workerman')->push($uid,ocmd::$SVR_UPDATE_COINS,['num'=>$action_num]);
                }else{
                    oo::commonOprModel('member')->optProperty($uid, array('money' => $temp), '+',50, '好友赠送金币');
                    oo::commonOprRedis('common')->hSet(okeys::friendGiftMax($gid),$uid,$max+$temp);
                    oo::commonOprModel('Workerman')->push($uid,ocmd::$SVR_UPDATE_COINS,['num'=>$temp]);
                }
            } else if ($gid == 2) {
                //体力
                $spins_num  = max(oo::commonOprModel('readconfig')->getCon('FriendProp','spins'),1);
                $userAssets = oo::commonOprModel('member')->getUserAssetsInfo($uid);
                $needAdd    = max(50 - $userAssets['spins'],0);
                $needAcTime = ceil($needAdd/$spins_num);
                $count_num  = min($count_num,$needAcTime);
                $action_num = $count_num * $spins_num;
                $max  = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMax($gid),$uid));
                $temp = $spins_num*200 - $max;
                if($temp>=$action_num){
                    oo::commonOprModel('member')->optProperty($uid, array('spins' => $action_num), '+',50, '好友赠送体力');
                    oo::commonOprRedis('common')->hSet(okeys::friendGiftMax($gid),$uid,$max+$action_num);
                }else{
                    oo::commonOprModel('member')->optProperty($uid, array('spins' => $temp), '+',50, '好友赠送体力');
                    oo::commonOprRedis('common')->hSet(okeys::friendGiftMax($gid),$uid,$max+$temp);
                }
            }
            foreach ($receive as  $k=> $v) {
                if($gid == 2 && $k >= $count_num){
                    continue;
                }
                //更改礼物领取状态
                oo::commonOprModel('gift')->updateUserGift($v['id'], $uid, $gid);
                $tempKey = okeys::userSendFri($v['fuid'], $uid, $gid);
                oo::commonOprRedis('common')->delete($tempKey);
            }
			
			//领取情况
            if(isset($action_num) && isset($temp)){
            	if($temp >= $action_num){
            		oo::commonOprModel('statistics')->giveSta($gid==1?'money':'spins','Receive',$uid,$action_num);
            	}else{
            		oo::commonOprModel('statistics')->giveSta($gid==1?'money':'spins','Receive',$uid,$temp);
            	}
            	
            	//一键领取 人数统计
            	oo::commonOprModel('statistics')->givesSta($gid==1?'money':'spins','Receive',$uid);
            }
        }

        $myGameList = $friendList;
        $myGameList = array_filter($myGameList);
        if (empty($myGameList)) {
            $data['code'] = -2;
            return $data;
        }

        //忽略已经赠送的好友
        $hasSendFriList = array();
        foreach ($myGameList as $fuid) {
            $key = okeys::userSendFri($uid, $fuid, $gid);
            $hasSend = oo::commonOprRedis('common')->get($key);
            if ($hasSend) {
                array_push($hasSendFriList, $fuid);
            }else{
                // 查庫
                $today = strtotime(date("Y-m-d"), time()); //当天开始时间戳
                $end = $today + 60 * 60 * 24; //当天结束时间戳
                $table = otable::gift($fuid);
                $sql = "SELECT * FROM " . $table . " WHERE  uid =" .$fuid . "  AND gid= " . $gid . " AND fid = " . $uid . "  AND gtime>={$today} AND gtime <= " . $end;
                $usergiftList = oo::commonOprDb('usergift')->getOne($sql, MYSQLI_ASSOC); //
                if($usergiftList)
                    array_push($hasSendFriList, $fuid);
            }
        }


        $myGameList = array_diff($myGameList, $hasSendFriList);//过滤的

        if (empty($myGameList)) {//所有好友已经赠送完毕
            $data['code'] = -3;
            $data['msg'] = '所有好友已经赠送完毕';
            return $data;
        }

        $GameListCount = count($myGameList);//赠送好友的数量


        //开始赠送
        $info = oo::commonOprModel('member')->getUserInfo($uid);
        if (empty($info)) {
            $data['code'] = -6;
            return $data;
        }

        //记录缓存(批量操作)
        $cacheList = array();
        $nows = time();
        $exp = strtotime(date('Y-m-d H:i:s', strtotime('+3day')));
        $uidInfo = oo::commonOprModel('member')->getUserInfo($uid);
        $myGameList = array_unique($myGameList);
        foreach ($myGameList as $fuid) {
            if ($gid != 3) {
                $table = otable::gift($fuid);
                $key = okeys::userSendFri($uid, $fuid, $gid);
                $cacheList[$key] = 1;
                $sql = " INSERT INTO {$table} VALUES (NULL,$fuid, $gid, 2, 0 , $nows, $exp,$uid,NULL)";
                $insertRs = oo::commonOprDb('usergift')->query($sql);
                oo::commonOprModel('Workerman')->push($fuid,ocmd::$redPoint,['type'=>5]);
                oo::commonOprModel('push')->pushNews($fuid, 'push.title.gift', 'push.content.gift', [$uidInfo['nick']],'gift');
                foreach ($cacheList as $keys=>$row){
                    oo::commonOprRedis('common')->setex($keys,$row, oo::todayDeadline());
                }
                if (!$insertRs) {
                    oo::logs()->debug3($sql, 'addUserGift.log');
                    return false;
                }
            }

        }

        // 任务系统 统计赠送好友筹码次数
        $data['code']  = 1;
        $data['total'] = $GameListCount;
        $data['money_num'] = isset($money_num) ? intval($money_num) : 0;
        $data['spins_num'] = isset($spins_num) ? intval($spins_num) : 0;
        $data['friend_list'] = oo::commonOprModel('friend')->getList($uid);
		
		//赠送情况统计
		if($gid == 1){
			if(!isset($money_num)){
				$num  = oo::commonOprModel('readconfig')->getCon('FriendProp','money');
			}else{
				$num = $money_num;
			}
		}else{
			if(!isset($spins_num)){
				$num = oo::commonOprModel('readconfig')->getCon('FriendProp','spins');
			}else{
				$num = $spins_num;
			}
		}
        oo::commonOprModel('statistics')->giveSta($gid==1?'money':'spins','Send',$uid,$GameListCount * $num);
        
        //一键赠送 人数统计
        oo::commonOprModel('statistics')->givesSta($gid==1?'money':'spins','Send',$uid);
		
        return $data;
    }

    /**
     * 领取卡片
     * YANG丶 2019年5月17日
     * $uid 当前用户uid $fuid 领取好友uid
     */
    public function FriendReceiveCard($uid,$fuid){
        if (empty($uid)  || empty($fuid)) {
            $data = ['code'=>-1,'msg'=>'参数错误','data'=>['card'=>[]]];
            return $data;
        }
        $key = okeys::userGiftList($uid);
        $list = oo::commonOprRedis('common')->lGetRange($key, 0, -1);
        if(count($list) > 0)
        {
            foreach ($list as  $v){
                $tempCardArr = json_decode($v,true);
                if($fuid == $tempCardArr['fromId']){
                    //要领取了
                    $cgid = $tempCardArr['cgid'];
                    $pos = $tempCardArr['pos'];
                    $cardInfo = otable::cardinfo_config();
                    $sql = " SELECT * FROM {$cardInfo} WHERE cgid={$cgid} AND ciid={$pos}";
                    $cardInfo = oo::commonOprDb('cardinfo')->getOne($sql, MYSQLI_ASSOC);
                    $flag = false;
                    $cards = oo::commonOprModel('card')->getUserCardInfo($uid);
                    $userCard = [];
                    $totalCardType = [];
                    foreach ($cards['ciid'] as $k=>$c){
                        $userCard[] = $k;
                        $totalCardType[] = $k;
                    }
                    if(!in_array($cardInfo['ciid'],$totalCardType)){
                        $totalCardType[] = $cardInfo['ciid'];
                        $flag = true;
                        oo::commonOprModel('member')->optProperty($uid,array('star'=>$cardInfo['ci_star_rank']),'+',32,'获取新卡片星星');
                    }
                    $res = oo::commonOprModel('card')->updateFriendsCardQuantity($uid,$tempCardArr['pos'],1);
                    if($res['code'] >=1){
                        //删掉队列里面这个key
                        oo::commonOprRedis('common')->lRemove($key, $v, $count=0);
                        $list = oo::commonOprRedis('common')->lGetRange($key, 0, -1);
                        $num = 0;  //当前用户剩余待领取卡片数量
                        foreach ($list as  $v){
                            $pending_card  = json_decode($v,true);
                            if($pending_card['fromId'] == $fuid){
                                $num ++;
                            }
                        }
                        $newCard = oo::commonOprModel('card')->getInfo($uid);
                        $receive[] = [
                            'group'=>$cardInfo['cgid'],
                            'card'=>$cardInfo['cgposition'],
                            'isNew'=>$flag
                        ];
                      	oo::logs()->debug4(['cardId'=>$cardInfo['ciid'],'cardGroup'=>$cardInfo['cgid'],'cardName'=>$cardInfo['ci_name'],'time'=>date('Y-m-d H:i'),'from'=>'firend-'.$fuid],$uid.'.log','cardlog/');
                        $cardReward = ['spins'=>0,'coins'=>0];//卡片奖励
                        $cardGroupReward = ['spins'=>0,'coins'=>0];//卡组奖励
                        $data = ['code'=>1,'msg'=>'领取成功','data'=>['receive'=>$receive,'card'=>$newCard,'cardReward'=>$cardReward,'cardGroupReward'=>$cardGroupReward,'pendingCard'=>$num]];
                    }
                    break;
                }else{
                    $data = ['code'=>-1,'msg'=>'没有该好友待领卡片数据','data'=>['card'=>[]]];
                }
            }
        }else{
            $data = ['code'=>-1,'msg'=>'没有该好友待领卡片数据','data'=>['card'=>[]]];
        }
        return $data;
    }

    /**
     *    检查当天是否有赠送过
     */
    public function checkSendPropToFri($uid = 0, $fuid = 0, $gid = 0)
    {
        $key = okeys::userSendFri($uid, $fuid, $gid);
        $flag = oo::commonOprRedis('common')->get($key);

        if(!$flag){
            $today = strtotime(date("Y-m-d"), time()); //当天开始时间戳
            $end = $today + 60 * 60 * 24; //当天结束时间戳
            $table = otable::gift($fuid);
            $sql = "SELECT * FROM " . $table . " WHERE  uid =" .$fuid . "  AND gid= " . $gid . " AND fid = " . $uid . "  AND gtime>={$today} AND gtime <= " . $end;
            $usergiftList = oo::commonOprDb('usergift')->getOne($sql, MYSQLI_ASSOC); //
            $flag = ($usergiftList)?1:0;
        }

        return $flag ? 1 : 0;
    }

    /**
     *    检查当天是否有领取过
     * uid 自己的id fuid 好友赠送的id  gid
     * 返回uid未领取的id //2020-1-16 owen 追加参数fuid ,单人检索单人
     */
    public function checkReceive($uid = 0, $gid = 0,$fuid = 0)
    {
        //先查出所有未过期的礼物列表
        $table = otable::gift($uid);
        $nows = time();
        if($fuid != 0){
            $sql = "SELECT * FROM " . $table . " WHERE  uid =" . $uid . "  AND gid= " . $gid . " AND fid = " . $fuid . " AND expire >= " . $nows . " ORDER BY gtime DESC,id DESC";
        }else{
            $sql = "SELECT * FROM " . $table . " WHERE  uid =" . $uid . "  AND gid= " . $gid . " AND expire >= " . $nows . " ORDER BY gtime DESC,id DESC";
        }
        $usergiftList = oo::commonOprDb('usergift')->getAll($sql, MYSQLI_ASSOC); //

        // 找出当天有领取的id
        $tempReceiveFid = [];
        $tempFid = [];
        $temp_arr = [];

        $today = strtotime(date("Y-m-d"), time()); //当天开始时间戳
        $end = $today + 60 * 60 * 24; //当天结束时间戳

        foreach ($usergiftList as $key => $val) {
            if (!empty($val['receive_time']) && $val['is_receive'] == 1) {
                //说明是已经领取了  然后在看是不是当天领取的
                if ($val['receive_time'] > $today && $val['receive_time'] < $end) {
                    //push当天领取的uid
                    array_push($tempReceiveFid, $val['fid']);
                }
            }
            if (!in_array($val['fid'], $tempFid)) {
                array_push($tempFid, $val['fid']);
                array_push($temp_arr, $val['id']);

            }
        }

        $result = [];

        foreach ($tempFid as $k => $v) {
            if (!in_array($v, $tempReceiveFid)) {
                $result[$k]['fuid'] = $v;
                $result[$k]['id'] = $temp_arr[$k];
            }
        }

        return $result;

    }

    /**
     *    批量查看是否可以领取
     * @param 返回可领取好友list
     */
    public function checkReceivePropMult($uid = 0, $fuidlist = [])
    {
        $keyArr = [];
        foreach ($fuidlist as $fuid) {
            for ($i = 1; $i < 4; $i++) {
                $tempKey = okeys::userSendFri($fuid, $uid, $i);
                array_push($keyArr, $tempKey);
            }
        }
        $list = oo::commonOprRedis('common')->getMultiple($keyArr);
		
        $sendUidList = [];//已赠送的好友uid  体力 金币 卡片三种情况
        $tempList = [];
        foreach ($list as $key => $value) {
            if ($value) {
                array_push($tempList, explode(':', $keyArr[$key]));
            }
        }

        if(!empty($tempList)){
            foreach ($tempList as $key => $val) {
                // 类型[1 2 3]  =》 已经赠送的好友id
                $sendUidList[$val[4]][] = substr($tempList[$key][2], 0, -1);
            }
        }

        $sendUidList[1] = empty($sendUidList[1])?[]:$sendUidList[1];
        $sendUidList[2] = empty($sendUidList[2])?[]:$sendUidList[2];
        $sendUidList[3] = empty($sendUidList[3])?[]:$sendUidList[3];
        return $sendUidList;
    }


    /**
     *    批量查看是否已经赠送过筹码
     * @param 返回已经发送好友list
     */
    public function checkSendPropToFriMult($uid = 0, $fuidlist = [])
    {
        $keyArr = [];
        foreach ($fuidlist as $fuid) {
            for ($i = 1; $i < 4; $i++) {
                $tempKey = okeys::userSendFri($uid, $fuid, $i);
                array_push($keyArr, $tempKey);
            }
        }
        $list = oo::commonOprRedis('common')->getMultiple($keyArr);


        $sendUidList = [];//已赠送的好友uid  体力 金币 卡片三种情况
        $tempList = [];
        foreach ($list as $key => $value) {
            if ($value) {
                array_push($tempList, explode(':', $keyArr[$key]));
            }
        }

        foreach ($tempList as $key => $val) {
            // 类型[1 2 3]  =》 已经赠送的好友id
            $sendUidList[$val[4]][] = substr($tempList[$key][3], 0, -1);
        }

        $sendUidList[1] = empty($sendUidList[1])?[]:$sendUidList[1];
        $sendUidList[2] = empty($sendUidList[2])?[]:$sendUidList[2];

        // 查庫
        $today = strtotime(date("Y-m-d"), time()); //当天开始时间戳
        $end = $today + 60 * 60 * 24; //当天结束时间戳
        foreach ($fuidlist as $row){
            if(!in_array($row,$sendUidList[1])){
                $table = otable::gift($row);
                $sql = "SELECT * FROM " . $table . " WHERE  uid =" .$row . "  AND gid= " . 1 . " AND fid = " . $uid . "  AND gtime>={$today} AND gtime <= " . $end;
                $usergiftList = oo::commonOprDb('usergift')->getOne($sql, MYSQLI_ASSOC); //
                if($usergiftList)
                    array_push($sendUidList[1],$row);
            }
        }
        foreach ($fuidlist as $row){
            if(!in_array($row,$sendUidList[2])){
                $table = otable::gift($row);
                $sql = "SELECT * FROM " . $table . " WHERE  uid =" .$row . "  AND gid= " . 2 . " AND fid = " . $uid . "  AND gtime>={$today} AND gtime <= " . $end;
                $usergiftList = oo::commonOprDb('usergift')->getOne($sql, MYSQLI_ASSOC); //
                if($usergiftList)
                    array_push($sendUidList[2],$row);
            }
        }

        $sendUidList[1] = empty($sendUidList[1])?[]:$sendUidList[1];
        $sendUidList[2] = empty($sendUidList[2])?[]:$sendUidList[2];
        return $sendUidList;
    }

    // -----------------------------------------------------------------------------------------------------------------

    public function addUserFriend($uid,$toUid,$type = 'game'){
        $uidArr = [$uid,$toUid];
        $uidCurFriendList = [];
        foreach ($uidArr as $row){
            $friend = $this->getUserAllFriend($row,$type);
            if($row==$uid){
                $acUid = $toUid;
                $uidCurFriendList = $friend;
            }else{
                $acUid = $uid;
            }
            array_push($friend,$acUid);
            $friend = array_filter(array_unique($friend));
            $friend = implode(',',$friend);
            $tb = otable::userfriends($row);
            if($type == 'game'){
                $sql = " UPDATE {$tb} SET game_list='{$friend}' WHERE uid = {$row} LIMIT 1 ";
            }else if($type == 'fb'){
                $sql = " UPDATE {$tb} SET poker='{$friend}' WHERE uid = {$row} LIMIT 1 ";
            }
            oo::commonOprDb('userfriends')->query($sql);
            oo::commonOprRedis('userinfo')->delete(okeys::userfriends($row,$type));
            oo::commonOprRedis('userinfo')->delete(okeys::userfriends($row,'all'));
            oo::commonOprRedis('userinfo')->delete(okeys::userIndexFriends($row));
//            oo::commonOprRedis('Usercache')->zAdd(okeys::Landing("USERFRIENDS", $row),time(),$uid);
        }
        oo::commonOprModel('ta')->setEventData($uid,'user_set',['friend_num'=>count($this->getUserAllFriend($uid))]);
        return [$type=>$uidCurFriendList];
    }

    public function getUserAllFriend($uid,$type = 'all'){
        $friends = oo::commonOprRedis('userinfo')->get(okeys::userfriends($uid,$type));
        if(!empty($friends)){
            $friends = json_decode($friends,true);
        }else{
            $this->getUserFriends($uid,$temp);
            $friends = [];
            if($type == 'game' || $type == 'all'){
                $gameList = explode(',',$temp['game_list']);
                foreach ($gameList as $row){
                    $row != $uid && $friends[] = $row;
                }
            }
            if($type == 'fb' || $type == 'all'){
                $poker= explode(',',$temp['poker']);
                foreach ($poker as $row){
                    $row != $uid && $friends[] = $row;
                }
            }
            $friends = array_unique(array_filter($friends));
            sort($friends);
            oo::commonOprRedis('userinfo')->setex(okeys::userfriends($uid,$type),json_encode($friends),oo::redisRandomExpire(7*24*60*60));
        }
        foreach ($friends as $key=>$row){
            if($row == $uid){
                unset($friends[$key]);
            }
        }
        return array_values($friends);
    }

    public function applyFriend($uid,$toUid){
        // 判断是否为好友
        if($uid == $toUid){
            return false;
        }
        $friends = $this->getUserAllFriend($uid);
        if(in_array($toUid,$friends)){
            return ['code'=>-2,'msg'=>'Already your friend'];
        }

        if(count($this->getUserAllFriend($uid,'game'))>=200){
            return ['code'=>-4,'msg'=>'Already your friend'];
        }

        oo::commonOprRedis('common')->hSet(okeys::applyFriend($uid),$toUid,time());
        oo::commonOprRedis('common')->expire(okeys::applyFriend($uid),86400*3);

        $tb = otable::friendLog();
        $sql = "SELECT * FROM {$tb} WHERE uid={$uid} AND touid={$toUid}  AND status=0";
        $ret = oo::commonOprDb('userfriendlog')->getOne($sql,MYSQLI_ASSOC);
        if(!empty($ret)){
            return ['code'=>-3,'msg'=>'apply under review'];
        }
        $time = date('Y-m-d H:i:s');
        $sql = "INSERT INTO {$tb} (uid, touid, created_at) VALUES({$uid},{$toUid},'{$time}')";
        $ret = oo::commonOprDb('userfriendlog')->query($sql);
        if(!$ret){
            return ['code'=>-1,'msg'=>'INSERT ERROR'];
        }
        $arr = ['uid','nick','sex','s_picture','signature','u_flag','vip','avatar'];
        $userInfo = oo::commonOprModel('member')->getUserInfo($uid,$arr);
        $userInfo['toUid'] = $uid;
        oo::commonOprModel('Workerman')->push($toUid,APPLY_FRIEND_MSG,$userInfo);

        oo::commonOprModel('Workerman')->push($toUid,ocmd::$redPoint,['type'=>4,'data'=>oo::commonOprModel('message')->getApplyFriendMessageData($toUid,$uid)]);

        return ['code'=>1,'msg'=>'apply success'];
    }

    public function reviewFriend($uid,$toUid,$status){
        $tb = otable::friendLog();
        $sql = "SELECT * FROM {$tb} WHERE uid={$toUid} AND touid={$uid} AND status=0";
        $ret = oo::commonOprDb('userfriendlog')->getOne($sql,MYSQLI_ASSOC);
        if(empty($ret)){
            return ['code'=>-3,'msg'=>'review error'];
        }

        if($status == 1){
            $sql = "UPDATE {$tb} SET `status`=1 WHERE uid = {$toUid} AND touid = {$uid} ";
            $ret = oo::commonOprDb('userfriendlog')->query($sql);
            if($ret){
                $uidtb = otable::userfriends($uid);
                $sql = "SELECT * FROM {$uidtb} WHERE uid={$uid}";
                $ret = oo::commonOprDb('userfriends')->getOne($sql,MYSQLI_ASSOC);
                $uidFriend = explode(',',$ret['game_list']);
                array_push($uidFriend,$toUid);
                $uidFriend = array_unique($uidFriend);
                if(count($uidFriend)>=200){
                    return ['code'=>-4,'msg'=>'好友超出上限'];
                }
                $uidFriend = implode(',',$uidFriend);
                $uidFriend = trim($uidFriend,',');

                $toUidtb = otable::userfriends($toUid);
                $sql = "SELECT * FROM {$toUidtb} WHERE uid={$toUid}";
                $ret = oo::commonOprDb('userfriends')->getOne($sql,MYSQLI_ASSOC);
                $toUidFriend = explode(',',$ret['game_list']);
                array_push($toUidFriend,$uid);
                $toUidFriend = array_unique($toUidFriend);
                if(count($toUidFriend)>=200){
                    return ['code'=>-5,'msg'=>'对方好友超出上限'];
                }
                $toUidFriend = implode(',',$toUidFriend);
                $toUidFriend = trim($toUidFriend,',');

                $uidSql = "UPDATE {$uidtb} SET `game_list`='{$uidFriend}' WHERE uid = {$uid}";
                oo::commonOprDb('userfriends')->query($uidSql);
                $toUidSql = "UPDATE {$toUidtb} SET `game_list`='{$toUidFriend}' WHERE uid = {$toUid}";
                oo::commonOprDb('userfriends')->query($toUidSql);

                $userInfo = oo::commonOprModel('member')->getUserInfo($uid);
                oo::commonOprModel('Workerman')->push($toUid,APPLY_FRIEND_REVIEW,$userInfo);
                oo::commonOprRedis('userinfo')->delete([
                    okeys::userfriends($uid,'game'),
                    okeys::userfriends($uid,'all'),
                    okeys::userfriends($toUid,'game'),
                    okeys::userfriends($toUid,'all')
                ]);
            }
        }else if($status == 2){
            $sql = "UPDATE {$tb} SET `status`=2 WHERE uid = {$toUid} AND touid = {$uid} ";
            oo::commonOprDb('userfriendlog')->query($sql);
        }

        return ['code'=>1,'msg'=>'review success'];
    }

    public function deleteFriend($uid,$toUid){
        $arr = [$uid,$toUid];
        $list = [];
        foreach ($arr as $key=>$row){
            $target = ($row==$uid)?$toUid:$uid;
            $ftb = otable::userfriends($row);
            $sql = "SELECT * FROM {$ftb} WHERE uid={$row}";
            $ret = oo::commonOprDb('userfriends')->getOne($sql,MYSQLI_ASSOC);
            $set = "";
            $sqlKey = ['game_list','poker'];
            foreach ($sqlKey as $k){
                if(strpos($ret[$k],(string)$target) === false){
                    continue;
                }
                $friend = explode(',',$ret[$k]);
                foreach ($friend as $x=>$y){
                    if($y== $target){
                        unset($friend[$x]);
                    }
                }
                $newList = trim(implode(',',array_unique($friend)),',');
                $list[$k] = $newList;
                $set .= "`{$k}`='{$newList}',";
            }
            $set = trim($set,',');
            oo::commonOprRedis('userinfo')->delete([
                okeys::userfriends($row,'fb'),
                okeys::userfriends($row,'all'),
                okeys::userfriends($row,'game'),
                okeys::userIndexFriends($row)
            ]);
            if(empty($set)){
                continue;
            }
            $sql = "UPDATE {$ftb} SET {$set} WHERE uid = {$row}";
            oo::commonOprDb('userfriends')->query($sql);
        }
        return ['code'=>1,'msg'=>'delete success',$list];
    }
  
    public function recommendFriend($uid){
        $friends = $this->getUserAllFriend($uid);
        if(empty($friends)){
            return ['code'=>1,'data'=>[]];
        }

        $IntersectionFriends = [];
        foreach ($friends as $row){
            $temp = $this->getUserAllFriend($row);
            foreach ($temp as $f){
                if(!in_array($f,$friends)){
                    $IntersectionFriends[] = $f;
                }
            }
        }
        
        $IntersectionFriends = array_unique($IntersectionFriends);
        unset($IntersectionFriends[array_search($uid,$IntersectionFriends)]);
        /**
         * 好友申请中的剔除
         */
        $applyFriend = oo::commonOprRedis('common')->hGetAll(okeys::applyFriend($uid));
        foreach ($applyFriend as $key=>$row){
            if(time() - $row < 4*60*60){
                unset($IntersectionFriends[array_search($key,$IntersectionFriends)]);
            }else{
                oo::commonOprRedis('common')->hDel(okeys::applyFriend($uid),$key);
            }
        }

        /**
         * 已经推荐过的剔除
         */
        $applyFriend = oo::commonOprRedis('common')->hGetAll(okeys::recommendFriend($uid));
        foreach ($applyFriend as $key=>$row){
            if(time() - $row < 10*60){
                unset($IntersectionFriends[array_search($key,$IntersectionFriends)]);
            }else{
                oo::commonOprRedis('common')->hDel(okeys::applyFriend($uid),$key);
            }
        }

        if(empty($IntersectionFriends)){
            return ['code'=>1,'data'=>[]];
        }

        shuffle($IntersectionFriends);

        $uidList = [];
        $maxRecommend = 9;
        foreach ($IntersectionFriends as $key=>$row){
            $memberInfo = oo::commonOprModel('member')->getUserInfo($row);
            $propertyInfo = oo::commonOprModel('member')->getUserAssetsInfo($row);
            if(empty($memberInfo) || empty($propertyInfo) || $memberInfo['isFb'] == 0){
                continue;
            }
            $temp         = $memberInfo;
            $temp['star'] = $propertyInfo['star'];
            $uidList[]    = $temp;
            if(count($uidList) >= $maxRecommend){
                break;
            }
        }

        if(count($uidList) < $maxRecommend){
            $IntersectionFriends = implode(',',$IntersectionFriends);
            $tb = otable::userinfo();
            $sql = "SELECT * FROM {$tb} WHERE uid IN ({$IntersectionFriends}) order by lasttime DESC LIMIT {$maxRecommend}";
            $ret = oo::commonOprDb('userinfo')->getAll($sql,MYSQLI_ASSOC);
            foreach ($ret as $key=>$row){
                $propertyInfo = oo::commonOprModel('member')->getUserAssetsInfo($row['uid']);
                if(empty($propertyInfo)){
                    continue;
                }
                $uidList[] = [
                    'star'  => $propertyInfo['star'],
                    'uid'   => $row['uid'],
                    'nick'  => $row['nick'],
                    's_picture'=> $row['s_picture'],
                    'u_flag'   => $row['u_flag'],
                    'signature'=> $row['signature'],
                    'vip'      => $row['vip'],
                    'vipLv'    => $row['vipLv'],
                    'avatar'   => intval($row['avatar']),
                ];
                if(count($uidList) >= $maxRecommend){
                    break;
                }
            }
        }

        $time = time();
        foreach ($uidList as $key=>$row){
            oo::commonOprRedis('common')->hSet(okeys::recommendFriend($uid),$row['uid'],$time);
        }

        $recommendCount = $maxRecommend - count($uidList);
        if($recommendCount > 0){
            $recommendFriend = oo::commonOprRedis('common')->hGetAll(okeys::recommendFriend($uid));
            asort($recommendFriend);
            foreach ($recommendFriend as $key=>$row){
                oo::commonOprRedis('common')->hDel(okeys::recommendFriend($uid),$key);
                $recommendCount = $recommendCount -1;
                if($recommendCount <= 0){
                    break;
                }
            }
        }

        oo::commonOprRedis('common')->expire(okeys::applyFriend($uid),3*24*60*60);
        oo::commonOprRedis('common')->expire(okeys::recommendFriend($uid),3*24*60*60);
        return ['code'=>1,'data'=>$uidList];
    }


    /**
     * 获取该用户的好友列表
     * @param $srcUid
     * @return mixed   礼物状态类型：领取 赠送 已赠送  每天每用户可以赠送一次 每晚00.00重置状态
     */
    public function getList($srcUid)
    {
        $data = array();
        if (!$srcUid) {
            return $data;
        }

        $userarr = array();//存储返回的值
        $game_listArray = $this->getUserAllFriend($srcUid);
        if (empty($game_listArray)) {
            return array('flist' => array());
        }

        $uidList = array();
        foreach ($game_listArray as $value) {
            $temp = intval($value);
            if (empty($temp) || $temp <= 0) continue;
            if ($temp == $srcUid) continue;
            array_push($uidList, $temp);
        }

        $infoList = array();
        //获取玩家当天赠送的玩家
        $todaySendMoneyUserList = $this->checkSendPropToFriMult($srcUid, $uidList);
        //可以领取的uid 状态改为2
        $UserReceivePropList = $this->checkReceivePropMult($srcUid, $uidList);

        $key = okeys::userGiftList($srcUid);
        $list = oo::commonOprRedis('common')->lGetRange($key, 0, -1);
        //可领取卡片的用户uid
        $cardCollection = [];
        $cardNum = [];
        foreach ($list as $v) {
            $tempCardArr = json_decode($v, true);
            array_push($cardCollection, $tempCardArr['fromId']);
            $cardNum[$tempCardArr['fromId']] +=  intval($tempCardArr['num']);
        }

        $userinfo = array();
        $ret = oo::commonOprModel('member')->getUserInfoMulti(array('keylist' => $uidList), $userinfo);
        $fbList = $this->getUserAllFriend($srcUid,'fb');
        if ($ret == 1) {
            usort($userinfo, 'TimeCmp');
            $uidList = array();
            $money = oo::commonOprModel('readconfig')->getCon('FriendProp','money');
            $spins = oo::commonOprModel('readconfig')->getCon('FriendProp','spins');

            $accumulationMoney = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMax(1),$srcUid));
            $accumulationSpins = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMax(2),$srcUid));
            $accumulationMoneyFlag  = true;
            $accumulationSpinsFlag = true;

            if($accumulationMoney >= $money*200){
                $accumulationMoneyFlag = false;
            }
            if($accumulationSpins >= $spins*200){
                $accumulationSpinsFlag = false;
            }

            $moneyReceiveUserList = [];
            $checkReceiveMoney = oo::commonOprModel('friend')->checkReceive($srcUid,1);
            if(!empty($checkReceiveMoney)){
                $moneyReceiveUserList = array_column($checkReceiveMoney,'fuid');
            }
            $spinsReceiveUserList = [];
            $checkReceiveSpins = oo::commonOprModel('friend')->checkReceive($srcUid,2);
            if(!empty($checkReceiveSpins)){
                $spinsReceiveUserList = array_column($checkReceiveSpins,'fuid');
            }

            $flag = false;
            foreach ($userinfo as $v) {
                $uid = $v['uid'];
                $img = $v['s_picture'];
                if (strpos($img, 'http') === false) {
                    $img = intval($img);
                    $img = empty($img) ? 1 : $img;
                }
                $infoList[$uid]['uid'] = $uid;
                $infoList[$uid]['siteid'] = (string)$v['siteuid'];
                $infoList[$uid]['nick'] = empty($v['nick']) ? '' : strval($v['nick']);
                $infoList[$uid]['s_picture'] = $img;
                $infoList[$uid]['u_flag'] = $v['u_flag'];
                $infoList[$uid]['sex'] = ($v['sex'] == 'f') ? 'f' : 'm';
                //获取财产信息
                $userProperty = oo::commonOprModel('member')->getUserAssetsInfo($uid);
                if ($userProperty) {
                    $infoList[$uid]['money'] = $userProperty['money'];
                    $infoList[$uid]['star'] = $userProperty['star'];
                    $infoList[$uid]['levelId'] = $userProperty['levelId'];
                    $infoList[$uid]['signature'] = $userProperty['signature'];
                }

                //查询是否属于FB
                $infoArr = oo::commonOprModel('member')->getAccount($v['siteuid']);
                if (!empty($infoArr) && $infoArr['uid'] == $uid) {
                    $infoList[$uid]['isFb'] = 1;
                    $infoList[$uid]['fbId'] = $v['siteuid'];
                    if(in_array($uid,$fbList)){
                        $infoList[$uid]['isFbFriend'] = 1;
                    }else{
                        $infoList[$uid]['isFbFriend'] = 0;
                    }
                } else {
                    $infoList[$uid]['isFb'] = 0;
                    $infoList[$uid]['isFbFriend'] = 0;
                }

                if($flag && (in_array($uid, $todaySendMoneyUserList[1])) && (in_array($uid, $UserReceivePropList[1]) && $accumulationMoneyFlag && in_array($uid,$moneyReceiveUserList)) ){
                    $infoList[$uid]['is_send_Coin'] = 3;
                }else if (in_array($uid, $UserReceivePropList[1]) && $accumulationMoneyFlag && in_array($uid,$moneyReceiveUserList)) {
                    $infoList[$uid]['is_send_Coin'] = 2;
                } else if (in_array($uid, $todaySendMoneyUserList[1])) {
                    $infoList[$uid]['is_send_Coin'] = 0;
                } else {
                    $infoList[$uid]['is_send_Coin'] = 1;
                }

                if($flag && (in_array($uid, $todaySendMoneyUserList[2])) && (in_array($uid, $UserReceivePropList[2]) && $accumulationSpinsFlag && in_array($uid,$spinsReceiveUserList))){
                    $infoList[$uid]['is_send_Coin'] = 3;
                }elseif (in_array($uid, $UserReceivePropList[2]) && $accumulationSpinsFlag && in_array($uid,$spinsReceiveUserList)) {
                    $infoList[$uid]['is_send_Spin'] = 2;
                } else if (in_array($uid, $todaySendMoneyUserList[2])) {
                    $infoList[$uid]['is_send_Spin'] = 0;
                } else {
                    $infoList[$uid]['is_send_Spin'] = 1;
                }
                //0已赠送 1赠送 2领取
                if (in_array($uid, $cardCollection)) {
                    $infoList[$uid]['is_send_Card'] = 2;
                    $infoList[$uid]['card_num'] = intval($cardNum[$uid]);
                }else{
                    $infoList[$uid]['is_send_Card'] = 1;
                    $infoList[$uid]['card_num'] = 0;
                }

                $infoList[$uid]['coin_num'] = $money;
                $infoList[$uid]['spin_num'] = $spins;
                $infoList[$uid]['vip'] = $v['vip'];
                $infoList[$uid]['vipLv'] = $v['vipLv'];
                $infoList[$uid]['vipExpire'] = $v['vip_expire'];
                $infoList[$uid]['avatar'] = intval($v['avatar']);

                $uidList[] = $uid;
            }
        }else{
            $return = array_values($infoList);
            return array('flist' => $return);
        }

        foreach ($infoList as $v) {
            if (empty($v) || empty($v['siteid'])) continue;
            $ret = preg_match('/^[0-9A-Za-z]*$/', $v['siteid']);
            if ($ret <= 0) continue;
            array_push($userarr, $v);
        }
        usort($userarr, 'cmpThree');
        foreach ($userarr as $key => $value) {
            $code1 = mb_detect_encoding($value['nick']);
            $nick = @iconv($code1, "utf-8//IGNORE", $userarr[$key]['nick']);
            $userarr[$key]['nick'] = empty($nick) ? '' : strval($nick);
        }
        if (empty($userarr) && count($userarr) > 0) {
            return array('flist' => array());
        }

        return array('flist' => $userarr);
    }

    /**
     * 当天是否有礼物可领取
     * @param int $uid
     * @return bool
     */
    public function hasNewGiftReceive($uid) {
        $friends = self::getUserAllFriend($uid);
        $userCard = oo::commonOprModel('card')->getUserCardInfo($uid);
        $sended  = array_keys($userCard['sended_card']);
        if(!empty($sended)){
            return true;
        }
        $coinsMaxTimes = oo::commonOprModel('readconfig')->getCon('FriendProp','coinsMaxTimes');
        $spinsMaxTimes = oo::commonOprModel('readconfig')->getCon('FriendProp','spinsMaxTimes');
        $coinsCurTimes = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMaxTimes(1),$uid));
        $spinsCurTimes = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMaxTimes(2),$uid));
        $accumulationMoneyFlag = $coinsCurTimes >= $coinsMaxTimes ? false : true;
        $accumulationSpinsFlag = $spinsCurTimes >= $spinsMaxTimes ? false : true;

        foreach($friends as $row){
            //金币
            $isSend       = intval(oo::commonOprRedis('common')->get(okeys::SendGiftToday($uid,$row,1)));
            $isReceive    = intval(oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($row,$uid,1)));
            if($isReceive == 1 && $accumulationMoneyFlag){
                return true;
            }
            //体力
            $isSend = intval(oo::commonOprRedis('common')->get(okeys::SendGiftToday($uid,$row,2)));
            $isReceive = intval(oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($row,$uid,2)));
            if($isReceive == 1 && $accumulationSpinsFlag){
                return true;
            }
        }
        return false;
    }

    // --------------------------------------------------1.5.0--------------------------------------------------------//
    //0已赠送 1赠送 2领取
    //1金币，2体力
    public function getFriendAndGiftList($uid, $page = 0){
        $friendList = [];
        $friends = self::getUserAllFriend($uid);
        $userCard= oo::commonOprModel('card')->getUserCardInfo($uid);
        $sended  = array_keys($userCard['sended_card']);
        $coinsMaxTimes = oo::commonOprModel('readconfig')->getCon('FriendProp','coinsMaxTimes');
        $spinsMaxTimes = oo::commonOprModel('readconfig')->getCon('FriendProp','spinsMaxTimes');
        $coinsCurTimes = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMaxTimes(1),$uid));
        $spinsCurTimes = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMaxTimes(2),$uid));
        $accumulationMoneyFlag = $coinsCurTimes >= $coinsMaxTimes ? false : true;
        $accumulationSpinsFlag = $spinsCurTimes >= $spinsMaxTimes ? false : true;
        $i = 0;
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        $callbackTimeList = $friends ? $this->getListCallBackTime($uid, array_values($friends)) : [];
        $count = count($friends);
        $oFriends = $friends;
        if($page){
            $offset = 10;
            $friendNum = count($friends);
            $showFriend = $userInfoArr = [];
            for ($i=0;$i<ceil($friendNum/$offset);$i++){
                sort($friends);
                $showFriend = array_slice($friends, ($page - 1) * $offset, $offset);
                foreach ($showFriend as $key=>$row){
                    if(!empty($userInfoArr[$row])){
                        continue;
                    }
                    $userInfo = oo::commonOprModel('member')->getUserInfo($row);
                    if(empty($userInfo)){
                        $this->deleteFriend($uid,$row);
                        foreach ($friends as $k=>$u){
                            if($u == $row){
                                unset($friends[$k]);
                                unset($showFriend[$key]);
                                break;
                            }
                        }
                    }else{
                        $userInfoArr[$row] = $userInfo;
                    }
                }
                if(count($showFriend) == $offset){
                    break;
                }
            }
            $friends = array_values($showFriend) ?? [];
        }else{
            $userInfoArr = [];
            foreach ($friends as $fuid){
                $userInfo = oo::commonOprModel('member')->getUserInfo($fuid);
                if(empty($userInfo)){
                    $this->deleteFriend($uid,$fuid);
                    foreach ($friends as $k=>$u){
                        if($u == $fuid){
                            unset($friends[$k]);
                            break;
                        }
                    }
                }else{
                    $userInfoArr[$fuid] = $userInfo;
                }
            }
        }
        $myLevelId = oo::commonOprModel('member')->getUserLevelId($uid);
        $callbackConf = $this->callbackConf();
        $helpInfo = oo::commonOprModel('level')->getHelpRepairInfo($uid);
        $repaired = false;
        //当天不能帮好友修了
        if($helpInfo && isset($helpInfo['repair']['expire']) && $helpInfo['repair']['expire'] > time()){
            $repaired = true;
            $repaireArr = [];
        }else{
            $repaireArr = oo::commonOprModel('level')->getRepairInfoArr(array_values($friends));
        }
        $versionFlag = oo::compareVersion($version,'1.7.8');
        foreach ($friends as $row){
            if($row == $uid){
                continue;
            }
            $userInfo = $userInfoArr[$row];
            $lastCallbackTime =  !empty($callbackTimeList[$row]) ? $callbackTimeList[$row] : 0; 
            $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($row);
            $canCallback = $this->canCallback($userInfo, $assetsInfo['levelId'], $lastCallbackTime, $callbackConf);
            if($myLevelId < $assetsInfo['levelId'] || $repaired){
                $canRepair = 0;
            }else{
                if(isset($repaireArr[$row], $repaireArr[$row]['berepair'], $repaireArr[$row]['berepair']['expire'])){
                    $canRepair = $repaireArr[$row]['berepair']['expire'] > time() ? 0 : 1;
                }else{
                    $levelInfo = oo::commonOprModel('member')->getUserLevel($row);
                    $element = empty($levelInfo['element']) ? [] : $levelInfo['element'];
                    //有损坏的建筑才显示可维修
                    $canRepair = empty(array_filter(array_column($element, 'status'))) ? 0 : 1;
                }
            }
            $i = $row;
            $friendList[$i] = [
                'uid'             => $row,
                'siteid'          => $userInfo['siteuid'],
                'nick'            => $versionFlag ? $userInfo['nick'] : oo::commonOprModel('member')->getUserFirstName($userInfo['nick']),
                's_picture'       => $userInfo['s_picture'],
                'u_flag'          => $userInfo['u_flag'],
                'callback_expire' => !empty($callbackTimeList[$row]) ? $callbackTimeList[$row] : 0,
                'can_callback'    => $canCallback ? 1 : 0,
                'can_repair'      => $canRepair,
                'sex'             => $userInfo['sex'],
                'money'           => $assetsInfo['money'],
                'coins'           => $assetsInfo['money'],
                'star'            => $assetsInfo['star'],
                'levelId'         => $assetsInfo['levelId'],
                'signature'       => $userInfo['signature'],
                'isFb'            => $userInfo['isFb'],
                'isFbFriend'      => $userInfo['isFb']?1:0,
                'vip'             => $userInfo['vip'],
                'vipLv'           => $userInfo['vipLv'],
                'vipExpire'       => $userInfo['vip_expire'],
                'avatar'          => $userInfo['avatar'],
            ];
            if(in_array($row,$sended)){
                $cards = $userCard['sended_card'][$row];
                $friendList[$i]['is_send_Card'] = 2;
                $friendList[$i]['card_num']  = array_sum(array_values($cards));
                $friendList[$i]['card_data'] = $cards;
            }else{
                $friendList[$i]['is_send_Card'] = 1;
                $friendList[$i]['card_num'] = 0;
                $friendList[$i]['card_data'] = json_decode("{}");
            }
            /**
             * 金币
             */
            $isSend       = intval(oo::commonOprRedis('common')->get(okeys::SendGiftToday($uid,$row,1)));
            $isReceive    = intval(oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($row,$uid,1)));
            if($isReceive == 2 && !$isSend && $accumulationMoneyFlag){
                $friendList[$i]['is_send_Coin'] = 3;
            }else if($isReceive == 1 && $accumulationMoneyFlag){
                $friendList[$i]['is_send_Coin'] = 2;
            }else if($isSend){
                $friendList[$i]['is_send_Coin'] = 0;
            }else{
                $friendList[$i]['is_send_Coin'] = 1;
            }
            /**
             * 体力
             */
            $isSend = intval(oo::commonOprRedis('common')->get(okeys::SendGiftToday($uid,$row,2)));
            $isReceive = intval(oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($row,$uid,2)));
            if($isReceive == 2 && !$isSend && $accumulationSpinsFlag){
                $friendList[$i]['is_send_Spin'] = 3;
            }else if($isReceive == 1 && $accumulationSpinsFlag){
                $friendList[$i]['is_send_Spin'] = 2;
            }else if($isSend){
                $friendList[$i]['is_send_Spin'] = 0;
            }else{
                $friendList[$i]['is_send_Spin'] = 1;
            }
        }

        $sendsArr = [];
        $coinsCount = $spinsCount = $coins1Count = $spins1Count = 0;
        if(oo::compareVersion($version,'1.7.5')){
            foreach($oFriends as $row){
                if(isset($friendList[$row])){
                    if($friendList[$row]['is_send_Spin'] == 2){
                        $spinsCount++;
                    }
                    if($friendList[$row]['is_send_Spin'] == 1){
                        $spins1Count++;
                    }
                    if($friendList[$row]['is_send_Coin'] == 2){
                        $coinsCount++;
                    }
                    if($friendList[$row]['is_send_Coin'] == 1){
                        $coins1Count++;
                    }
                    if($friendList[$row]['card_num'] > 0){
                        $sendsArr[$row]['uid']       = $row;
                        $sendsArr[$row]['nick']      = $friendList[$row]['nick'];
                        $sendsArr[$row]['u_flag']    = $friendList[$row]['u_flag'];
                        $sendsArr[$row]['avatar']    = $friendList[$row]['avatar'];
                        $sendsArr[$row]['s_picture'] = $friendList[$row]['s_picture'];
                        $sendsArr[$row]['card_num']  = $friendList[$row]['card_num'];
                        $sendsArr[$row]['card_data'] = $friendList[$row]['card_data'];
                    }
                    continue;
                }

                $cards = isset($userCard['sended_card'][$row]) ? $userCard['sended_card'][$row] : [];
                if(in_array($row,$sended) && !empty($cards)){
                    $userInfo = oo::commonOprModel('member')->getUserInfo($row);
                    $sendsArr[$row]['uid']       = $row;
                    $sendsArr[$row]['nick']      = oo::commonOprModel('member')->getUserFirstName($userInfo['nick']);
                    $sendsArr[$row]['u_flag']    = $userInfo['u_flag'];
                    $sendsArr[$row]['avatar']    = $userInfo['avatar'];
                    $sendsArr[$row]['s_picture'] = $userInfo['s_picture'];
                    $sendsArr[$row]['card_num']  = array_sum(array_values($cards));
                    $sendsArr[$row]['card_data'] = $cards;
                }

                 //金币
                $isSend       = intval(oo::commonOprRedis('common')->get(okeys::SendGiftToday($uid,$row,1)));
                $isReceive    = intval(oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($row,$uid,1)));
                if($isReceive == 2 && !$isSend && $accumulationMoneyFlag){
                    //$sendsArr[$row]['is_send_Coin'] = 3;
                }else if($isReceive == 1 && $accumulationMoneyFlag){
                    $coinsCount++;
                }else if($isSend){
                    //$friendList[$i]['is_send_Coin'] = 0;
                }else{
                    $coins1Count++;
                }
                //体力
                $isSend = intval(oo::commonOprRedis('common')->get(okeys::SendGiftToday($uid,$row,2)));
                $isReceive = intval(oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($row,$uid,2)));
                if($isReceive == 2 && !$isSend && $accumulationMoneyFlag){
                    //$sendsArr[$row]['is_send_Spin'] = 3;
                }else if($isReceive == 1 && $accumulationSpinsFlag){
                    $spinsCount++;
                }else if($isSend){
                    //$friendList[$i]['is_send_Spin'] = 0;
                }else{
                    $spins1Count++;
                }
            }
        }
        $data = [
            'list'  =>array_values($friendList),
            'reward'=>[
                'coins' => self::getUserFriendGiftCoins($uid),
                'spins' => oo::commonOprModel('readconfig')->getCon('FriendProp','spins'),
                'card'  => 1,
            ],
            'is_send_list'     => array_values($sendsArr),
            'canGet_coins_num' => $coinsCount,
            'canGet_spins_num' => $spinsCount,
            'canSend_coins_num' => $coins1Count,
            'canSend_spins_num' => $spins1Count,
            'callback_reward'  => $callbackConf['reward'],
            'limit'     =>[
                'spins' =>[
                    'max'  =>$spinsMaxTimes,
                    'times'=>$spinsCurTimes
                ],
                'coins' =>[
                    'max'  =>$coinsMaxTimes,
                    'times'=>$coinsCurTimes
                ],
                'maxFriendNum' => 200,
                'refreshTime'  => 24
            ]
        ];
        if(!empty($page)){
            $data['page'] = $page;
            $data['total'] = $count;
        }
        return oo::response(1,$data,"",true);
    }

    /**
     * 单个玩家赠送礼物   暂定每天每人只能送一次  每次1个体力 50K金币  系统给
     * @param int $uid
     * @param int $toUid
     * @param int $gid 1金币 2体力
     * @return array|bool
     * Created by: Owen
     * Created on: 2020/3/30 15:03
     */
    public function sendGift($uid,$toUid,$gid){
        $cacheKey = okeys::SendGiftToday($uid,$toUid,$gid);
        $cache    = oo::commonOprRedis('common')->get($cacheKey);
        if($cache){
            return oo::response(-2,[],"已赠送礼物");
        }
        if($gid == 1){
            $num = self::getUserFriendGiftCoins($toUid);
        }else{
            $num = oo::commonOprModel('readconfig')->getCon('FriendProp','spins');
        }
        oo::commonOprRedis('common')->setex($cacheKey,1, 24*60*60);
        oo::commonOprRedis('common')->setex(okeys::SendEdGiftToday($uid,$toUid,$gid),1, 7*24*60*60);
        oo::commonOprModel('Workerman')->push($toUid,ocmd::$redPoint,['type'=>5]);
        $uidInfo = oo::commonOprModel('member')->getUserInfo($uid);
        oo::commonOprModel('push')->pushNews($toUid, 'push.title.gift', 'push.content.gift', [$uidInfo['nick']],'gift');
        //召回活动-赠送金币,体力
        $tid = $gid==1?10:9;
        oo::commonOprModel('callback')->doTask($uid, $tid, 1);
        //赠送情况统计
        oo::commonOprModel('statistics')->giveSta($gid==1?'money':'spins','Send',$uid,$num);
        $isSend       = oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($toUid,$uid,$gid));
        $data['gid'] = $gid;
        $data['num'] = $num;
        $data['state'] = ($isSend==1)?2:0;
        if($gid == 1){
            oo::commonOprModel('ta')->setEventData($uid,"coin_send",["coin_send_object_user"=>$toUid,"coin_send_num"=>$num]);
        }else if($gid == 2){
            oo::commonOprModel('ta')->setEventData($uid,"spin_send",["spin_send_object_user"=>$toUid,"spin_send_num"=>$num]);
        }
        return oo::response(1,$data,"赠送成功");
    }

    /**
     * 领取好友礼物
     * @param $uid
     * @param $toUid
     * @param $gid
     * @return string
     * Created by: Owen
     * Created on: 2020/3/30 15:19
     */
    public function receiveGift($uid,$toUid,$gid){
        $cacheKey = okeys::SendEdGiftToday($toUid,$uid,$gid);
        $cache    = oo::commonOprRedis('common')->get($cacheKey);
        if(empty($cache)){
            return oo::response(-2,[],"无礼物赠送记录");
        }
        if($cache == 2){
            return oo::response(-3,[],"礼物已领取");
        }
        oo::commonOprRedis('common')->setex($cacheKey,2,oo::todayDeadline());
        if($gid == 1){
            $money_num = $num = self::getUserFriendGiftCoins($uid);
            $type= 'money';
        }else if($gid == 2){
            $spins_num = $num = intval(oo::commonOprModel('readconfig')->getCon('FriendProp','spins'));
            $type= 'spins';
        }
        $MaxTimes = oo::commonOprModel('readconfig')->getCon('FriendProp','coinsMaxTimes');
        $CurTimes = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMaxTimes($gid),$uid));
        if($CurTimes >= $MaxTimes){
            return oo::response(-3,[],"领取礼物次数已达最大限制");
        }
        oo::commonOprModel('member')->optProperty($uid, [$type=>$num], '+',50, '好友赠送金币');
        oo::commonOprRedis('common')->hIncrBy(okeys::friendGiftMax($gid),$uid,$num);
        oo::commonOprRedis('common')->hIncrBy(okeys::friendGiftMaxTimes($gid),$uid,1);
        $isSend            = oo::commonOprRedis('common')->get(okeys::SendGiftToday($uid,$toUid,$gid));
        $data['money_num'] = $money_num ?? 0;
        $data['spins_num'] = $spins_num ?? 0;
        $flag = ($isSend)?0:3;
        $data['state'] = $flag;

        /**
         * ta 事件--卡组完成
         */
        if($gid == 1){
            oo::commonOprModel('ta')->setEventData($uid,"coin_accept",["coin_accept_from_user"=>$toUid,"coin_accept_num"=>$num]);
        }else if($gid == 2){
            oo::commonOprModel('ta')->setEventData($uid,"spin_accept",["spin_accept_from_user"=>$toUid,"spin_accept_num"=>$num]);
        }


        return oo::response(1,$data,"领取成功");
    }

    /**
     * 一键领取并赠送
     * @param $uid
     * @param $gid
     * @return string
     * Created by: Owen
     * Created on: 2020/3/30 15:53
     */
    public function sendAndReceiveGifts($uid,$gid){
        $friends = self::getUserAllFriend($uid);
        if($gid == 1){
            $num = self::getUserFriendGiftCoins($uid);
            $MaxTimes = oo::commonOprModel('readconfig')->getCon('FriendProp','coinsMaxTimes');
            $type= 'money';
            $tips= '金币';
        }else if($gid == 2){
            $num = oo::commonOprModel('readconfig')->getCon('FriendProp','spins');
            $MaxTimes = oo::commonOprModel('readconfig')->getCon('FriendProp','spinsMaxTimes');
            $type= 'spins';
            $tips= '体力';
        }
        $total      = 0;
        $CurTimes = intval(oo::commonOprRedis('common')->hGet(okeys::friendGiftMaxTimes($gid),$uid));
        $uidInfo    = oo::commonOprModel('member')->getUserInfo($uid);
        if($gid == 2){
            $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $curSpins   = intval($assetsInfo['spins']);
            $maxSpins = oo::commonOprModel('member')->getLevelUpLimit($assetsInfo['levelId'],'spins') ?? 50;
        }

        //当前剩余未领完的好友个数
        $remainCount = 0;
        $receiveSpins = [];
        $sendNum = 0;
        foreach($friends as $row){
            /**
             * 赠送
             */
            $sendkey = okeys::SendGiftToday($uid,$row,$gid);
            if(!oo::commonOprRedis('common')->get($sendkey)){
                oo::commonOprRedis('common')->setex($sendkey,1,24*60*60);
                oo::commonOprRedis('common')->setex(okeys::SendEdGiftToday($uid,$row,$gid),1,7*24*60*60);
                oo::commonOprModel('Workerman')->push($row,ocmd::$redPoint,['type'=>5]);
                oo::commonOprModel('push')->pushNews($row, 'push.title.gift', 'push.content.gift', [$uidInfo['nick']],'gift');
                if($gid == 1){
                    oo::commonOprModel('ta')->setEventData($uid,"coin_send",["coin_send_object_user"=>$row,"coin_send_num"=>$num]);
                }else if($gid == 2){
                    oo::commonOprModel('ta')->setEventData($uid,"spin_send",["spin_send_object_user"=>$row,"spin_send_num"=>$num]);
                }
                $sendNum++;
            }
            if($gid == 2 && $curSpins >= $maxSpins){
                if(oo::commonOprRedis('common')->get(okeys::SendEdGiftToday($row,$uid,$gid)) == 1){
                    $remainCount++;
                }
                continue;
            }
            /**
             * 领取
             */
            $receiveKey = okeys::SendEdGiftToday($row,$uid,$gid);
            if(oo::commonOprRedis('common')->get($receiveKey) == 1){
                if($CurTimes < $MaxTimes){
                    oo::commonOprRedis('common')->setex($receiveKey,2,oo::todayDeadline());
                    $total    += 1;
                    $CurTimes += 1;
                    if($gid == 2){
                        $curSpins += 1;
                        $receiveSpins[] = $row;
                    }
                    if($gid == 1){
                        oo::commonOprModel('ta')->setEventData($uid,"coin_accept",["coin_accept_from_user"=>$row,"coin_accept_num"=>$num]);
                    }else if($gid == 2){
                        oo::commonOprModel('ta')->setEventData($uid,"spin_accept",["spin_accept_from_user"=>$row,"spin_accept_num"=>$num]);
                    }
                }
            }
        }
        $tid = $gid==1?10:9;
        oo::commonOprModel('callback')->doTask($uid, $tid, $sendNum);//召回任务
        if($total != 0){
            oo::commonOprModel('member')->optProperty($uid, [$type=>$total*$num], '+',50, '好友赠送'.$tips);
        }
        $reward = [$type=>$total*$num];
        if($type == 'money'){
            $reward['coins'] = $total*$num;
        }
        return oo::response(1,['reward'=>$reward,"remain_count" => $remainCount, "receive"=>['spins'=>$receiveSpins]]);
    }

    /**
     * 获取用户好友礼物金币数量
     * @param $uid
     * @return int
     * Created by: Owen
     * Created on: 2020/9/2 18:41
     */
    public function getUserFriendGiftCoins($uid){
        $config = oo::commonOprModel('config')->getFriendGiftCoinConfig();
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        $num = 10000;
        foreach ($config as $levelId=>$coins){
            if($levelId <= $assetsInfo['levelId']){
                $num = $coins;
            }else{
                break;
            }
        }
        return intval($num);
    }

    /**
     * 判断是否是好友
     * @param $uid
     * @param $toUid
     * @return bool
     * Created by: Owen
     * Created on: 2020/9/28 19:20
     */
    public function isFriend($uid,$toUid){
        if(in_array($toUid,self::getUserAllFriend($uid))){
            return true;
        }
        return false;
    }
}


function TimeCmp($a, $b) {
    return (@$a['lasttime'] < @$b['lasttime']) ? 1 : -1;
}

function cmpThree($a, $b) {
    if (@$a['type'] == @$b['type']) {
        return (@$a['money'] < @$b['money']) ? 1 : -1;
    } else {
        return (@$a['type'] < @$b['type']) ? -1 : 1;
    }
}
