<?php
defined( 'IN_WEB') or die( 'Include Error!');

/**
 * 消息
 * Class ModelMessage
 * Created by: Owen
 * Created on: 2019/8/29 17:29
 * Description:
 */
class ModelMessage{
    public $maxTime = 7 * 24 * 60 * 60;
    /**
     * 获取当前用户的消息数量 -- 未读
     * @param $uid
     * @return false|int|string
     * Created by: Owen
     * Created on: 2019/8/29 17:34
     * Description:
     */
    public function getTotalNum($uid){
        $uid = intval($uid);
        if(empty($uid)){
            $data = array('code' => -1,'desc'=>'参数错误！');
            return json_encode($data);
        }
        //查询所有未读的消息
        $table = otable::messageLog($uid);
        $time  = time() - $this->maxTime;
        $sql = " SELECT count(*) AS count FROM {$table} WHERE `uid` = $uid AND `time` > {$time} AND `is_read`=0  order by time desc";
        $ret = oo::commonOprDb('message_log')->getOne($sql, MYSQLI_ASSOC);
        if($ret){
            return $ret['count'];
        }else{
            return 0;
        }
    }

    /**
     * 好友申請數量
     * @param $uid
     * @return int
     * Created by: Owen
     * Created on: 2019/9/4 18:34
     */
    public function getFriApplyNum($uid){
        $time = time() - $this->maxTime;
        $date = date('Y-m-d H:i:s',$time);
        $ftb = otable::friendLog();
        $sql = "SELECT count(*) as count FROM {$ftb} WHERE `touid` = {$uid} AND created_at > '{$date}' AND status=0";
        $ret = oo::commonOprDb('userfriendlog')->getOne($sql, MYSQLI_ASSOC);
        if($ret){
            return $ret['count'];
        }else{
            return 0;
        }
    }

    /**
     * 增加消息
     * @param $uid
     * @param $toUid
     * @param $nick
     * @param $s_picture
     * @param $gbaseReward
     * @param $is_read
     * @param $petSkill
     * @param $type 1 偷，2盾牌，3、4建筑，6支付，7邀請，8、9寵物，10邀请码进入,11召回好友成功消息 12挖雷奖励
     * Created by: Owen
     * Created on: 2019/9/4 18:53
     */
    public function addMessage($uid,$toUid,$nick,$s_picture,$gbaseReward,$type,$is_read = 0,$petSkill = []){
        $tb = otable::messageLog($uid);
        $start_time = time();
        $end_time = $start_time + $this->maxTime;
      	$nick = str_replace("\\","",$nick);
        $nick = str_replace("'","\'",$nick);
        $tempPetSkill = 0;
        if(!empty($petSkill[1]) && $petSkill[1] != 0){
            $tempPetSkill = $petSkill[1];
        }
        if(isset($petSkill['petGetExp'])){
            $tempPetSkill = intval($petSkill['petGetExp']);
        }
        oo::commonOprDb('common')->query("INSERT INTO {$tb} (uid, toUid, name, s_picture, num, type, is_read, time, exp_time, bubble,petSkill) VALUES({$uid},{$toUid},'{$nick}','{$s_picture}',{$gbaseReward},{$type},{$is_read}, {$start_time},{$end_time},0,{$tempPetSkill})");
        $data = [
            'uid'       => $uid,
            'toUid'     => $toUid,
            'name'      => $nick,
            's_picture' => $s_picture,
            'num'       => $gbaseReward,
            'type'      => $type,
            'is_read'   => $is_read,
            'time'      => $start_time,
            'exp_time'  => $end_time,
            'bubble'    => 0,
            'petSkill'  => $tempPetSkill,
        ];
        if($type != 6){
            $friends = oo::commonOprModel('friend')->getUserAllFriend($uid);
            $data    = array_merge($data,$this->getMessageData($toUid,$friends,['petSkill'=>$tempPetSkill]));
        }
        oo::commonOprModel('Workerman')->push($uid,ocmd::$redPoint,['type'=>4,"data"=>$data]);
    }

