<?php

class ModelNotice{


    /**
     * Notes:定时公告推送
     * User: wsc
     * Time: 2020/7/13 16:29
     * @param int $type
     * @param bool $do 是否直接推送
     * @return array
     */
    public function cronToSendNotice($type=1,$uid='',$do=false){
        $time =time();
        $data = $this->getNotice($type);
        if($type=1&&!empty($data)){//停服公告
            $sendTime = [30,10,5,1];
            $shortTime = $data['stime']-$time;
            $shortMinute =  $shortTime>0?intval($shortTime/60):-1;
            $ret['content'] =funs::dejson($data['content']);
            if($shortMinute==0||$do==2){//到点
                $ret['stime']= $data['stime'];
                $ret['etime']= $data['etime'];
                if(!empty($uid)){
                    oo::commonOprModel('Workerman')->push($uid,ocmd::$send['Announcement'],$ret);
                }else{
                    oo::commonOprModel('Workerman')->pushAll(ocmd::$send['Announcement'],$ret);
                }
            }
            if(in_array($shortMinute,$sendTime)||$do==1){
                $ret['etime']= $data['stime'];
                $ret['type']=1;
                $ret['systemTips']=0;//持续显示
                if(!empty($uid)){
                    oo::commonOprModel('Workerman')->push($uid,ocmd::$SVR_NOTICE_INFO,$ret);
                }else{
                    oo::commonOprModel('Workerman')->pushAll(ocmd::$SVR_NOTICE_INFO,$ret);
                }
                return true;
            }else{
                return false;
            }
        }
    }

    /**
     * Notes:客户端获取公告
     * User: wsc
     * Time: 2020/7/7 15:49
     * @param $type 1停服公告
     * @return array
     */
    public function clientGetNotice($uid,$type=1){
        $time =time();
        $data = $this->getNotice($type);
        $title   = !empty($data['title'])?funs::dejson($data['title']):[];
        $content = !empty($data['content'])?funs::dejson($data['content']):[];
        $lang = oo::getDefinedLang($uid);
        $lang = strtoupper($lang);
        $ret['title'] = isset($title[$lang])?$title[$lang]:$title['EN'];
        $ret['content'] = isset($content[$lang])?$content[$lang]:$content['EN'];
        $ret['stime'] = $data['stime'];
        $ret['etime'] = $data['etime'];
        $wList = explode(',',$data['wlist']);
        if(empty($data)||$data['stime']-60>$time||$time>$data['etime']||$data['isStop']||in_array($uid,$wList)){
            return [];
        }
        return $ret;
    }

    /**
     * Notes:获取公告
     * User: wsc
     * Time: 2020/7/7 15:49
     * @param string $type
     * @param bool $db
     * @return array
     */
    public function getNotice($type="",$db=false){
        $key  = okeys::serverNotice();
        $tb   = otable::notice();
        $list = oo::commonOprRedis('config')->hGetAll($key);
        $data = funs::getArrFromJsonArr($list);
        if($db){
            $where = '';
            if($type){
                $where = " WHERE type={$type}";
            }
            $sql = "SELECT * FROM {$tb} {$where} ORDER BY stime DESC";
            $result = oo::commonOprDb('config')->getAll($sql,1);
            if(!empty($result)){
                $data = array_column($result,null,'type');
                foreach ($data as $k=>$v){
                    $d = json_encode($v,256);
                    oo::commonOprRedis('config')->hSet($key,$v['type'],$d);
                }
            }
        }
        if(!empty($type)&&!empty($data[$type])){
            $data = $data[$type];
        }
        return $data;
    }

    /**
     * Notes:设置公告
     * User: wsc
     * Time: 2020/7/7 15:49
     * @param $data
     * @return bool
     */
    public function setNotice($data){
        $type = $data['type'];
        $tb = otable::notice();
        $data['content'] = isset($data['content'])?json_encode($data['content'],256):"[]";
        $data['title'] = isset($data['title'])?json_encode($data['title']):"[]";
        if(!empty($this->getNotice($type))){
            unset($data['type']);
            unset($data['id']);
            $w = " type={$type}";
            $sql =funs::db_updateSQL($tb,$data,$w);
        }else{
            $sql = funs::db_insertSQL($tb,$data);
        }
        $res  = oo::commonOprDb('config')->query($sql);
        if($res){
            $this->getNotice($type,true);
            return true;
        }
        return false;
    }
    //==============系统公告====================

