<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2024/3/26} {20:55} 
 */

namespace app\api\controller;


use app\api\logic\UserOfflinePrizeLogic;
use app\common\model\TabConf;
use GatewayWorker\Lib\Gateway;
use think\Db;
use think\Exception;
use wanghua\general_utility_tools_php\Mmodel;
use wanghua\general_utility_tools_php\SundryConfig;
use wanghua\general_utility_tools_php\tool\Tools;
use wanghua\general_utility_tools_php\wechat\UserAuth;

class Users extends BaseHttpApi
{
    /**
     * desc：根据游戏id查询用户
     * api/Users/getUserById
     * 参数：
     * gameid 用户id
     * author：wh
     */
    function getUserById(){
        return Mmodel::catchJson(function (){
            $gameid = input('gameid');
            if(empty($gameid)){
                return Tools::set_fail('参数错误');
            }
            $data = Db::table(TabConf::$fa_users)
                ->where('id',$gameid*1)
                ->find();
            return Tools::set_res(200,'查询成功',$data);
        });
    }

    /**
     * desc：根据openid查询用户
     * api/Users/getUserInfo
     * 参数：
     * openid
     *
     * 返回：
     * now_rank 当前排名
     * all_coins: 累计获得金币
     * enemy 累计击杀数
     * eliminate 消消乐道具
     */
    function getUserInfo(){
        Tools::log_to_write_txt(['查询单个用户 入参：'=>input()]);
        try {

            $openid = input('openid');
            if(empty($openid)){
                return json(Tools::set_fail('参数错误'));
            }



            $model_obj = Db::table('fa_users');

            if(input('openid')){
                $model_obj->where('openid',input('openid'));
            }
            $data = $model_obj->find();
            if(empty($data)){
                return json(Tools::set_res(234,'用户不存在'));
            }
            //更新用户最后登录时间
            Db::table('fa_users')
                ->data(['last_login_time'=>Tools::get_now_date()])
                ->where('id',$data['id'])
                ->update();

            //写入登录记录
            Mmodel::existsUpdateInsert('fa_login_record',['date'=>date('Y-m-d')],[
                'openid'=>$openid,
                'date'=>date('Y-m-d')
            ]);

            //总计登录天数
            $data['total_login_days'] = Db::table('fa_login_record')
                ->where('openid',$openid)
                ->count('id');
            //当前排名
            $data['now_rank'] = $this->countRank($openid);

            //eliminate
            $eliminate = Db::table('fa_usereliminate')
                ->where('openid',$data['openid'])
                ->select();
            $data['eliminate'] = $eliminate;


            return json(Tools::set_ok('ok',$data));
        }catch(\Exception $e){
            Tools::log_to_write_txt([
                'error'=>'查询单个用户.异常.'.$e->getMessage(),
                '参数'=>input(),
                'error_info'=>$e->getTraceAsString()
            ]);
            return json(Tools::set_res(500,'操作异常',[]));
        }
    }

