<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use Redis;
/**
 * 视频直播间
 */
class Livebc extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    //直播列表
    public function lists(){
        $type_id = input('type_id','');

        $map = [
            'livebc.is_online' => 1,
            'livebc.room_type' => 2,
            'livebc.status' => 1,
        ];
        if(!empty($type_id)){
            $map['livebc.party_type'] = $type_id;
        }

        $list = Db::name('party')->alias('livebc')->field('livebc.id,livebc.user_id,livebc.party_name as title,livebc.cityname,user.nickname,user.avatar')
            ->join('user','livebc.user_id = user.id','LEFT')
            ->where($map)
            ->autopage()->select();

        $list = list_domain_image($list,['avatar']);

        $this->success('success',$list);
    }

    //直播间详情
    public function info(){
        $id = input('id',0);
        if(empty($id)){
            $this->error();
        }

        $map = [
            'livebc.id' => $id,
            'livebc.room_type' => 2,
        ];
        $info = Db::name('party')->alias('livebc')->field('livebc.id,livebc.user_id,livebc.party_name as title,livebc.cityname,user.nickname,user.avatar')
            ->join('user','livebc.user_id = user.id','LEFT')
            ->where($map)
            ->find();

        if(!empty($info)){
            $map = [
                'uid' => $this->auth->id,
                'follow_uid' => $info['user_id'],
            ];
            $is_follow = Db::name('user_follow')->where($map)->find();
            $info['is_follow'] = $is_follow ? 1 : 0;

            $info = info_domain_image($info,['avatar']);
        }

        $this->success('success',$info);
    }

    //直播送礼物
    public function givegift() {
        // 接口防并发
        if (!$this->apiLimit(1, 1000)) {
            $this->error(__('Operation frequently'));
        }

        $user_id = input('user_id');// 赠送对象
        $gift_id = input('gift_id');// 礼物ID
        $number  = input('number',1,'intval');//数量

        if (!$user_id || !$gift_id || $number < 1)
        {
            $this->error();
        }

        // 不可以赠送给自己
        if($this->auth->id == $user_id)
        {
            $this->error("不可以赠送给自己");
        }

        // 获取礼物信息
        $giftinfo = Db::name('gift')->where('id',$gift_id)->find();
        if (!$giftinfo)
        {
            $this->error("请选择礼物");
        }
        $giftvalue = bcmul($giftinfo['value'],$number);

        //被赠送人信息
        $touserinfo = Db::name('user')->where('id',$user_id)->find();
        if (!$touserinfo)
        {
            $this->error("不存在的用户");
        }

        // 判断当前用户余额
        $user_gold = model('wallet')->getWallet($this->auth->id,'gold');
        if($user_gold < $giftvalue)
        {
            $this->error("您的金币余额不足");
        }

        $partyid = Db::name('party')->where(['user_id'=>$user_id,'room_type'=>2])->value('id');

        Db::startTrans();


        // 添加礼物赠送记录表
        $data = [
            'user_id' => $this->auth->id,
            'user_to_id' => $user_id,
            'gift_id' => $giftinfo['id'],
            'gift_name' => $giftinfo['name'],
            'number' => $number,
            'price' => $giftvalue,
            'createtime' => time(),
        ];
        $log_id = Db::name('gift_user_livebc')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('赠送失败');
        }


        if($giftvalue > 0){

            // 扣除当前用户余额
            $wallet_rs = model('wallet')->lockChangeAccountRemain($this->auth->id,'gold',-$giftvalue,55,'赠送礼物:'.$giftinfo["name"],'gift_user_typing',$log_id);
            if($wallet_rs['status'] === false){
                Db::rollback();
                $this->error($wallet_rs['msg']);
            }

            // 添加赠送用户声币余额
            $money_to_gold = config('site.money_to_gold');
            $gift_plat_scale = config('site.gift_plat_scale');

            $giftmoney = bcdiv($giftvalue,$money_to_gold,2);

            $money = bcdiv(bcmul($giftmoney,100 - $gift_plat_scale,2),100,2);
            $wallet_rs = model('wallet')->lockChangeAccountRemain($user_id,'money',$money,56,'获得礼物:'.$giftinfo["name"],'gift_user_typing',$log_id);
            if($wallet_rs['status'] === false){
                Db::rollback();
                $this->error($wallet_rs['msg']);
            }

            //排行榜
            $redis = new Redis();
            $redisconfig = config("redis");
            $redis->connect($redisconfig["host"], $redisconfig["port"]);

            // 添加redis记录做财富排行榜
            $redis->zIncrBy("livebc_jewel_get_" . $partyid, $giftvalue, $user_id);

            // 添加redis记录做贡献排行榜
            $redis->zIncrBy("livebc_jewel_to_" . $partyid, $giftvalue, $this->auth->id);
        }

        // tcp 获取房间用户周前三名
        $partyUserTop = $this->getPartyUserTop($partyid);
        $returnData["partyUserTop"] = $partyUserTop;
        $returnData["image"] = one_domain_image($giftinfo["image"]);
        $returnData["gif_image"] = one_domain_image($giftinfo["special"]);

        Db::commit();
        $this->success("赠送成功！",$returnData);

    }

    /**
     * 用户赠送礼物后房间内用户排行，贡献榜前三名
     */
    private function getPartyUserTop($party_id) {
        $redis = new Redis();
        $redisconfig = config("redis");
        $redis->connect($redisconfig["host"], $redisconfig["port"]);

        $userModel = new \app\common\model\User();
        // 获取条数
        $num = 3;
        // 获取3条财富排行周记录
        $getweek = $redis->zRevRange("livebc_jewel_to_".$party_id,0,$num-1,true);
        $userList = $userModel->rankList($getweek);

        $avatarArr = [];
        if($userList) {
            foreach($userList as $k => $v) {
                $v["jewel"] > 0 && $avatarArr[] = $v["avatar"];
            }
            // 加入缓存做备份
            $redis->hSet("user_jewel_top3",$party_id,json_encode($avatarArr));
        }
        return $avatarArr;
    }

    //准备返回数据，刷礼物的总值，刷礼物人数，榜一信息
    public function outlivebc(){
        $party_id = Db::name('party')->where(['user_id'=>$this->auth->id,'room_type'=>2])->value('id');

        $redis = new Redis();
        $redisconfig = config("redis");
        $redis->connect($redisconfig["host"], $redisconfig["port"]);

        // 获取财富排行 全部
        $getweek = $redis->zRevRange("livebc_jewel_to_".$party_id,0,-1,true);

        $userinfo = [];
        if(!empty($getweek)){
            $userid = array_keys($getweek)[0];
            $userinfo = Db::name('user')->field('id,username,nickname,avatar,gender')->where('id',$userid)->find();
            $userinfo = info_domain_image($userinfo,['avatar']);
        }

        $rs = [
            'gift_value' => array_sum($getweek),
            'gift_user'  => count($getweek),
            'top_userinfo' => $userinfo,
        ];

        $this->success('success',$rs);
    }



}
