<?php
defined('IN_WEB') or die('Include Error!');
define('AWAY_SEVEN_DAYS',  3);
define('ON_THE_HALL',      2);
define('ON_THE_TABLE',     1);
define('MONEY',        5000);//赠好友间送金币数
define('DOUBLETIME',       2);
define('LIMITTIME',       10);
define('MAX_FRIEND_NUM', 300);
/**
 * 好友相关
 */
class Friend
{
    protected $sendFriendMoney = 500;//赠送好友筹码
    protected $configFriend = array();

    public function __construct()
    {
        if (file_exists(PATH_CFG . 'config.friend.php')) {
            $this->configFriend = include PATH_CFG . 'config.friend.php';
        }
    }



    /**
     * 获取用户好友信息
     * @param unknown $param
     * @return string -1  获取id失败 -2  获取好友信息失败
     */
    public function listFunction($param)
    {
        $data = oo::commonOprModel('friend')->getList($param);
        return $data;
    }





    /**
     * 自动设置应用好友为牌友(FB登陆调用)
     */
    public function setFriends($param)
    {
        $array = array('code' => 0,);
        $uid = (int)$param['uid'];
        if (empty($uid)) {
            $array['code'] = -1;
            $array['line'] = __LINE__;
            return json_encode($array);
        }
        if(!funs::concurrentLock($uid,'serFriends',3600)){
            return json_encode(array('code' => 0));
        }
//        if (oo::commonOprCache('recallreward')->get(okeys::setFriends($uid))) { // 限制频繁请求
//            return json_encode(array('code' => 0));
//        }
        /* 安装了app的好友列表 */
        $accessToken = isset($param['access_token']) ? $param['access_token'] : '';
        if (empty($accessToken)) {
            $array['code'] = -2;
            $array['line'] = __LINE__;
            return json_encode($array);
        }
        /* 延迟设置牌友 -- 减少curl请求 */
//        if (oo::flag('DELAY_TO_SET_POKER')) {
//            $delayKey = okeys::delay_to_set_poker($uid);
//            if (ocache::cache()->add($delayKey, 1, 3600) === false) {
//                return json_encode(array('ret' => 0));
//            }
//        }
        //$shellCmd = sprintf('curl -ks --max-time 10 "https://graph.facebook.com/v2.1/me/friends?access_token=%s"', $accessToken);
        //$resJson = shell_exec($shellCmd);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'https://graph.facebook.com/v3.3/me?fields=friends&access_token='.$accessToken);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $resJson = curl_exec($curl);
        curl_close($curl);
        if (empty($resJson)) {
            $array['code'] = -3;
            $array['line'] = __LINE__;
            return json_encode($array);
        }
        $appList = array();
        $resArray = json_decode($resJson, TRUE);
        if (!empty($resArray['friends']['data'])) {
            foreach ($resArray['friends']['data'] as $tmpUser) {
                if (empty($tmpUser['id'])) continue;
                $appList[] = $tmpUser['id'];
            }
        }

        $appList = array_slice($appList, 0, 300); // 截取前300个应用好友
        if (empty($appList)) {
            $array['code'] = -4;
            $array['line'] = __LINE__;
            return json_encode($array);
        }
        $user = oo::commonOprModel('member');
        /* 根据siteuid反向查询uid */
        $accountList = array();
        $result = $user->getAccountMulti(array('keytype' => 'i', 'keyname' => 'siteuid', 'keylist' => $appList,),
            array('isiteuid' => 0, 'iuid' => 0,), $accountList);
        if ($result <= 0) {
            $array['ret'] = -5;
            $array['line'] = __LINE__;
            return json_encode($array);
        }
        $insertIsApper = json_encode($accountList);
        /* 安装应用好友的uid数组 */
        $uidList = array();
        foreach ($accountList as $v) {
            $uidList[] = intval($v['uid']);
        }
        /* 取用户好友信息，更新牌友 */
        $friends = array();
        $result = oo::commonOprModel('friend')->getUserFriends($uid, $friends, array('spoker' => '', 'snotapper' => ''));
        if ($result < 0) { /* 获取数据失败 */
            $array['ret'] = -6;
            $array['line'] = __LINE__;
            return json_encode($array);
        } elseif ($result == 0) { /* 没有好友信息 */
            $setUFRet = oo::commonOprModel('friend')->setUserFriends($uid, array('sisapper' => $insertIsApper,
                'spoker' => implode(',', $uidList), 'iupdatetime' => time()));
            if ($setUFRet <= 0) {
                $array['ret'] = -7;
                $array['line'] = __LINE__;
                return json_encode($array);
            }
            $array['ret'] = 0;
            return json_encode($array);
        }

        if (empty($friends['poker'])) {
            $poker = implode(',', $uidList);
        } else {
            $oldPokerArray = explode(',', $friends['poker']);
            $deletApper = explode(',', $friends['notapper']);
            //防止poker字段和notapper里面有相同的值，这样下面删除数据时候就不会把牌友给删除了
            foreach ($oldPokerArray as &$val) {
                $val = intval($val);
                if ($k = array_search($val, $deletApper) !== FALSE) {
                    unset($deletApper[$k]);
                }
            }
            $newPokerArray = array_merge($uidList, $oldPokerArray);
            if (!empty($deletApper)) {
                $newPokerArray = array_diff($newPokerArray, $deletApper);
            }
            $resultArray = array_unique($newPokerArray);
            $poker = implode(',', $resultArray);
        }
        $updateUFRet = oo::commonOprModel('friend')->updateUserFriends($uid, array('sisapper' => $insertIsApper, 'spoker' => $poker, 'iupdatetime' => time()));
        if ($updateUFRet < 0) {
            $array['code'] = -7;
            $array['line'] = __LINE__;
            $array['ttcCode'] = $updateUFRet;
            return json_encode($array);
        }
        $array['code'] = 1;
        // 限制频繁请求
//        oo::commonOprCache('recallreward')->set(okeys::setFriends($uid), 1, 1 * 3600);

        return json_encode($array);
    }