    /**
     * desc：计算排名
     * author：wh
     */
    private function countRank($openid){
        if(cache('user_rank_'.$openid)){
            return cache('user_rank_'.$openid);
        }
        $lists = Db::table(TabConf::$fa_users)
            ->order('now_level desc')
            ->field('openid,now_level')
            ->select();

        if($lists){
            foreach ($lists as $k=>$v){
                if($v['openid'] == $openid){
                    cache('user_rank_'.$openid,$k+1,3600);
                    return $k+1;
                }
            }
        }
        return 0;//没有排名
    }
    /**
     * desc：微信授权，登录
     *
     * /api/users/login
     *
     * 参数:code
     *
     * author：wh
     */
    function login()
    {
        Db::startTrans();
        try {
            $clientid = input('clientid');
            if(empty($clientid)){
                return json(Tools::set_fail('clientid error'));
            }
            $code = input('code');
            if(empty($code)){
                return json(Tools::set_fail('CODE参数错误'));
            }
            $wxconfig = get_wechat_config();

            Tools::log_to_write_txt(['微信授权，start'=>input(),'$wxconfig'=>$wxconfig]);
            $res = (new UserAuth($wxconfig))->usrAccessTokenApplet($code);
            Tools::log_to_write_txt(['微信授权，end'=>$res]);


            $openid = $res['openid'];

            $user = Db::table(TabConf::$fa_users)->where('openid',$openid)->find();
            if(empty($user)){

                $data = [
                    'openid'=>$openid,
                    'nickname'=>Tools::rand_str(),
                    'headimage'=>'',
                    'hint_num'=>3,
                    'clientid'=>$clientid,
                    'user_type'=>'wechat'
                ];
                //新增一个用户
                $id = Db::table(TabConf::$fa_users)
                    ->insertGetId($data);
                $data['id'] = $id;
            }else{
                Db::table(TabConf::$fa_users)
                    ->where('openid',$openid)
                    ->data(['clientid'=>$clientid])//更新登录状态
                    ->update();
                $data = $user;
            }

            session('api_user_info',$data);

            Db::commit();
            return json(Tools::set_ok('ok',$res));
        }catch (\Exception $e){
            Db::rollback();
            Tools::log_to_write_text([
                'error'=>'微信授权异常。'.$e->getMessage(),
                'input'=>input(),
                'error_info'=>$e->getTraceAsString()
            ]);
            return json(Tools::set_fail('请求异常'));
        }
    }

    /**
     * desc：修改用户昵称、头像
     *
     * /api/users/updateuser
     *
     * 参数：
     * openid 必传
     * nickname，headimage
     */
    function updateuser(){
        return Mmodel::catchJson(function (){

            $nickname = input('nickname','');
            $headimage = input('headimage','');

            $data = [];
            if($nickname){
                $data['nickname'] = $nickname;
            }
            if($headimage){
                $data['headimage'] = $headimage;
            }
            $openid = input('openid');
            if(empty($openid)){
                return Tools::set_fail('OPENID MUST');
            }
            if(!empty($data)){
                Db::table(TabConf::$fa_users)
                    ->where('openid',$openid)
                    ->data($data)
                    ->update();
            }

            return Tools::set_ok();
        });
    }

    /**
     * desc：更新最新关卡
     * api/users/updatenowlevel
     *
     * 参数：
     * now_level 最新关卡
     * author：wh
     */
    function updateNowLevel(){
        return Mmodel::catchJson(function (){
            $now_level = input('now_level');
            if(empty($now_level)){
                return Tools::set_fail('now_level 必须');
            }
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->update([
                    'now_level'=>$now_level,
                ]);
            return Tools::set_ok();
        });
    }