    /**
     * 消息中心--宠物消息
     * @param $uid
     * @param $toUid
     * @param $nick
     * @param $s_picture
     * @param $type
     * Created by: Owen
     * Created on: 2020/3/19 18:11
     */
    public function addPetMessage($uid,$toUid,$nick,$s_picture,$type){
        $tb = otable::messageLog($uid);
        $start_time = time();
        $end_time = $start_time + $this->maxTime;
        $nick = str_replace("\\","",$nick);
        $nick = str_replace("'","\'",$nick);
        $sql = "INSERT INTO {$tb} (uid, toUid, name, s_picture,num,type, time, exp_time) VALUES($uid,$toUid,'$nick','$s_picture',0,$type,$start_time,$end_time)";
        oo::commonOprDb('common')->query($sql);
        $data = [
            'uid'       => $uid,
            'toUid'     => $toUid,
            'name'      => $nick,
            's_picture' => $s_picture,
            'num'       => 0,
            'type'      => $type,
            'is_read'   => 0,
            'time'      => $start_time,
            'exp_time'  => $end_time,
            'bubble'    => 0,
            'petSkill'  => 0,
        ];
        $data = array_merge($data,$this->getMessageData($toUid,oo::commonOprModel('friend')->getUserAllFriend($uid)));
        oo::commonOprModel('Workerman')->push($uid,ocmd::$redPoint,['type'=>4,"data"=>$data]);
    }

    /**
     * 重构消息列表
     * @param $uid
     * @return array
     * Created by: Owen
     * Created on: 2020/3/6 15:50
     */
    public function getMessageList($uid){
        if(empty($uid)){
            return ['code' => -1,'desc'=>'参数错误！'];
        }
        $tb      = otable::messageLog($uid);
        $minTime = $time = time() - $this->maxTime;
        $list    = oo::commonOprDb('message_log')->getAll("SELECT * FROM {$tb} WHERE `uid`={$uid} AND `time`>={$time} ORDER BY time DESC LIMIT 30", MYSQLI_ASSOC);
        $readArrId = [];
        $friends = oo::commonOprModel('friend')->getUserAllFriend($uid);
        $attackAndStealLimit=0;
        foreach ($list as $k=>$v){
            //打偷消息只显示10条
            if(in_array($v['type'],[1,2,3])){
                $attackAndStealLimit++;
                if($attackAndStealLimit>10){
                    unset($list[$k]);
                    continue;
                }
            }
            !$v['is_read'] && array_push($readArrId,$v['id']);
            $v['type'] != 6 && $list[$k] = array_merge($list[$k],$this->getMessageData($v['toUid'],$friends,$v));
            $list[$k]['from'] = "messgae";
            $minTime = $v['time'];
        }

        !empty($readArrId) && $this->changeMessageReadStatus($uid,$readArrId);

        $ftb     = otable::friendLog();
        $minTime = date("Y-m-d H:i:s",$minTime);
        $review  = oo::commonOprDb('userfriendlog')->getAll("SELECT * FROM {$ftb} WHERE `touid`={$uid} AND created_at>'{$minTime}' ORDER BY created_at DESC", MYSQLI_ASSOC);
        foreach ($review as $k=>$v){
            $temp = $this->getApplyFriendMessageData($uid,$v['touid'],$v);
            !empty($temp) && $list[] = $temp;
        }
        if(!empty($list)){
            array_multisort(array_column($list,'time'),SORT_DESC,$list);
        }
        return ['code' => 1,'desc'=>'获取列表成功','data'=>$list];
    }

    /**
     * 删除消息
     * Created by: Owen
     * Created on: 2020/3/6 16:02
     */
    public function delMessgae(){
        $time = time() - $this->maxTime;
        $created_at = date("Y-m-d H:i:s",$time);
        for ($i=0;$i<100;$i++){
            $tb  = otable::messageLog($i);
            oo::commonOprDb('message_log')->query("DELETE FROM {$tb} WHERE `time`<{$time}");
        }
//        $ftb = otable::friendLog();
//        oo::commonOprDb('userfriendlog')->query("DELETE FROM {$ftb} WHERE `created_at`<'{$created_at}'");
    }