    public function getNowAnnouncement($uid){
        $ret = $data=[];
        $list = $this->getAnnouncemant();
        $now = time();
        foreach ($list as $v){
            if(!empty($v['stime'])&&!empty($v['etime'])){//过滤时间
                if($now>=$v['stime']-30&&$now<=$v['etime']){
                    $data = $v;
                    break;
                }
            }
        }
        if(!empty($data)){
            $slInfo = oo::commonOprRedis('userinfo')->hGetAll(okeys::userDefinedInfo($uid));
            $blist = !empty($data['blist'])?explode(',',$data['blist']):[];
            if(in_array($uid,$blist)){//黑名单只要有系统公告就停服
                $data['type']=1;
            }else{
                if($data['device']!=0&&!empty($slInfo['sid'])&&$data['device']!=$slInfo['sid']){//过滤渠道
                    $data =[];
                }
                if($data['usertype']!=0&&!empty($slInfo['lid'])&&$data['usertype']!=$slInfo['lid']){//过滤用户类型
                    $data =[];
                }
                $wlist = !empty($data['wlist'])?explode(',',$data['wlist']):[];
                if(!empty($wlist)&&is_array($wlist)&&in_array($uid,$wlist)){//过滤白名单
                    $data =[];
                }
            }
            if($data){
                $lang = oo::getDefinedLang($uid)??'EN';
                $lang = strtoupper($lang);
                unset($data['id'],$data['wlist'],$data['blist'],$data['device'],$data['usertype']);
                $data['content'] = $data['content'][$lang]?$data['content'][$lang]:$data['content']['EN'];
            }
        }
        return $data;
    }

    /**
     * 1.11新版公告
     * @param int $uid
     * @return array
     */
    public function getNowAnnouncementNew($uid) {
        $key = okeys::announcementReward($uid);
        $ret = oo::commonOprRedis('userinfo')->get($key);
        //if(!empty($ret)){
        //    return (array)json_decode($ret, true);
        //}
        $list = $this->getAnnouncemant(2);
        $now = time();
        $data = [];
        foreach ($list as $v){
            if(!empty($v['stime'])&&!empty($v['etime'])){//过滤时间
                if($now>=$v['stime']-30&&$now<=$v['etime']){
                    $data = $v;
                    break;
                }
            }
        }
        if(empty($data)){
            return [];
        }
        $slInfo = oo::commonOprRedis('userinfo')->hGetAll(okeys::userDefinedInfo($uid));
        if($data['device']!=0&&!empty($slInfo['sid'])&&$data['device']!=$slInfo['sid']){//过滤渠道
            $data =[];
        }
        if(empty($data)){
            return [];
        }
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        //过滤版本
        $dversion =implode('.',array_slice(explode('.',$version),0,3));
        $versions = [];
        if(!empty($data['version']) && is_array($data['version'])){
            foreach ($data['version'] as $v){
                $str = implode('.',array_slice(explode('.',$v),0,3));
                $versions[] = $str;
            }
        }
        if(!empty($versions) && !in_array($dversion,$versions)){
            return [];
        }

        //if($data){
            //$lang = oo::getDefinedLang($uid)??'EN';
            //unset($data['id'], $data['usertype'], $data['admin_user'], $data['version']);
            //$data['content'] = $data['content'][$lang]?$data['content'][$lang]:$data['content']['EN'];
        //}
        $ret = $ret ? (array)json_decode($ret, true) : [];

        $got = !empty($ret['got']) ? (int)$ret['got'] : 0;
        $newVersion = !empty($data['newVersion']) ? $data['newVersion'] : '1.11.1';
        $rewardInfo = [
            'title'      => $data['title'],
            'content'    => $data['content'],
            'version'    => $newVersion,
            'reward'     => $data['reward'],
            'stime'      => $data['stime'],
            'etime'      => $data['etime'],
            'got'        => !empty($ret['got']) ? (int)$ret['got'] : 0,
            'range_desc' => $data['range_desc'],
            'time_desc'  => $data['time_desc'],
        ];
        if(empty($ret)){ //第一次设置值
            //没有领过的新版本都要可领取
            $ret = ['got' => 0, 'version' => $version];
            $expire = $data['etime'] - $now + 3*24*60*60;
            oo::commonOprRedis('userinfo')->setex($key,json_encode($ret),oo::redisRandomExpire($expire));
        }
        return $rewardInfo;
    }