    /**
     * desc：查询好友列表-计算离线奖励
     * /api/users/getFriendsOfflinePrizeList
     *
     * 离线奖励:从用户下线时刻开始，每3个小时奖励一瓶随机等级的肥料，只取整数，不四舍五入。离线时长除以3取整数。
     * 比如:离线 0-2.9 个小时 不奖励
    离线 3-5.9 个小时 奖励 1瓶
    离线 6-8.9 个小时 奖励 2瓶
     *
    gameprop_id   道具奖品
    prize_all_num   总奖励数量
    self_got_num   自己保底所得数量(固定)
    can_lose_num   可被偷取的数量(固定)
    now_can_lose_num 已偷取（偷取后数值增加，数值大于可被偷取的总数量时，拒绝偷取）
     * author：wh
     */
    function getFriendsOfflinePrizeList(){
        return Mmodel::catchJson(function (){
            //查询我的离线好友
            $friends = Db::table(TabConf::$fa_gamefriend)
                ->where('openid',api_user_openid())
                ->select();
            if(empty($friends)){
                return Tools::set_res(220,'没有好友');
            }
            //可偷取的奖励部分每次允许偷取比例配置
            $lose_rate = SundryConfig::val('offline_prize_can_lose_per_times_lose_rate');


            foreach ($friends as &$list){
                $friend_openid = $list['friend_openid'];
                $sql = "
                select * from fa_user_offline_prize a left join 
		fa_user_offline_prize_got_record b
		on a.id = b.user_offline_prizeid
		where a.openid='{$friend_openid}' and b.user_offline_prizeid is null;
                ";
                //查询好友的离线奖励
                $friend_prize = Db::query($sql);
                //统计我的已偷取数量
                //$my_already_lose_num = Db::table(TabConf::$fa_user_offline_prize_got_record)
                //    ->where('openid',api_user_openid())
                //    ->whereIn('user_offline_prizeid',array_column($friend_prize,'id'))
                //    ->sum('num');
                //统计我的已偷取数量=$can_lose_num*$lose_rate，如果相等就设置偷取数量为0
                $can_lose_num_arr = array_column($friend_prize,'can_lose_num');
                //总的可偷取数量
                $can_lose_num = array_sum($can_lose_num_arr);
                $already_lose_num_arr = array_column($friend_prize,'already_lose_num');
                //已偷取的总数量
                $already_lose_num = array_sum($already_lose_num_arr);

                $friend_prize['now_can_lose_num'] = floor(($can_lose_num-$already_lose_num)*$lose_rate);
                $friend_prize['lose_rate'] = $lose_rate;

                $tmp_arr = [];
                //查询好友的奖励
                $tmp_arr['friend_prize'] = $friend_prize;
                $list = array_merge($list, $tmp_arr);


                //$can_lose_num_arr = array_column($friend_prize,'can_lose_num');
                //$can_lose_num = array_sum($can_lose_num_arr);//总的可偷取数量
                //if($my_already_lose_num == $can_lose_num*$lose_rate){
                //    //默认为0
                //    $friend_prize['now_can_lose_num'] = 0;
                //    $friend_prize['lose_rate'] = 0;
                //    $tmp_arr = [];
                //    $tmp_arr['friend_prize'] = $friend_prize;
                //    $list = array_merge($list, $tmp_arr);
                //}else{
                //    //过滤已偷过的记录
                //    //$already_lose_record = Db::table(TabConf::$fa_user_offline_prize_got_record)
                //    //    ->where('openid',api_user_openid())
                //    //    ->whereIn('user_offline_prizeid',array_column($friend_prize,'id'))
                //    //    ->select();
                //    $friend_prize = Db::table(TabConf::$fa_user_offline_prize)
                //        ->where('openid',$list['friend_openid'])
                //        ->whereNotIn('id',array_column($already_lose_record,'id'))//剔除已偷过的记录
                //        ->select();
                //
                //    $can_lose_num_arr = array_column($friend_prize,'can_lose_num');
                //    //总的可偷取数量
                //    $can_lose_num = array_sum($can_lose_num_arr);
                //    $already_lose_num_arr = array_column($friend_prize,'already_lose_num');
                //    //已偷取的总数量
                //    $already_lose_num = array_sum($already_lose_num_arr);
                //
                //    $friend_prize['now_can_lose_num'] = floor(($can_lose_num-$already_lose_num)*$lose_rate);
                //    $friend_prize['lose_rate'] = $lose_rate;
                //
                //    $tmp_arr = [];
                //    //查询好友的奖励
                //    $tmp_arr['friend_prize'] = $friend_prize;
                //    $list = array_merge($list, $tmp_arr);
                //}
            }
            return Tools::set_ok('ok',$friends);
        });
    }

    /**
     * desc：随机奖励
     */
    private function random_prop($key=''){
        $count = Db::table(TabConf::$fa_gameprop)
            ->count('id');
        $id = mt_rand(1,$count);

        $p = Db::table(TabConf::$fa_gameprop)->where('id',$id)->find();
        if(empty($p)){
            $id = mt_rand(1,$count);
            $p = Db::table(TabConf::$fa_gameprop)->where('id',$id)->find();
        }
        if(empty($p)){
            throw new Exception('道具获取失败');
        }
        return $key?$p[$key]:$p;
    }

