<?php

class ModelIpaddress{
    public $countryMaster =['RO','US','DE','GB','ES','FR','IN'];//主要国家：罗马尼亚，美国，德国，英国，西班牙，法国，印度
    public function getUserCountry($uid,$db=false){
        $cache =[];
        $key = okeys::userCountryInfo($uid);
        if(!$db){
           $cache =  oo::commonOprRedis('userinfo')->hGetAll($key);
           oo::commonOprRedis('userinfo')->expire($key,oo::redisRandomExpire(7*86400));
        }
        if(empty($cache)){
            $tb = otable::useraddress();
            $sql = "SELECT * FROM {$tb} where uid={$uid}";
            $info = oo::commonOprDb('userinfo')->getOne($sql,1);
            $info['showCode'] = !empty($info['country_code'])&&in_array($info['country_code'],$this->countryMaster)?$info['country_code']:'OTHER';
            if(isset($info['uid'])&&!empty($info['uid'])){
                oo::commonOprRedis('userinfo')->hMset($key,$info);
                oo::commonOprRedis('userinfo')->expire($key,oo::redisRandomExpire(7*86400));
                $cache = $info;
            }
        }
        return $cache;
    }

    public function updateUserCountry($data){

    }

    /**
     * Notes:新写用户ip缓存队列
     * User: wsc
     * Time: 2020/5/19 16:01
     * @param $uid
     * @param $ip
     * @param int $type  1写入 2更新 3失败的
     */
    public function intoIpList($uid,$ip,$type=1){
        $arr = ["uid"=>$uid,"ip"=>$ip];
        $res = 0;
        if(!empty($arr['uid'])){//&&!empty($arr['ip'])
            $key = okeys::newUserIpList($type);
            $json = json_encode($arr);
            $res = oo::commonOprRedis('common')->rPush($key,$json);
            if(!$res){
                oo::logs()->debug3(["type"=>4,"data"=>'入队失败，data:'.$json,"res"=>$res],'getIpErr');
            }
        }
        return $res;
    }

    /**
     * Notes:定时消费更新用户地址信息
     * User: wsc
     * Time: 2020/5/29 15:05
     * @return bool
     */
    public function updateUserAddressIntoDb(){
        $key = okeys::newUserIpList(2);
        $listJsonArr = oo::commonOprRedis('common')->lGetRange($key,0,99);
        $list = funs::getArrFromJsonArr($listJsonArr);
        $tb = otable::useraddress();
        if(!empty($list)){
            foreach ($list as $k=>$v){
                $arr =[];
                $setdata='';
                $arr = $this->getAddressByIp($v['uid'],$v['ip']);
                if(isset($arr['country_code'])&&!empty($arr['country_code'])){
                        $setdata = "country_code='{$arr['country_code']}',";
                }
                if(isset($arr['continent'])&&!empty($arr['continent'])){
                    $setdata .= "continent='{$arr['continent']}',";
                }
                if(isset($arr['country'])&&!empty($arr['country'])){
                    $setdata .= "country='{$arr['country']}',";
                }
                if(!empty($setdata)){
                    $setdata = rtrim($setdata, ',');
                    $sql = "update {$tb} SET {$setdata} where uid={$v['uid']}";
                    oo::commonOprDb('userinfo')->query($sql,false);
                }
                oo::commonOprRedis('common')->lRemove($key,$listJsonArr[$k],1);
            }
        }else{
           return  false;
        }
        return true;
    }

    /**
     * Notes:定时消费队列入库
     * User: wsc
     * Time: 2020/5/19 16:01
     */
    public function writeUserAddressIntoDB(){
        $key = okeys::newUserIpList(1);
        $listJsonArr = oo::commonOprRedis('common')->lGetRange($key,0,99);
        $list = funs::getArrFromJsonArr($listJsonArr);
        $errData=$res=[];
        if(!empty($list)){
            $value ='';
            foreach ($list as $k=>$v){
                $arr = $this->getAddressByIp($v['uid'],$v['ip']);
                $arr_values  = array_values($arr);
                $value =" ('" . implode("','" ,$arr_values) . "')";
                oo::commonOprRedis('common')->lRemove($key,$listJsonArr[$k],1);
                $sql = "INSERT INTO crazygod_api_user.t_useraddress(uid,ip,continent,country,country_code)values $value";
                $res[$v['uid']] =oo::commonOprDb('common')->query($sql);
            }
//            oo::logs()->debug3(["type"=>3,"data"=>$list,"res"=>$res],'getIp');
        }
        return true;
    }
    /**
     * Notes:获取ip地址信息
     * User: wsc
     * Time: 2020/5/19 16:02
     * @param $uid
     * @param $ip
     * @return array
     */
    public function getAddressByIp($uid,$ip,$t=0){
        $data =[
            'uid'         =>$uid,
            'ip'          =>$ip,
            'continent'   =>"",
            'country'     =>"",
            'country_code'=>""
        ];
        if(!empty($ip)&&$ip!='127.0.0.1') {
            $res = funs::ip_info($ip);
            if (!empty($res)) {
                $data['continent'] = isset($res['continent']) ? $res['continent'] : '';
                $data['country'] = isset($res['country']) ? $res['country'] : '';
                $data['country_code'] = isset($res['country_code']) ? $res['country_code'] : '';
            } else if(!$t) {//失败的ip入队到备份ip列表
                $this->intoIpList($uid, $ip, 3);
            }
        }
        return $data;
    }

    public function setUserAddress($uid,$ip){
        $ret = [];
        $data = $this->getAddressByIp($uid,$ip);
        if(!empty($data)){
            $sql = funs::db_insertSQL(otable::useraddress(),$data);
            $res =oo::commonOprDb('common')->query($sql);
            if($res){
                $ret = $this->getUserCountry($uid);
            }
        }
        return $ret;
    }
}