    /**
     *    给单个玩家赠送道具 传类型 uid fuid gid
     */
    public function sendPropToFriend($param)
    {
        $data = array('code' => -1);
        $uid = oo::functions()->uint($param['uid']); //uid
        $fuid = oo::functions()->uint($param['fuid']);//送给谁
        $gid = oo::functions()->uint($param['gid']);//类型id
        if (!$uid || !$fuid || !$gid) {
            return json_encode($data);
        }
        $data = oo::commonOprModel('friend')->sendPropToFriend($uid, $fuid, $gid);
        if($data['code'] == 1){
            $uidInfo = oo::commonOprModel('member')->getUserInfo($uid);
            oo::commonOprModel('push')->pushNews($fuid, 'push.title.gift', 'push.content.gift', [$uidInfo['nick']],'gift');
        }
        return json_encode($data);
    }

    /**
     *    一键批量赠送好友
     */
    public function sendPropToFriends($param){
        $data = array('code' => -1, 'total' => 0);
        $uid = oo::functions()->uint($param['uid']);
        $gid = oo::functions()->uint($param['gid']);//类型id
        if (!$uid || !$gid) {
            return json_encode($data);
        }
        if(!funs::concurrentLock($uid,'sendPropToFriends',5)){
            return oo::response(-2,[],'频繁操作');
        }
//        $timeLimit = oo::commonOprCache('memcache')->get("TIMELIMIT:{$uid}");
//        if($timeLimit){
//            return oo::response(-2,[],'频繁操作');
//        }
        $data = oo::commonOprModel('friend')->sendPropToFriends($uid, $gid);
//        oo::commonOprCache('memcache')->set("TIMELIMIT:{$uid}",1,5);
        return json_encode($data);
    }

    /**
     *  领取好友赠送的道具
     * YANG丶
     */
    public function FriendPropReceive($param){
        $data = array('code' => -1,'msg'=>'参数错误');
        $uid = oo::functions()->uint($param['uid']);
        $gid = oo::functions()->uint($param['gid']);//类型id
        $fuid = oo::functions()->uint($param['fuid']);
        if (!$uid || !$gid || !$fuid) {
            return json_encode($data);
        }
        $data = oo::commonOprModel('friend')->FriendPropReceive($uid,$fuid,$gid);
        return json_encode($data);

    }