    /**
     * 消息数据结构
     * @param $uid
     * @param array $friends
     * @param array $vData
     * @return array
     * Created by: Owen
     * Created on: 2020/12/25 11:47
     */
    public function getMessageData($uid,$friends = [],$vData = []){
        $memberInfo = oo::commonOprModel('member')->getUserInfo($uid);
        $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($uid);
        return [
            'u_flag'    => $memberInfo['u_flag'],
            'vip'       => $memberInfo['vip'],
            'vipLv'     => $memberInfo['vipLv'],
            'vipExpire' => $memberInfo['vip_expire'],
            'avatar'    => intval($memberInfo['avatar']),
            'isFb'      => intval($memberInfo['isFb']),
            'sex'       => intval($memberInfo['sex']),
            'signature' => intval($memberInfo['signature']),
            'isFbFriend'=> (in_array($uid,$friends) && $memberInfo['isFb'])?1:0,
            'isFriend'  => (in_array($uid,$friends))?1:0,
            'levelId'   => intval($assetsInfo['levelId']),
            'star'      => intval($assetsInfo['star']),
            'money'     => intval($assetsInfo['money']),
            'coins'     => intval($assetsInfo['money']),
            'petSkill'  => intval($vData['petSkill']),
        ];
    }

    /**
     * 好友消息结构
     * @param $uid
     * @param $toUid
     * @param array $vData
     * @return array
     * Created by: Owen
     * Created on: 2020/12/25 11:29
     */
    public function getApplyFriendMessageData($uid,$toUid,$vData = []){
        $memberInfo = oo::commonOprModel('member')->getUserInfo($toUid);
        if(!empty($memberInfo)){
            $assetsInfo = oo::commonOprModel('member')->getUserAssetsInfo($toUid);
            if(!empty($assetsInfo)){
                return [
                    'is_read'  => 1,
                    'name'     => oo::commonOprModel('member')->getUserFirstName($memberInfo['nick']),
                    'num'      => 0,
                    's_picture'=> $memberInfo['s_picture'],
                    'time'     => empty($vData['created_at']) ? time() : strtotime($vData['created_at']),
                    'toUid'    => $memberInfo['uid'],
                    'type'     => 5,
                    'u_flag'   => $memberInfo['u_flag'],
                    'vip'      => $memberInfo['vip'],
                    'vipLv'    => $memberInfo['vipLv'],
                    'vipExpire'=> $memberInfo['vip_expire'],
                    'avatar'   => $memberInfo['avatar'],
                    'uid'      => $uid,
                    'from'     => 'friend',
                    'status'   => empty($vData['status']) ? 0 : $vData['status'],
                    'isFb'     => $memberInfo['isFb'],
                    'sex'      => $memberInfo['sex'],
                    'signature'=> $memberInfo['signature'],
                    'isFbFriend'=> 0,
                    'isFriend'=> 0,
                    'petSkill'=> 0,
                    'levelId' => intval($assetsInfo['levelId']),
                    'star'    => intval($assetsInfo['star']),
                    'money'   => intval($assetsInfo['money']),
                    'coins'   => intval($assetsInfo['money']),
                ];
            }
        }
        return [];
    }

    /**
     * 设置已读
     * @param $uid
     * @param $arrId
     * @return string
     * Created by: Owen
     * Created on: 2020/12/25 15:15
     */
    public function changeMessageReadStatus($uid,$arrId = []){
        $tb = otable::messageLog($uid);
        if(!empty($arrId)){
            $arrId = implode(',',$arrId);
            oo::commonOprDb('message_log')->query("UPDATE {$tb} SET `is_read`=1 WHERE id IN ({$arrId})");
        }else{
            oo::commonOprDb('message_log')->query("UPDATE {$tb} SET `is_read`=1 WHERE uid={$uid}");
        }
        return oo::response(1);
    }


