<?php

namespace app\index\controller;

use think\Controller;

use Redis;
use think\Db;
use app\common\library\Easemob;
class Plantask extends Controller
{
    //关于本文件里的计划任务
    //只有 public 方法，auto_开头的才是计划任务，其他private 方法都是工具方法

////////////////////////////////////////下面都是计划任务方法///////////////////////////////////////////////////////////////


    //送礼物(api/party/giveGiftToYou)拆分出来的异步用户升级方法,
    public function auto_user_level_up(){
        Db::startTrans();
        $tasklist = Db::name('gift_user_party')->where('task_status',0)->limit(20)->lock(true)->select();
        if(empty($tasklist)){
            Db::rollback();
            echo 'empty';
            exit;
        }

        try {
            //redis
            $redis = new Redis();
            $redisconfig = config("redis");
            $redis->connect($redisconfig["host"], $redisconfig["port"]);
            if ($redisconfig['redis_pwd']) {
                $redis->auth($redisconfig['redis_pwd']);
            }
            if($redisconfig['redis_selectdb'] > 0){
                $redis->select($redisconfig['redis_selectdb']);
            }

            $money_to_jewel = config('site.money_to_jewel') ?: 10; //余额兑换金币
//            $getempirical_conf = config("site.getempirical");

            foreach($tasklist as $key => $giftuserparty){
                echo $giftuserparty['id'].'<br>';

                $giftValue = $giftuserparty['value'];
                $hotValue  = $giftValue;

                //用户信息
                $authuser_info = Db::name('user')->field('nickname')->where('id',$giftuserparty['user_id'])->find();
                $touserInfo    = Db::name('user')->field('nickname')->where('id',$giftuserparty['user_to_id'])->find();
                $party_id = $giftuserparty['party_id'];


                //添加获赠用户余额
                $user_id = $giftuserparty['user_to_id'];
                if($giftuserparty['getvalue'] > 0){
                    $getMoney = bcdiv($giftuserparty['getvalue'],$money_to_jewel,2);
                    if($getMoney > 0){
                        $rs_wallet = model('wallet')->lockChangeAccountRemain($user_id,$getMoney,'+',0,"{$authuser_info['nickname']}送你{$giftuserparty['gift_name']}x{$giftuserparty['number']}",101,'money');
                        if($rs_wallet['status'] == false){
                            Db::rollback();
                            $this->error($rs_wallet['msg']);
                        }
                    }
                }
                $partyInfo = \app\common\model\Party::field("id,room_type,party_name,party_hot,user_id,platRate,guilderRate,easemob_room_id")->where(["id"=>$giftuserparty['party_id']])->find();
                //增加房主抽成
                if ($partyInfo && $giftuserparty['guildervalue'] > 0) {
                    $guilderMoney = bcdiv($giftuserparty['guildervalue'],$money_to_jewel,2);
                    if($guilderMoney > 0){
                        $rs_wallet = model('wallet')->lockChangeAccountRemain($partyInfo->user_id,$guilderMoney,'+',0,"{$authuser_info['nickname']}送礼物{$giftuserparty['gift_name']}x{$giftuserparty['number']}给{$touserInfo['nickname']},房间礼物抽成",102,'money');
                        if($rs_wallet['status'] == false){
                            Db::rollback();
                            $this->error($rs_wallet['msg']);
                        }
                    }
                }

                //更新麦位魅力值
                $this->updateSeatCharm($partyInfo['easemob_room_id'],$giftuserparty['seat_num'],$hotValue,$partyInfo);

                // 如果是主播，则添加魅力值记录做榜单统计,这个表和送礼物日志表重复了，无意义
                /*if($partyInfo) {
                    $data = [];
                    $data["user_id"] = $giftuserparty['user_to_id'];
                    $data["party_id"] = $party_id;
                    $data["charm"] = $hotValue;
                    $data["createtime"] = time();
                    \app\common\model\UserCharmRank::insert($data);

                }*/

                //用户经验升级
                //$getempirical = $getempirical_conf * $hotValue;
                // 获取用户贵族信息
                /*$noble = \app\common\model\User::getUserNoble($giftuserparty['user_id']);
                if(isset($noble["noble_on"]) && $noble["noble_on"] == 1) {
                    $getempirical = $getempirical + $getempirical * ($noble["explain"]/100);
                }*/

                // 增加用户经验值
                //$res = \app\common\model\User::addEmpirical($giftuserparty['user_id'],$getempirical);
                /*if ($res){
                    $this->auth->level = $res->level;
                }*/

                //增加被送礼物用户的魅力等级
                $res_charm = \app\common\model\User::add_charm_level($giftuserparty['user_to_id'],$giftValue);

                // +exp
//                \app\common\model\TaskLog::tofinish($giftuserparty['user_id'],"OBHqCX4g",$giftuserparty['number']);

                // +message
                \app\common\model\Message::addMessage($giftuserparty['user_to_id'],"礼物通知","收到 ".$authuser_info['nickname']." 赠送的".$giftuserparty['gift_name']." x".$giftuserparty['number']." 价值 ".$giftValue ." 金币");

                //增加送礼用户的财富等级
                $res_wealth = \app\common\model\User::add_wealth_level($giftuserparty['user_id'],$giftValue);

                // tcp 获取房间用户周前三名 getPartyUserTop里面摘出来的一部分
                //[环信]更新财富榜前3。
                $avatarArr = $redis->hGet("user_jewel_top3",$partyInfo['id']);
                $easemob = new Easemob();
                $matedata = [
                    'wealth_top3_userlist'  => $avatarArr,
                ];
                $easemob->room_setRoomCustomAttributeForced($partyInfo['easemob_room_id'],$partyInfo['user_id'],$matedata);

                //结束
                $rs_up = Db::name('gift_user_party')->where('id',$giftuserparty['id'])->update(['task_status'=>1]);
                if($rs_up === false){
                    Db::rollback();
                    echo '更新错误'.$giftuserparty['id'];
                    exit;
                }
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

/////////////////////////////////////////下面都是工具方法////////////////////////////////////////////////

    /**
     *  用户赠送礼物后房间内麦位魅力值增加,更新到麦位自定义信息
     * $seatnum 座位数字 1，不是键名 seat1
     */
    private function updateSeatCharm($easemob_room_id,$seatnum,$giftValue,$party_info) {
        //获取已有信息
        $key = 'seat'.$seatnum;
        $easemob = new Easemob();
        $seatdata = $easemob->room_getRoomCustomAttribute($easemob_room_id,[$key]);

        if(empty($seatdata)){
            //默认为空
            $seatdata = [
                'charm'    => 0,                    //红心，魅力值

                'isMaster'       => false,            // 是否是房主
                'headUrl'        => '',              // 头像
                'userNo'         => '',               // 座位上用户no
                'rtcUid'         => '',               // 座位上用户id，与rtc的userId一致
                'name'           => '',                 // 座位上用户昵称
                'seatIndex'      => $seatnum,               // 座位编号
                'chorusSongCode' => '',             // 是否合唱
                'isAudioMuted'   => 1,            // 是否静音
                'isVideoMuted'   => 0,            // 是否开启视频
                'checked'        => false,       // 用于送礼物选择用户
                'isUsed'         => true,          // 用于送礼物选择用户
                'gender'         => 1, //性别
            ];
        }else{
            $seatdata = json_decode($seatdata[$key],true);
        }

        //魅力值自增
        $seatdata['charm'] = intval($seatdata['charm']);
        $seatdata['charm'] += $giftValue;

        //重新设置
        $matedata = [
            $key  => json_encode($seatdata),
        ];
        $easemob->room_setRoomCustomAttributeForced($easemob_room_id,$party_info['user_id'],$matedata);

        return true;
    }


}