    /**
     *  领取好友赠送的卡片   -- 一系列逻辑
     * YANG丶  +
     * $uid 当前用户uid  fuid 需要领取的好友uid
     * 2019-5-17 20:12:12
     */
    public function FriendReceiveCard($param){
        $data = array('code' => -1,'msg'=>'参数错误');
        $uid = oo::functions()->uint($param['uid']);
        $fuid = oo::functions()->uint($param['fuid']);
        if (empty($uid)  || empty($fuid)) {
            return json_encode($data);
        }
        $data = oo::commonOprModel('friend')->FriendReceiveCard($uid,$fuid);
        $all = oo::functions()->uint($param['getAll']);
        if($data['code'] == 1 && $all){
            $receive = [];
            foreach ($data['data']['receive'] as $row){
                $receive[] = $row;
            }
            $pendingCard = $data['data']['pendingCard'];
            for($i=0;$i<$pendingCard;$i++){
                $temp = oo::commonOprModel('friend')->FriendReceiveCard($uid,$fuid);
                if($temp['code']=1){
                    if(isset($temp['data']['receive'])&&is_array($temp['data']['receive'])){
                        foreach ($temp['data']['receive'] as $row){
                            $receive[] = $row;
                        }
                    }
                    $data['data']['card'] = $temp['data']['card'];
                    $data['data']['cardReward'] = $temp['data']['cardReward'];
                    $data['data']['cardGroupReward'] = $temp['data']['cardGroupReward'];
                    $data['data']['pendingCard'] = $temp['data']['pendingCard'];
                }
            }
            $data['data']['receive'] = $receive;
        }
        return json_encode($data);
    }

    public function friendList($param)
    {
        $data = [];
        $datas = array('code' => -1, 'list' => []);
        $uid = oo::functions()->uint($param['uid']);
        if (empty($uid)) {
            return json_encode($datas);
        }
        $friends = oo::commonOprModel('friend')->getUserAllFriend($uid);
        $datas['code'] =1;
        unset($datas['list']);
        if(empty($friends)){
            $datas['data'] = [];
            return json_encode($datas);
        }
        $attackCfg = oo::cfg('stealattack')['attack'];
        foreach ($friends as$k =>$v){
            $data[$k] = oo::commonOprModel('member')->getUserBasic($v);
            if($data[$k]['levelId']<=$attackCfg['minLv']){
                unset($friends[$k]);
                unset($data[$k]);
                continue;
            }
            $ttl = oo::commonOprRedis('common')->ttl(okeys::AttackLock($v));
            if($ttl>0){
                $data[$k]['protectTime'] = $ttl;
                $data[$k]['status'] = 1;
                $data[$k]['type'] =3;
            }else{
                $data[$k]['protectTime'] = 0;
                $data[$k]['status'] = 0;
                $data[$k]['type'] = 1;
            }
        }
        array_multisort(array_column($data,'star'),SORT_DESC,$data);
        $datas['data'] =$data;
        return json_encode($datas);
    }
    /**
     *	好友列表 -- 攻击模式 wsc-4.2(废弃)
     */
    public function friendListold($param)
    {
        $data = array('code' => -1, 'list' => []);
        $uid = oo::functions()->uint($param['uid']);
        if( empty($uid) ){
            return json_encode($data);
        }
        $data = oo::commonOprModel('rank')->friMoneyRank($uid,false);
        $data['data'] = ($data['list']['fir'])??[];
        unset($data['list']);
        if(!empty($data['data'])){
            $uids = implode(',',array_column($data['data'],'uid'));
            $tb   = otable::userlevel();
            $sql  = "SELECT * FROM {$tb} WHERE uid IN ({$uids}) ORDER BY FIELD(`uid`,{$uids})";
            $ret  = oo::commonOprDb('userlevel')->getAll($sql,MYSQLI_ASSOC);
            $time = time();
            foreach ($data['data'] as  $key=>$row){
                if($ret[$key]['attackProtectionTime'] > $time){
                    $data['data'][$key]['status'] = 1;
                }else{
                    $data['data'][$key]['status'] = 0;
                }
            }
        }
        return json_encode($data);
    }