    //===========================邮件系统===========================
    /**
     * 钻石自动转换成体力系统邮件
     * @return array
     */
    private function getDiamondToSysMailInfo() {
        return [
            'body'  => [
                'EN' => "To bring you better gaming experiences, the gem system will be officially canceled in the next version.\r\n\r\nTo avoid your losses, your Gems have been automatically 1:1 converted into Spins. Please collect here. \r\nWe sincerely apologize for the inconvenience caused to you. If you have any questions, please do not hesitate to contact our customer service team.\r\nThank you！",
                "ZH" => "为了给您带来更好的游戏体验，宝石系统将会在下个版本中正式取消。\r\n为了避免您的损失，您的宝石被自动1:1兑换为体力进行返还。 请在这里收集您的体力。\r\n给您带来的不便，我们深表歉意。 如果您有任何问题，请与我们的客户服务团队联系。\r\n谢谢您！",
                "FR" => "Pour vous offrir de meilleures expériences de jeu, le système GEM sera officiellement annulé dans la prochaine version.\r\n\r\nPour éviter des pertes, vos GEM ont été automatiquement 1:1 converties en Spins. Veuillez récupérer ici. \r\n\r\nNous vous présentons nos sincères excuses pour le désagrément qui vous a été causé. Si vous avez des questions, n\'hésitez pas à contacter notre service client.\r\n\r\nMerci!",
                "DE" => "Um Ihnen ein besseres Spielerlebnis zu bieten, wird das Edelstein-System in der nächsten Version offiziell abgeschafft.\r\n\r\n Um Ihre Verluste zu vermeiden, wurden Ihre Edelsteine automatisch 1:1 in Drehungen umgewandelt. Bitte sammeln Sie diese hier ein. \r\n\r\nWir entschuldigen uns aufrichtig für die Unannehmlichkeiten. Bei Fragen können Sie sich gerne an unseren Kundenservice wenden. \r\n\r\nVielen Dank!",
            ],
            "title" => [
                'EN' => 'Dear Voyager',
                'ZH' => '亲爱的旅行者',
                'FR' => 'Cher voyageur',
                'DE' => 'Liebe Reisende',
            ],
            "langs" => ["ZH","EN","TW","FR","PT","DE","ES","TH","ID","VI","NO"],
        ];
    }

    public function getDiamondToSpinsNum($diamond = 0){
        //return $diamond; //1:1兑换
        if($diamond <= 10){
            $diamond = 10;
        } elseif($diamond <= 50){
            $diamond = 50;
        } elseif($diamond <= 100){
            $diamond = 100;
        } else {
            $diamond = $diamond;
        }
        return $diamond;
    }

    /**
     * 钻石转化成体力更新公告
     * @param int $uid
     * @param int $diamond
     * @return bool
     */
    public function diamondToSysMail($uid, $diamond = 0) {
        //$switch = oo::commonOprRedis('userinfo')->get(okeys::sysMsgGetNSatus());
        //if(empty($switch) && $diamond > 1000){
        //    return [];
        //}
        if($diamond > 0){
            $diamond = $this->getDiamondToSpinsNum($diamond);
        }
        //领取状态(2:已领取,1:可领取,0:未读)
        $dCache = $this->getDiamondToSysMail($uid);
        if($diamond > 0){
            //有奖励且未领取,在原基础上加
            if(isset($dCache['status']) && !$dCache['status'] && !empty($dCache['props'])){
                $diamond += $dCache['props'][0]['num'];
            }
            $dCache = ['props'=>[['propsId' => '15','num' => (int)$diamond]], 'status' => 0];
            $ret = oo::commonOprRedis('userinfo')->setex(okeys::sysMsgGetN($uid), json_encode($dCache), 30 * 24 * 3600);
        } else {
            if(empty($dCache)){
                return [];
            }
        }
        $got = $dCache['status'];
        $data = $this->getDiamondToSysMailInfo();
        $rewardInfo = [
            'title'   => $data['title'],
            'body'    => $data['body'],
            'langs'   => $data['langs'],
            'rewards' => $dCache['props'],
            'msgid'   => 1000001, //给默认值
            'id'      => 1000001, //给默认值
            'got'     => $got,
        ];
        return $rewardInfo;
    }