    /**
     * desc：（偷取）领取好友离线奖励（领取多少根据后台配置领取比例而定），偷取后发邮件给用户
     * 
     * api/users/offlineprizegot
     * 参数：
     * friend_openid 好友
     *
     * author：wh
     */
    function offlinePrizeGot(){
        return Mmodel::catchTransJson(function (){
            $friend_openid = input('friend_openid');
            if(empty($friend_openid)){
                return Tools::set_fail('friend_openid 必须');
            }
            //可偷取的奖励部分每次允许偷取比例配置
            $lose_rate = SundryConfig::val('offline_prize_can_lose_per_times_lose_rate');

            $sql = "
                select a.* from fa_user_offline_prize a left join 
		fa_user_offline_prize_got_record b
		on a.id = b.user_offline_prizeid
		where a.openid='{$friend_openid}' and b.user_offline_prizeid is null;
                ";
            //查询好友的离线奖励
            $prize_lists = Db::query($sql);

            $got_prize_arr = [];
            foreach ($prize_lists as $prize){
                $gameprop_id = $prize['gameprop_id'];
                //计算本次可领取奖励
                $num = floor($prize['can_lose_num'] * $lose_rate);
                if($num<=0){
                    //偷取数量为0
                    $got_prize_arr[]=[
                        'num'=>0,
                        'gameprop_id'=>0
                    ];
                    continue;
                }
                //查询用户已有道具
                $usergameprop = Db::table(TabConf::$fa_usergameprop)
                    ->where('openid',api_user_openid())
                    ->where('gameprop_id',$gameprop_id)
                    ->find();
                //偷取时更新奖励
                if($usergameprop){
                    //更新用户道具数量
                    Db::table(TabConf::$fa_usergameprop)
                        ->where('openid',api_user_openid())
                        ->where('gameprop_id',$gameprop_id)
                        ->setInc('num',$num);
                }else{
                    //查询道具
                    $gameprop = Db::table(TabConf::$fa_gameprop)
                        ->where('id',$prize['gameprop_id'])
                        ->find();
                    //新增用户道具
                    Db::table(TabConf::$fa_usergameprop)
                        ->data([
                            'gameproptype_id'=>$gameprop['gameproptype_id'],
                            'name'=>$gameprop['name'],
                            'image'=>$gameprop['image'],
                            'openid'=>api_user_openid(),
                            'num'=>$num,
                            'gameprop_id'=>$gameprop_id
                        ])
                        ->insert();
                }

                //偷取时，增加已偷取数量
                Db::table(TabConf::$fa_user_offline_prize)
                    ->where('id',$prize['id'])
                    ->setInc('already_lose_num',$num);

                //写入（偷取）领取记录
                Db::table(TabConf::$fa_user_offline_prize_got_record)
                    ->data([
                        'openid'=>api_user_openid(),
                        'friend_openid'=>$friend_openid,
                        'num'=>$num,
                        'gameprop_id'=>$gameprop_id,
                        'user_offline_prizeid'=>$prize['id'],//记录id
                    ])
                    ->insert();
                $got_prize_arr[]=[
                    'num'=>$num,
                    'gameprop_id'=>$gameprop_id
                ];

            }
            //添加一封邮件（不是真实的邮件，可以理解为消息）
            Db::table(TabConf::$fa_user_email)
                ->data([
                    'addresser_openid'=>api_user_openid(),
                    'addressee_openid'=>$friend_openid,//收件人
                    'title'=>'好友偷取奖励',
                    'content'=>'您的奖励已被好友偷取啦！',
                ])
                ->insert();
            return Tools::set_ok('ok',$got_prize_arr);
        });
    }