    /**
     * 查询好友
     * @param $param
     * @return false|string
     * Created by: Owen
     * Created on: 2019/6/25 14:24
     * Description:
     */
    public function searchFriend($param){
        $uid = oo::functions()->uint($param['uid']);
        $toUid = oo::functions()->uint($param['toUid']);
        if( empty($uid) || empty($toUid) || $uid == $toUid){
            return json_encode($out = [
                'code'=>-1,
                'msg'=>'uid empty or toUid empty'
            ],JSON_NUMERIC_CHECK);
        }
        $arr = ['uid','nick','sex','s_picture','signature','u_flag'];
        $userInfo = oo::commonOprModel('member')->getUserInfo($toUid,$arr,false,NULL);
        if(empty($userInfo)){
            $out = [
                'code'=>-1,
                'msg'=>'User does not exist'
            ];
            return json_encode($out,JSON_NUMERIC_CHECK);
        }
        $temp = [];
        oo::commonOprModel('friend')->getUserFriends($uid,$temp);
        $gameList = explode(',',$temp['game_list']);
        foreach ($gameList as $row){
            $friends[] = $row;
        }
        $poker= explode(',',$temp['poker']);
        foreach ($poker as $row){
            $friends[] = $row;
        }
        $code = 1;
        $friends = array_filter($friends);
        if(in_array($toUid,$friends)){
            $userInfo['isfri'] = 1;
            $code = -2;
        }else{
            $userInfo['isfri'] = 0;
        }

        $tempInfo = oo::commonOprModel('member')->getUserAssetsInfo($toUid);
        $userInfo['star'] = $tempInfo['star'];
        return json_encode([
            'code'=>$code,
            'data'=>$userInfo
        ],JSON_NUMERIC_CHECK);
    }

    /**
     * 添加好友操作
     * @return false|string
     * Created by: Owen
     * Created on: 2019/6/25 14:24
     * Description:
     */
    public function applyFriend($param){
        $uid = oo::functions()->uint($param['uid']);
        $toUid = oo::functions()->uint($param['toUid']);
        if( empty($uid) || empty($toUid) ){
            return json_encode($out = [
                'code'=>1,
                'msg'=>'uid empty or toUid empty'
            ],JSON_NUMERIC_CHECK);
        }
        $ret = oo::commonOprModel('friend')->applyFriend($uid,$toUid);
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }

    /**
     * 審核好友
     * @param $param
     * @return false|string
     * Created by: Owen
     * Created on: 2019/6/25 15:23
     * Description:
     */
    public function reviewFriend($param){
        $uid = oo::functions()->uint($param['uid']);
        $toUid = oo::functions()->uint($param['toUid']);
        $status = oo::functions()->uint($param['status']);
        if( empty($uid) || empty($toUid) || empty($status) ){
            return json_encode($out = [
                'code'=>1,
                'msg'=>'uid empty or toUid empty'
            ],JSON_NUMERIC_CHECK);
        }
        $ret = oo::commonOprModel('friend')->reviewFriend($uid,$toUid,$status);
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }

    /**
     * 刪除好友
     * @param $param
     * @return false|string
     * Created by: Owen
     * Created on: 2019/6/25 15:30
     * Description:
     */
    public function deleteFriend($param){
        $uid = oo::functions()->uint($param['uid']);
        $toUid = oo::functions()->uint($param['toUid']);
        if( empty($uid) || empty($toUid) ){
            return json_encode($out = [
                'code'=>1,
                'msg'=>'uid empty or toUid empty'
            ],JSON_NUMERIC_CHECK);
        }
        $ret = oo::commonOprModel('friend')->deleteFriend($uid,$toUid);
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }

    public function recommendFriend($param){
        $uid = oo::functions()->uint($param['uid']);
        if( empty($uid)){
            return json_encode($out = [
                'code'=>1,
                'msg'=>'uid empty'
            ],JSON_NUMERIC_CHECK);
        }
        $ret = oo::commonOprModel('friend')->recommendFriend($uid);
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }

    /**
     * 分享添加好友
     * @param $param
     * @return false|string
     * Created by: Owen
     * Created on: 2019/8/15 17:14
     * Description:
     */
    public function shareAddFriend($param){
        $uid = oo::functions()->uint($param['uid']);
        $toUid = oo::functions()->uint($param['toUid']);
        if(empty($uid) || empty($toUid)){
            return oo::response(-1);
        }
        $userInfo = [];
        $argument['keylist'] = [$uid,$toUid];//批量获得参数
        $ret = oo::commonOprModel('member')->getUserInfoMulti($argument, $userInfo);
        if($ret != 1){
            return oo::response(-2,[],'用户ID异常');
        }

        $uidFriends = oo::commonOprModel('friend')->getUserAllFriend($uid);
        if(in_array($toUid,$uidFriends)){
            return oo::response(1,[],'已是好友');
        }

        $toUidFriends = oo::commonOprModel('friend')->getUserAllFriend($toUid);
        if(count($toUidFriends)>=200 || count($uidFriends)>=200){
            return oo::response(-3,[],'好友上限');
        }
        oo::commonOprModel('friend')->addUserFriend($uid,$toUid);
        return json_encode(['code'=>1],JSON_NUMERIC_CHECK);
    }
}