    /**
     * 添加1.11新版公告
     * @param int $flag
     * @return array
     */
    public function getAnnouncemant($flag = 0){
        $key = okeys::announcement($flag);
        $list = oo::commonOprRedis('config')->hGetAll($key);
        if(empty($list)){
            $tb = otable::announcement($flag);
            $sql = "SELECT * FROM {$tb}";
            if($flag == 2){
                $sql .= ' WHERE plat IN(0, 1)'; //过滤fox公告
            }
            $retData = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            foreach ($retData as $k=>$v){
                if($flag){
                    $v['version']    = empty($v['version']) ? [] : (array)json_decode($v['version'], true);
                    $v['title']      = empty($v['title']) ? [] : (array)json_decode($v['title'], true);
                    $v['content']    = empty($v['content']) ? [] : (array)json_decode($v['content'], true);
                    $v['reward']     = empty($v['reward']) ? [] : (array)json_decode($v['reward'], true);
                    $v['time_desc']  = empty($v['time_desc']) ? [] : (array)json_decode($v['time_desc'], true);
                    $v['range_desc'] = empty($v['range_desc']) ? [] : (array)json_decode($v['range_desc'], true);
                }
                $list[$v['id']] = json_encode($v,256);
            }
            oo::commonOprRedis('config')->hMset($key,$list);
        }
        if($list){
            $list = funs::getArrFromJsonArr($list);
        }else {
            $list = [];
        }
        return $list;
    }

    //==============消息类跑马灯管理===========

    /**
     * Notes:跑马灯样板
     * User: wsc
     * Time: 2021/1/20 20:55
     * @param $type
     * @return mixed
     */
    public function msgModel($type){
        $arr['buyVip'] = [
            "type"=>"buyVip",
            "content"=>[
                'ZH'=> '恭喜! <color=#fff220>{0}</color>成为了尊贵的<color=#5afffe>VIP</color>',
                'TW'=> '恭喜! <color=#fff220>{0}</color> 成為了尊貴的<color=#5afffe>VIP</color>',
                'EN'=> 'Congratulations! <color=#fff220>{0}</color> became the <color=#5afffe>VIP</color>!',
                'FR'=> 'Félicitations ! <color=#fff220>{0}</color> a devenu <color=#5afffe>VIP</color>!',
                'DE'=> 'Glückwunsch! <color=#fff220>{0}</color> wurde der <color=#5afffe>VIP</color>!',
            ],
            'conf'=>[]
        ];
        $arr['getCard'] = [
            "type"=>"getCard",
            "content"=>[
                'ZH'=> '哇！<color=#fff220>{0}</color>获得了一张<color=#5afffe>小丑卡</color>！',
                'TW'=> '哇！<color=#fff220>{0}</color>獲得了一張<color=#5afffe>小丑卡</color>！',
                'EN'=> 'Amazing! <color=#fff220>{0}</color> got a <color=#5afffe>Joker Card</color>!',
                'FR'=> 'Parfait ! <color=#fff220>{0}</color> gagne une <color=#5afffe>Carte Joker</color> !',
                'DE'=> 'Toll! <color=#fff220>{0}</color> hat eine <color=#5afffe>Joker-Karte</color> bekommen!',
            ],
            'conf'=>[]
        ];
        $arr['fulCardGroup'] = [
            "type"=>"fulCardGroup",
            "content"=>[
                'ZH'=> '恭喜！<color=#fff220>{0}</color>集齐了<color=#5afffe>{1}</color>卡组！',
                'TW'=> '恭喜！<color=#fff220>{0}</color>集齊了<color=#5afffe>YYY</color>卡組！',
                'EN'=> 'Congratulations! <color=#fff220>{0}</color> completed the <color=#5afffe>{1}</color> set!',
                'FR'=> 'Félicitations ! <color=#fff220>{0}</color> complète <color=#5afffe>{1}</color> set !',
                'DE'=> 'Glückwunsch! <color=#fff220>{0}</color> hat das Set <color=#5afffe>{1}</color> vervollständigt!',
            ],
            'conf'=>[]
        ];
        $arr['getMaxSpins'] = [
            "type"=>"getMaxSpins",
            "content"=>[
                'ZH'=> '太棒了！<color=#fff220>{0}</color>在<color=#1fff2a>{2}</color>中获得了<color=#5afffe>{1}</color>体力！',
                'TW'=> '太棒了！<color=#fff220>{0}</color>在<color=#1fff2a>{2}</color>中獲得了<color=#5afffe>{1}</color>體力！',
                'EN'=> 'Awesome! <color=#fff220>{0}</color> won <color=#5afffe>{1}</color> spins in <color=#1fff2a>{2}</color>!',
                'FR'=> 'Bravo ! <color=#fff220>{0}</color> gagne <color=#5afffe>{1}</color> tours sur <color=#1fff2a>{2}</color>!',
                'DE'=> 'Bravo! <color=#fff220>{0}</color> hat <color=#5afffe>{1}</color> Drehungen im <color=#1fff2a>{2}</color> gewonnen!',
            ],
            'conf'=>["maxSpins"=>1000]
        ];
        $arr['buyCrazyPass']=[
            "type"=>"buyCrazyPass",
            "content"=>[
                'ZH'=> '<color=#fff220>{0}</color> 购买了<color=#5afffe>疯狂通行证</color>',
                'TW'=> '<color=#fff220>{0}</color> 購買了<color=#5afffe>瘋狂通行證</color>',
                'EN'=> '<color=#fff220>{0}</color> purchased <color=#5afffe>Crazy Pass</color>',
                'FR'=> '<color=#fff220>{0}</color> a acheté le <color=#5afffe>Crazy Pass</color>',
                'DE'=> '<color=#fff220>{0}</color> hat <color=#5afffe>Verrückten Pass</color> gekauft',
            ],
            'conf'=>[]
        ];
        return $arr[$type];
    }
    /**
     * Notes:通过类型获取跑马灯配置
     * User: wsc
     * Time: 2021/1/20 15:28
     * @param $type
     * @param bool $db
     * @return array|mixed
     */
    public function getNoticeMsgByType($type){
        $key=okeys::noticeMsg();
        $info = oo::commonOprRedis('config')->hGet($key,$type);
        if(empty($info)){
            $tb = otable::noticeMsg();
            $sql = "SELECT * FROM {$tb} where type ='{$type}'";
            $data = oo::commonOprDb('config')->getOne($sql,1);
            if(!empty($data)){
                $arr['type'] = $data['type'];
                $arr['conf']=json_decode($data['conf'],true);
                $arr['content']=json_decode($data['content'],true);
                $info = str_replace("\/", "/", json_encode($arr,256));
                oo::commonOprRedis('config')->hSet($key,$type,$info);
            }
        }
        return !empty($info)?json_decode($info,true):[];
    }