    /**
     * 查询自己的离线奖励
     *
     * 离线奖励:从用户下线时刻开始，每3个小时奖励一瓶随机等级的肥料，只取整数，不四舍五入。离线时长除以3取整数。
     * 比如:离线 0-2.9 个小时 不奖励
    离线 3-5.9 个小时 奖励 1瓶
    离线 6-8.9 个小时 奖励 2瓶
     *
     * api/users/getselfofflineprize
     */
    function getSelfOfflinePrize(){
        return Mmodel::catchJson(function (){
            $lists = Db::table(TabConf::$fa_user_offline_prize)
                ->where('openid',api_user_openid())
                ->order('id asc')//客户端要取最早的那个时间
                ->select();
            if(empty($lists)){
                return Tools::set_res(220,'没有离线奖励');
            }
            //可偷取的奖励部分每次允许偷取比例配置
            $lose_rate = SundryConfig::val('offline_prize_can_lose_per_times_lose_rate');
            $lists_data = [];
            foreach ($lists as $list){
                if($list['self_got_num']==0){
                    continue;//领取过的数据，不返回
                }
                $record = Db::table(TabConf::$fa_user_offline_prize_got_record)
                    ->where('openid',api_user_openid())//当前登陆人
                    ->where('user_offline_prizeid',$list['id'])
                    ->find();
                if(empty($record)){//为空说明未偷取
                    $lists_data[] = array_merge($list, ['now_can_lose_num'=>floor($list['can_lose_num']*$lose_rate),'lose_rate'=>$lose_rate]);
                }else{
                    $lists_data[] = array_merge($list, ['now_can_lose_num'=>0]);
                }
            }
            return Tools::set_ok('ok',$lists_data);
        });
    }
    /**
     * desc：领取自己的离线奖励（一次性领取所有离线奖励，不能分批次领取，没有部分领取一说）
     * api/users/receiveSelfOfflinePrize
     * 参数：
     * is_double 是否双倍奖励 1 一倍，2 二倍
     * author：wh
     */
    function receiveSelfOfflinePrize(){
        return Mmodel::catchTransJson(function (){
            //查询我的离线奖励
            $prize_lists = Db::table(TabConf::$fa_user_offline_prize)
                ->where('openid',api_user_openid())
                ->lock(true)//锁住
                ->select();

            $got_prize_arr = [];
            //是否双倍奖励 1 一倍，2 二倍
            $is_double = input('is_double',1);
            foreach ($prize_lists as $item){
                //查询领取记录
                $offline_prize_got_record = Db::table(TabConf::$fa_user_offline_prize_got_record)
                    ->where('openid',api_user_openid())
                    ->where('user_offline_prizeid',$item['id'])
                    ->find();
                if($offline_prize_got_record){
                    continue;//领取过的数据，不能再次领取
                }
                //道具id
                $gameprop_id = $item['gameprop_id'];
                //自己保底所得数量+可被偷取的数量-已被偷取的数量
                $prize_all_num = $item['self_got_num'] + $item['can_lose_num'] - $item['already_lose_num'];
                //乘以倍数
                $num = $prize_all_num * $is_double;

                //查询道具
                $gameprop = Db::table(TabConf::$fa_gameprop)
                    ->where('id',$gameprop_id)
                    ->find();
                if(empty($gameprop)){
                    //道具不应该不存在
                    continue;
                    //return Tools::set_fail('道具不存在');
                }
                //写入领取记录
                Db::table(TabConf::$fa_user_offline_prize_got_record)
                    ->data([
                        'openid'=>api_user_openid(),
                        'num'=>$num,
                        'gameprop_id'=>$gameprop_id,
                        'is_double'=>$is_double,
                        'user_offline_prizeid'=>$item['id'],
                    ])
                    ->insert();
                //查询用户已有道具
                $usergameprop = Db::table(TabConf::$fa_usergameprop)
                    ->where('openid',api_user_openid())
                    ->where('gameprop_id',$gameprop_id)
                    ->find();
                if($usergameprop){
                    //更新道具数量
                    Db::table(TabConf::$fa_usergameprop)
                        ->where('openid',api_user_openid())
                        ->where('gameprop_id',$gameprop_id)
                        ->setInc('num',$num);
                }else{
                    //新增道具
                    Db::table(TabConf::$fa_usergameprop)
                        ->data([
                            'gameproptype_id'=>$gameprop['gameproptype_id'],
                            'name'=>$gameprop['name'],
                            'image'=>$gameprop['image'],
                            'openid'=>api_user_openid(),
                            'num'=>$num,
                            'gameprop_id'=>$gameprop_id
                        ])
                        ->insert();
                }

                Db::table(TabConf::$fa_user_offline_prize)
                    ->where('id',$item['id'])
                    ->data([
                        'self_got_num'=>0,
                        'can_lose_num'=>0,
                    ])
                    ->update();
                $got_prize_arr[]=[
                    'num'=>$num,
                    'gameprop_id'=>$gameprop_id
                ];
            }
            //领取之后删除离线奖励表
            UserOfflinePrizeLogic::deletedPrize(api_user_openid());
            return Tools::set_ok('领取成功',$got_prize_arr);
        });
    }