    public function getDiamondToSysMail($uid) {
        $key = okeys::sysMsgGetN($uid);
        $tmp = oo::commonOprRedis('userinfo')->get($key);
        return empty($tmp) ? [] : (array)json_decode($tmp, true); 
    }

    /**
     * 设置钻石转换体力已领取
     * @param int $uid
     * @param int $flag (1:已读,2:已领)
     * @return bool
     */
    public function setDiamondNoticeStatus($uid, $flag = 1) {
        $key = okeys::sysMsgGetN($uid);
        $tmp = oo::commonOprRedis('userinfo')->get($key);
        if(empty($tmp)){
            return true;
        }
        $dCache = (array)json_decode($tmp, true);
        if(empty($dCache)){
            oo::logs()->debug3(['uid' => $uid, 'flag' => $flag, 'data' => $dCache], 'diamond_to_sysmail_log');
            oo::commonOprRedis('userinfo')->delete($key);
            return true;
        }
        $flag = !in_array($flag, [1, 2]) ? 2 : $flag;
        $dCache['status'] = $flag;
        return (bool)oo::commonOprRedis('userinfo')->setex($key, json_encode($dCache), 30 * 24 * 3600);
    }

    /**
     * 获取系统配置的邮件内容
     * @param int $uid
     * @return array
     */
    public function getSysMailMsg() {
        $key = okeys::sysMailMsg();
        $cacheArr = oo::commonOprRedis('common')->hGetAll($key);
        $msgs = [];
        if(empty($cacheArr)){
            $tb    = otable::sysMailMsg();
            $time  = time() - 15 * 24 * 3600; //15天之前的内容不读了
            $sql   = "SELECT * FROM {$tb} WHERE create_time > {$time} order by id desc";
            $list  = oo::commonOprDb('config')->getAll($sql, 1);
            $upArr = [];
            foreach($list as $v){
                $v['title']      = (array)json_decode($v['title'], true);
                $v['body']       = (array)json_decode($v['body'], true);
                $v['langs']      = (array)json_decode($v['langs'], true);
                $v['rewards']    = (array)json_decode($v['rewards'], true);
                $v['uids']       = (array)json_decode($v['uids'], true);
                $v['version']    = explode(',', $v['version']);
                $upArr[$v['id']] = json_encode($v);
                $msgs[] = $v;
            }
            oo::commonOprRedis('common')->hMSet($key, $upArr);
            $a = oo::commonOprRedis('common')->hGetAll($key);
            //设置过期时间
            oo::commonOprRedis('common')->expire($key, oo::redisRandomExpire(20 * 24 * 3600));
        }else{
            krsort($cacheArr);
            foreach($cacheArr as $k => $v){
                $v = json_decode($v, true);
                $msgs[] = $v;
            }
        }
        return $msgs;
    }

    /**
     * 获取我的系统邮件
     * @param
     */
    public function getMySysMail($uid, $id = 0) {
        $key = okeys::sysMsgGet($uid);
        $cacheArr  = oo::commonOprRedis('user')->hGetAll($key);
        $arr = [];
        $time = time();
        if(empty($cacheArr)){
            $tb = otable::userSysMail($uid);
            //$sql = "SELECT * FROM {$tb} WHERE uid={$uid} AND expire > {$time}";
            $expired  = $time - 30 * 24 * 3600; //30天之前的内容不读了
            $sql = "SELECT * FROM {$tb} WHERE uid={$uid} AND create_time > {$expired}";
            $tmp = oo::commonOprDb('usersysmail')->getAll($sql, MYSQLI_ASSOC);
            $upArr = [];
            foreach($tmp as $k => $v){
                $v['rewards'] = $v['rewards'] ? (array)json_decode($v['rewards'], true) : [];
                $arr[$v['msgid']] = $v;
                $msgId = $v['msgid'];
                unset($v['msgid']);
                $upArr[$msgId] = json_encode($v);
            }
            if($upArr){
                oo::commonOprRedis('user')->hMSet($key, $upArr);
                //个人邮件保留7天
                oo::commonOprRedis('user')->expire($key, oo::redisRandomExpire(7 * 24 * 3600));
            }
        }else{
            foreach($cacheArr as $k => $v){
                $v = json_decode($v, true);
                $arr[$k] = $v;
            }
        }

        /////////////////////////////////////////////
        //存量钻石转化系统邮件
        $diamondInfo = $this->diamondToSysMail($uid);
        if($id == 1000001) {
            return $diamondInfo;
        }

        if(!empty($id)){
            return isset($arr[$id]) ? $arr[$id] : [];
        }
        $arr[1000001] = $diamondInfo;
        return $arr;
    }

