<?php
class userModule extends commonModule
{
    public function __construct()
    {
        parent::__construct("sl_user");
    }
    /**
     * Notice: 获取用户信息
     * Date: 2019年6月10日11:55:48
     * @author dyj
     */
    //获取用户等级


    //登录、注册参数验证
    public function verLoginData($request){

        //参数验证
        if (empty($request["phone"])){
            returnFail([],getcodestr(3002),3002);
        }
        if (empty($request["code"])){
            returnFail([],getcodestr(3007),3007);
        }

        //验证验证码是否正确
        $where_code = "user = '{$request['phone']}'";
        $code = (new smslogModel())->orderBy("dtime desc")->where($where_code)->one();
        //是否获取验证码
        if (empty($code)){
            returnFail([],getcodestr(3010),3010);
        }
        //验证码是否过期
        if (time() > strtotime($code["dtime"]) + 5 * 60){
            returnFail([],getcodestr(3009),3009);
        }
        //验证码是否正确
        if ($request["code"] != $code["log"]){
            returnFail([],getcodestr(3008),3008);
        }

        //验证通过，判断是否是新用户
        $user = $this->getInfoByTel($request["phone"]);
        if (empty($user)){ //非新用户，直接调用登录
            //创建用户编号
            $user_number = $this->createUserNumber();
            $data = [
                "number" => $user_number,
                "nickname" => "用户".$request["phone"],
                "phone" => $request["phone"],
                "state" => 1,                   //默认账号状态有效
                "is_certification" => 2,        //默认未实名认证
                "is_ban" => 2,                  //默认未被禁播
                "is_deleted" => 2,              //默认未被删除
                "is_vip" => 2,                  //默认不是贵族
                "noble_currency" => 0,          //默认贵族币为0
                "noble_integral" => 0,          //默认贵族积分为0
                "is_push" => 1,                 //默认消息推送
                "code" => $user_number,         //默认邀请码为用户编号
                "experience" => 0,              //经验值0
                "sex" => 1,                     //默认性别保密
                "type" => 1,                    //默认类型普通用户
                "created_time" => date("Y-m-d H:i:s"),
                "update_time" => date("Y-m-d H:i:s")
            ];

            //新建用户
            $register = $this->insert($data);
            if (!$register){    //用户创建失败
                returnFail([],getcodestr(3011),3011);
            }
        }

        return true;

    }

    //根据手机号查询用户信息
    public function getInfoByTel($phone){
        $data = $this->where(["phone"=>$phone])->one();
        return $data;
    }

    //生成用户编号
    public function createUserNumber(){
        $number = time().rand(0,99);
        //查询所有用户的number
        $user_number = $this->getAllUserNumber();
        //查询所有靓号的number
        $user_beautiful = (new beautifulNumberModule())->getAllUserNumber();
        $user_number_all = array_unique(array_merge($user_number,$user_beautiful));
        if (in_array($number,$user_number_all)){
            $this->createUserNumber();
        }else{
            return $number;
        }
    }

    //查询所有用户的number
    public function getAllUserNumber(){
        $data = $this->find("number")->all();
        $number = [];
        foreach ($data as &$v){
            $number[] = $v["number"];
        }
        return $number;
    }

    //绑定用户手机号
    public function bandUserPhone($data){
        $arr  = $this->where(['number'=>$data['user_number']])->update($data);
        return $arr;
    }

    //根据用户编号查询用户信息
    public function getUserInfoByNumber($user_number){

        //查询用户信息
        $user_info = $this->where(["number"=>$user_number])->one();

        if (!empty($user_info)){

            //查询关注
            $userShieldingModule = new userShieldingModule();
            $follow = $userShieldingModule->getUserFollowNum($user_number);
            //查询粉丝
            $fans = $userShieldingModule->getUserFansNum($user_number);
            //查询今日印票数
            $gift = (new userGiftLogModule())->getOneDayGift($user_number);
            //查询用户等级
            $level = (new userLevelModule())->getUserLevelByExp($user_info["experience"]);
            //查询小视频
            $short_video = (new shortVideoModule())->getVideoCount($user_number);
            //查询最近来访数量
            $lately_visit_total = (new userHistoryModule())->where(["usered_number" => $user_number])->count();
            $lately_visit_not_see = (new userHistoryModule())->where(["usered_number" => $user_number,"is_see" => 2])->count();
            //计算用户年龄
            $age = $this->birthday($user_info["birthday"]);
            $age = !empty($age)?$age:1;

            //组装数据
            $data = [
                "follow" => $follow,    //关注数
                "fans" => $fans,        //粉丝数
                "gift" => $gift,        //当日礼物总计
                "level" => $level,      //当日礼物总计
                "short_video" => $short_video,      //当日礼物总计
                "lately_visit_total" => $lately_visit_total,      //最近来访总量
                "lately_visit_not_see" => $lately_visit_not_see,      //最近来访未被查看
                "age" => $age,      //年龄
            ];

            $user_info = array_merge($user_info,$data);
        }


        return $user_info;
    }