    /**
     * desc：查询我的好友列表
     *
     * api/users/getMyFriends
     *
     * author：wh
     */
    function getMyFriends(){
        return Mmodel::catchJson(function (){
            $lists = Db::table(TabConf::$fa_gamefriend)
                ->where('openid',api_user_openid())
                ->select();
            return Tools::set_ok('ok',$lists);
        });
    }
    /**
     * desc：添加好友
     *
     * api/users/addFriend
     * 参数：
     * friend_openid 好友openid
     * 注意：如果好友在线，会向好友发送申请消息
     * author：wh
     */
    function addFriend(){
        return Mmodel::catchJson(function (){
            $friend_openid = input('friend_openid');
            if(empty($friend_openid)){
                return Tools::set_fail('请输入好友openid');
            }
            $user_friend = Db::table(TabConf::$fa_users)
                ->where('openid',$friend_openid)
                ->find();
            if(empty($user_friend)){
                return Tools::set_fail('好友不存在');
            }
            $uf = Db::table(TabConf::$fa_gamefriend)
                ->where('openid',api_user_openid())
                ->where('friend_openid',$friend_openid)
                ->find();
            if($uf){
                return Tools::set_fail('不能添加自己和自己的好友');
            }
            if($friend_openid == api_user_openid()){
                return Tools::set_fail('不能添加自己');
            }
            $data = [
                'openid'=>api_user_openid(),
                'headimage'=>api_user_info('headimage'),
                'nickname'=>api_user_info('nickname'),
                'friend_openid'=>$friend_openid,
                'friend_nickname'=>$user_friend['nickname']
            ];
            //如果已经申请则不再申请
            $apply_record = Db::table(TabConf::$fa_friend_apply_record)
                ->where('openid',api_user_openid())
                ->where('friend_openid',$friend_openid)
                ->find();
            if($apply_record){
                return Tools::set_fail('你已申请过该好友');
            }

            Db::table(TabConf::$fa_friend_apply_record)
                ->data($data)
                ->insert();

            //如果好友在线，则发送添加好友申请
            if($user_friend['clientid']){
                $json = BaseWssApi::json_wss('new-friend-apply', '有新的好友申请');
                Gateway::sendToClient($user_friend['clientid'], json_encode($json, JSON_UNESCAPED_UNICODE));
            }

            return Tools::set_ok('申请已发送');
        });
    }

    /**
     * desc：查询我的好友申请列表
     *
     * api/users/getFriendApplyList
     * author：wh
     */
    function getFriendApplyList(){
        return Mmodel::catchJson(function (){
            $friend_apply_record = Db::table(TabConf::$fa_friend_apply_record)
                ->where('friend_openid',api_user_openid())
                ->select();
            return Tools::set_ok('ok',$friend_apply_record);
        });
    }

    /**
     * 同意好友申请
     * api/users/agreeFriendApply
     * 参数：
     * friend_openid 好友openid
     */
    function agreeFriendApply(){
        return Mmodel::catchTransJson(function (){
            $friend_openid = input('friend_openid');
            if(empty($friend_openid)){
                return Tools::set_fail('请输入好友openid');
            }
            $user_friend = Db::table(TabConf::$fa_users)
                ->where('openid',$friend_openid)
                ->find();
            if(empty($user_friend)){
                return Tools::set_fail('好友不存在.');
            }
            //好友已存在
            $uf = Db::table(TabConf::$fa_gamefriend)
                ->where('openid',api_user_openid())
                ->where('friend_openid',$friend_openid)
                ->find();
            if($uf){
                return Tools::set_fail('好友已存在');
            }
            //添加陌生人为好友
            Db::table(TabConf::$fa_gamefriend)
                ->data([
                    'openid'=>api_user_openid(),
                    'nickname'=>api_user_info('nickname'),
                    'friend_openid'=>$friend_openid,
                    'friend_nickname'=>$user_friend['nickname'],
                    'friend_image'=>$user_friend['headimage'],
                ])
                ->insert();
            //把自己添加为陌生人的好友
            Db::table(TabConf::$fa_gamefriend)
                ->data([
                    'openid'=>$friend_openid,
                    'nickname'=>$user_friend['nickname'],
                    'friend_openid'=>api_user_openid(),
                    'friend_nickname'=>api_user_info('nickname'),
                    'friend_image'=>api_user_info('headimage'),
                ])
                ->insert();

            //删除好友申请记录
            Db::table(TabConf::$fa_friend_apply_record)
                ->where('openid',$friend_openid)
                //->where('friend_openid',$friend_openid)
                ->delete();
            return Tools::set_ok('ok');
        });
    }