    /**
     * 获取玩家对应的系统消息
     * @param int $uid
     * @return array
     * Created by: Richard
     * Created on: 2021/03/03 12:20
     */
    public function getSysMailMsgByUid($uid, $sid = 0, $lasttime = 0) {
        $list = $this->getSysMailMsg();
        $levelId = oo::commonOprModel('member')->getUserLevelId($uid);
        $version = oo::commonOprModel('user')->getUserVersion($uid);
        $userinfo = oo::commonOprModel('member')->getUserInfo($uid);
        if(empty($lasttime)){
            $lasttime = $userinfo['lasttime'];
        }
        $vipPoint = empty($userinfo['vipPoint']) ? 0 : $userinfo['vipPoint'];

        $myMsgArr = $this->getMySysMail($uid);

        $key = okeys::sysMsgGet($uid);

        $sid = empty($sid) ? oo::getDefinedSid($uid) : $sid;
        $lang = ''; //玩家所在国家
        $msgs = [];
        $newNum = 0;
        $sql = '';
        $tb = otable::userSysMail($uid);
        $time = time();

        //钻石存量转系统邮件数据
        if(!empty($myMsgArr[1000001])){
            $tmp = $myMsgArr[1000001];
            $tmp['id'] = 1000001;
            $tmp['expire'] = 24 * 3600 * 30;
            $list[] = $myMsgArr[1000001];
        }

        foreach($list as $v){
            if(!empty($myMsgArr[$v['id']])){
                if(!empty($myMsgArr[$v['id']]['expire']) && $myMsgArr[$v['id']]['expire'] < $time){
                    continue; //过期的邮件
                }
                $v['got'] = $myMsgArr[$v['id']]['got'];
                $info = [
                    'id'          => $v['id'],
                    'title'       => $v['title'],
                    'body'        => $v['body'],
                    'rewards'     => $myMsgArr[$v['id']]['rewards'],
                    'got'         => $v['got'],
                    'expire'      => isset($myMsgArr[$v['id']]['expire']) ? $myMsgArr[$v['id']]['expire'] : time(),
                    'create_time' => empty($v['create_time']) ? $time : $v['create_time'],
                ];

                $msgs[] = $info;
                if(empty($v['got'])){
                    $newNum++;
                }
                continue;
            }

            if(!empty($v['online_start']) && $lasttime < $v['online_start']){
                continue;
            }
            if(!empty($v['online_end']) && $lasttime > $v['online_end']){
                continue;
            }

            //uid列表
            if(!empty($v['uids']) && !in_array($uid, $v['uids'])){
                continue;
            }
            //版本
            if(!empty($v['version'][0]) && !oo::compareVersion($version, $v['version'][0])){
                continue;
            }

            if(!empty($v['version'][1]) && oo::compareVersion($version, $v['version'][1], false)){
                continue;
            }

            //玩家等级区间
            if(($v['level_start'] && $levelId < $v['level_start']) || ($v['level_end'] && $levelId > $v['level_end'])){
                continue;
            }
            //积分区间
            if(($v['score_start'] && $vipPoint < $v['score_start']) || $v['score_end'] && $vipPoint > $v['score_end']){
                continue;
            }
            //设备
            if(!empty($v['sid']) && $sid != $v['sid']){
                continue;
            }
            //国家语言
            if(!empty($v['langs'])){
                $lang = $lang ? $lang : oo::commonOprModel('member')->getUserLang($uid);
                if(!in_array($lang, $v['langs'])){
                    continue;
                }
            }
            if(empty($v['days'])){
                continue;
            }
            $rewards = $v['rewards'];
            $newNum++;
            $t = json_encode($rewards);
            $up = ['got' => 0, 'uid' => $uid, 'expire' => $time + 24 * 3600 * $v['days'], 'rewards' => $rewards, 'create_time' => $time];
            //写入数据库
            oo::commonOprRedis('user')->hSet($key, $v['id'], json_encode($up));
            if($sql){
                $sql .= ",(NULL,{$uid},{$v['id']},0,'{$t}',{$up['expire']},{$time})";
            }else{
                $sql = "REPLACE INTO {$tb} (id,uid,msgid,got,rewards,expire,create_time) VALUES (NULL,{$uid},{$v['id']},0,'{$t}',{$up['expire']},{$time})";
            }

            $info = [
                'id'          => $v['id'],
                'title'       => $v['title'],
                'body'        => $v['body'],
                'rewards'     => $rewards,
                'got'         => 0,
                'expire'      => $up['expire'],
                'create_time' => $time,
            ];

            if(!empty($id) && $v['id'] == $id){
                return $info;
            }
            $msgs[] = $info;
        }

        if($sql){
            $ret = oo::commonOprDb('usersysmail')->query($sql);
            if(empty($myMsgArr) && $newNum > 0){
                oo::commonOprRedis('user')->expire($key, oo::redisRandomExpire(7 * 24 * 3600));
            }
        }

        $data = ['msgs' => $msgs, 'newNum' => $newNum];
        return $data;
    }