    //根据用户ID查询用户信息
    public function getUserInfoByUserId($id){

        //查询用户信息
        $user_info = $this->where(["id"=>$id])->one();

        if (!empty($user_info)){
            $user_number = $user_info["number"];
            //查询关注
            $userShieldingModule = new userShieldingModule();
            $follow = $userShieldingModule->getUserFollowNum($user_number);
            //查询粉丝
            $fans = $userShieldingModule->getUserFansNum($user_number);
            //查询今日印票数
            $gift = (new userGiftLogModule())->getOneDayGift($user_number);
            //查询用户等级
            $level = (new userLevelModule())->getUserLevelByExp($user_info["experience"]);
            //查询小视频
            $short_video = (new shortVideoModule())->getVideoCount($user_number);
            //查询最近来访数量
            $lately_visit_total = (new userHistoryModule())->where(["usered_number" => $user_number])->count();
            $lately_visit_not_see = (new userHistoryModule())->where(["usered_number" => $user_number,"is_see" => 2])->count();
            //计算用户年龄
            $age = $this->birthday($user_info["birthday"]);
            $age = !empty($age)?$age:1;

            //组装数据
            $data = [
                "follow" => $follow,    //关注数
                "fans" => $fans,        //粉丝数
                "gift" => $gift,        //当日礼物总计
                "level" => $level,      //当日礼物总计
                "short_video" => $short_video,      //当日礼物总计
                "lately_visit_total" => $lately_visit_total,      //最近来访总量
                "lately_visit_not_see" => $lately_visit_not_see,      //最近来访未被查看
                "age" => $age,      //年龄
            ];

            $user_info = array_merge($user_info,$data);
        }


        return $user_info;
    }

    //用户开播验证用户信息
    public function verOpenLive($user_info,$request){

        //判断用户是否认证与被禁播
        if ($user_info["is_certification"] == 2){ //用户未认证
            returnSuccess([],getcodestr(4003),4003);
        }
        if ($user_info["is_ban"] == 1){ //用户已被禁播
            returnSuccess([],getcodestr(4004),4004);
        }

        //验证开播参数信息
        if (empty($request["title"])){ //直播间标题
            returnSuccess([],getcodestr(4005),4005);
        }
//        if (empty($request["cover"])){ //直播封面图
//            returnSuccess([],getcodestr(4006),4006);
//        }
        if (empty($request["type"])){ //直播分类
            returnSuccess([],getcodestr(4007),4007);
        }
        if (empty($request["url"])){ //直播分类
            returnSuccess([],getcodestr(4012),4012);
        }

        //查询用户是否正在直播
        $live_info = (new userLiveLogModule())->getOneByWhere(["live_type"=>1,"user_number"=>$user_info["number"]]);
        if (!empty($live_info)){
            returnSuccess([],getcodestr(4009),4009);
        }

        return true;
    }

    //计算年龄
    public function birthday($birthday){
        $age = strtotime($birthday);
        if($age === false){
            return false;
        }
        list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
        $now = strtotime("now");
        list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
        $age = $y2 - $y1;
        if((int)($m2.$d2) < (int)($m1.$d1))
            $age -= 1;
        return $age;
    }

    //禁播主播
    public function ban($number){
        $data = $this->where(["number"=>$number])->update(["is_ban"=>1]);
        return $data;
    }

    //搜索用户信息
    public function getUserList($text){
        $text = trim($text);
        $data = $this->findBySql("select * from sl_user where number like '%{$text}%' or nickname like '%{$text}%' order  by id desc");
        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['leavel'] = (new userLevelModule())->getUserLevelByExp($v["experience"]);
                $data[$k]['leavel'] = $data[$k]['leavel']['leavel_name'];
            }
        }
        return $data;
    }

    //获取用户收益数据
    public function getAnchorProfit($request,$user){
        //参数验证
        if (empty($request["type"]) || !in_array($request["type"],[1,2])){
            returnSuccess([],getcodestr(3018),3018);
        }
        if (empty($request["date"])){
            returnSuccess([],getcodestr(3019),3019);
        }

        //查询数据
        $userLiveLogModule = new userLiveLogModule();
        if ($request["type"] == 1){ //日数据
            $date_begin = $request["date"]." 00:00:00";
            $date_finish = $request["date"]." 23:59:59";
            $where = "user_number = {$user} and create_time between '$date_begin' and '$date_finish'";
            $log = $userLiveLogModule->where($where)->all();
        }else{  //月数据
            $date_info = explode("-",$request["date"]);
            $year = $date_info[0];
            $month = $date_info[1];
            $sql = "select * from sl_user_live_log where user_number = {$user} and year(create_time) = '$year' and month(create_time) = '$month'";
            $log = $userLiveLogModule->findBySql($sql);
        }
        //计算直播时长、印币收入、送礼人数
        $live_time = 0;
        $coin = 0;
        $give_count = [];
        $userGiftLogModule = new userGiftLogModule();
        foreach ($log as &$v){
            //直播时长
            $create_time = $v["create_time"];
            $finish_time = $v["finish_time"];
            $time = strtotime($finish_time) - strtotime($create_time);
            $live_time += $time;

            //收礼
            $gift_log = $userGiftLogModule->where("usered_number = {$user} and create_time between '$create_time' and '$finish_time'")->all();
            foreach ($gift_log as &$vv){
                $coin += $vv["price"];
                $give_count[] = $vv["user_number"];
            }
        }

        $data = [
            "live_time" => number_format($live_time / 3600,2),
            "coin" => $coin,
            "give_count" => count(array_unique($give_count))
        ];
        returnSuccess($data,getcodestr(200),200);

    }

}