    /**
     * 拒绝好友申请
     *
     * api/users/refuseFriendApply
     * 参数:
     * friend_openid 好友openid
     */
    function refuseFriendApply(){
        return Mmodel::catchTransJson(function (){
            $friend_openid = input('friend_openid');
            if(empty($friend_openid)){
                return Tools::set_fail('请输入好友openid');
            }
            $users = Db::table(TabConf::$fa_users)
                ->where('openid',$friend_openid)
                ->find();
            if(empty($users)){
                return Tools::set_fail('用户不存在');
            }
            //删除好友申请记录
            Db::table(TabConf::$fa_friend_apply_record)
                ->where('openid',$friend_openid)
                //->where('friend_openid',$friend_openid)
                ->delete();
            return Tools::set_ok('ok');
        });
    }

    /**
     * desc：增加金币,直接存用户信息里
     * author：wh
     * 参数：
     * coins 金币数量
     */
    function addCoins(){
        return Mmodel::catchTransJson(function (){
            $coins = input('coins');
            if(empty($coins)){
                return Tools::set_fail('请输入金币');
            }
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->setInc('coins',$coins);

            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->setInc('all_coins',$coins);//累计金币

            return Tools::set_ok('ok');
        });
    }
    /**
     * desc：消耗金币
     * author：wh
     * 参数：
     * coins 金币数量
     */
    function cutCoins(){
        return Mmodel::catchJson(function (){
            $coins = input('coins');
            if(empty($coins)){
                return Tools::set_fail('请输入金币');
            }
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->setDec('coins',$coins);
            return Tools::set_ok('ok');
        });
    }



    /**
     * 消耗金币增加体力(消耗金币增加体力次数减一)
     * 参数：无
     * api/users/cutCoinsAddStrength
     */
    function cutCoinsAddStrength(){
        return Mmodel::catchTransJson(function (){
            //消耗金币增加体力的金币数值配置
            $cut_n_coins_add_power = SundryConfig::val('cut_n_coins_add_power');
            $user = Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->lock(true)
                ->find();
            if($user['coin_power_times'] <= 0){
                return Tools::set_fail('金币增加体力次数不足');
            }
            if($user['coins'] < $cut_n_coins_add_power){
                return Tools::set_fail('金币不足');
            }
            //消耗金币
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->setDec('coins',$cut_n_coins_add_power);
            //增加体力
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->setInc('power',1);

            //减少金币增加体力次数
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->where('coin_power_times','>',0)
                ->setDec('coin_power_times',1);

            return Tools::set_ok('ok');
        });
    }

    /**
     * 看广告增加体力 (看广告增加体力次数减一)
     * 参数：无
     * api/users/lookAdAddPower
     */
    function lookAdAddPower(){
        return Mmodel::catchTransJson(function (){
            $user = Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->lock(true)
                ->find();
            if($user['ad_power_times'] <= 0){
                return Tools::set_fail('看广告增加体力次数不足');
            }
            //增加体力
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->setInc('power',1);

            //
            Db::table(TabConf::$fa_users)
                ->where('openid',api_user_openid())
                ->where('ad_power_times','>',0)
                ->setDec('ad_power_times',1);

            return Tools::set_ok('ok');
        });
    }

}