    /**
     * 获取邮件奖励
     * @param int $id
     * @param int $uid
     * @return array
     * Created by: Richard
     * Created on: 2021/03/03 12:20
     */
    public function getUserMailMsgReward($uid, $id) {
        $key = okeys::sysMsgGet($uid); //领取状态
        $info = $this->getMySysMail($uid, $id);
        $data = ['code' => errorCode::SUCCESS];
        if(empty($info)){
            $data['code'] = errorCode::NONE_REWARD;
            $data['msg'] = 'no msg found';
            return json_encode($data);
        }
        if($info['got'] == 2){
            $data['code'] = errorCode::OVER_RECEIVE_REWARD;
            return json_encode($data);
        }
        $reason = '获取系统邮件奖励';
        if($id == 1000001){
            $reason = '钻石转体力邮件奖励';
            $this->setDiamondNoticeStatus($uid, 2);
        } else {
            $info['got'] = 2;
            oo::commonOprRedis('user')->hSet($key, $id, json_encode($info));
            //更新数据库
            $tb = otable::userSysMail($uid);
            $sql = "UPDATE {$tb} set got = 2 WHERE uid = {$uid} AND msgid={$id}";
            $ret = oo::commonOprDb('usersysmail')->query($sql);
            if(!$ret){
                oo::logs()->debug3(['uid' => $uid, 'id' => $id], 'sysmail_reward_error');
                $data['code'] = errorCode::SYSTEM_ERROR;
                return json_encode($data);
            }
        }

        foreach($info['rewards'] as $k => $reward){
            oo::commonOprModel('member')->sendReward($uid,$reward['propsId'],$reward['num'],600,$reason);
        }
        $data['rewards'] = $info['rewards'];
        return json_encode($data);
    }

    /**
     * 设置已读
     * @param int $uid
     * @param $id
     * @return bool
     */
    public function readMailMsg($uid, $id) {
        if($id == 1000001){
            return $this->setDiamondNoticeStatus($uid, 1);
        }
        $key = okeys::sysMsgGet($uid);
        $cache = oo::commonOprRedis('user')->hGet($key, $id);
        if(empty($cache)){ //记录不存在
            return false;
        }
        $info = (array)json_decode($cache, true);
        if(!empty($info['got'])){
            return true;
        }
        $info['got'] = 1;
        oo::commonOprRedis('user')->hSet($key, $id, json_encode($info));
        //更新数据库
        $tb = otable::userSysMail($uid);
        $sql = "UPDATE {$tb} set got = 1 WHERE uid = {$uid} AND msgid={$id}";
        return oo::commonOprDb('usersysmail')->query($sql);
    }
}