    /**
     * Notes:
     * User: wsc
     * Time: 2021/1/20 21:58
     * @param $uid
     * @param $type
     * @param array $ext buyVip=[],getCard=[],fulCardGroup=["卡组英文名"],getMaxSpins=["体力值","场景英文名"],buyCrazyPass=[]
     */
    public function sendNoticeMsg($uid,$type,$ext=[],$filter=[]){
        $msgCfg = $this->getAgesCfg($type);
        if($msgCfg['status']!=1){//开关
            return true;
        }
        $info = oo::commonOprModel('member')->getUserInfo($uid);
        if(in_array($type,["buyCrazyPass"])){//循环播放
            $data = [
                "stime"=>time(),
                "etime"=>time()+20,
                "systemTips"=>1,
            ];
        }else{//一次性播放
            $data = ["systemTips"=>0];
        }

        $data["type"]=$type;
        $data['args'] = $ext;
        $nick=oo::commonOprModel('member')->getUserFirstName($info['nick']);
        array_unshift($data['args'],$nick);
        if(funs::concurrentLock(1,'sendNoticeMsg_'.$type,2)){//群播,2秒最多一条 //oo::commonOprRedis('statistics')->exists(okeys::noticeMsgList($type))||
            if($filter){//过滤群播
                $this->filterUserSend($filter,$data);
            }else{
                oo::commonOprModel('Workerman')->pushAll(ocmd::$send['NOTICE_MSG_REC'],$data);//群播所有人
            }
        }else{//单播给自己
            oo::commonOprModel('Workerman')->push($uid,ocmd::$send['NOTICE_MSG_REC'],$data);
        }
    }

    /**
     * Notes:过滤型群播
     * User: wsc
     * Time: 2021/1/21 17:11
     * @param $filter array 过滤群播条件["minLevel"=>"最小等级"]
     * @param $data array 群播数据
     */
    public function filterUserSend($filter,$data){
        $allUid = oo::commonOprModel("workerman")->getAllUidList();//当前机器所有uid
        foreach($allUid as $k => $uid){
            $property = oo::commonOprModel('member')->getUserAssetsInfo($uid);
            $levelId = intval($property['levelId']);
            if($levelId >= $filter['minLevel']){
                oo::commonOprModel('Workerman')->push($uid,ocmd::$send['NOTICE_MSG_REC'],$data);
            }
        }
    }

    /**
     * Notes:获取跑马灯配置
     * User: wsc
     * Time: 2021/1/21 17:01
     * @param $type
     * @return mixed
     */
    public function getAgesCfg($type){
        $info = $this->getNoticeMsgByType($type);
        return $info['conf'];
    }
}
