<?php

namespace app\common\library;

use addons\epay\library\Service;
use app\common\model\school\Area;
use app\common\model\school\classes\VirtualHead;
use app\common\model\school\classes\VirtualUser;
use bw\Common;

/**
 *  虚拟数据工具类
 */
class Virtual
{

    /** 获得虚拟昵称
     * @return mixed|string
     */
    public function getNickName(){
        $str = config("site.virtual_nickname");
        $arr = explode("##",$str);
        $r = rand(0,sizeof($arr));
        return $arr[$r];
    }

    public function getVirtualUser($num=10,$classes_lib_id = 0,$time=null,$set=false){
        if(!is_numeric($time)) $time =  strtotime($time); //日期字符格式化时间戳

        $users = [];
        if(!$time)$time = time();
        //mysql随机查询$num个数据
        $virtualHead  = VirtualHead::orderRaw("rand()")->limit($num)->select();
        //随机获得$num个虚拟用户昵称和头像
        foreach($virtualHead as $k=>$v) {
            $nickname = $this->getNickName();
            $head = $v->head_image;
            $r = rand(($time - 86400*7),$time);

            $users[] = [
                "nickname"=>$nickname,
                "head_image"=>$head,
                "time"=>$r,
                "jointype" => "1",
//                "havetype" => "".($k % 2)
                "havetype" => "0" //只要非已报名数据
            ];
        }

        if(!$set){
            return $users;
        }else{

            $user_data=[];
            foreach($users as $k=> $user) {
                $r = rand(($time - 86400*7),$time);
                $user_data[] = [
                    "nickname"=>$user["nickname"],
                    "head_image"=>$user["head_image"],
                    "classes_lib_id"=>$classes_lib_id,
                    "time"=>$r,
                    "jointype" => "1",
                    "havetype" => $user["havetype"]
                ];
            }
            (new VirtualUser)->saveAll($user_data);

              \app\common\model\school\classes\ClassesLib::update_classes($classes_lib_id);
            return $user_data;
        }

    }


    public static function getWeekByTime($time){
        $time = $time && !is_numeric($time) ? strtotime($time) : time();

        //得到当前日期所在周几
        $week = date("w",$time);
        $week = $week == 0 ? '7' : $week;
        $sub =  abs(7-( 7-$week)) -1; //绝对值
        $start_time = $time - ($sub*86400);
//        var_dump( date("Y-m-d",$start_time));
        $titles = ["周一","周二","周三","周四","周五","周六","周日"];
        //循环7天
        $week_arr = [];
        for($i=0;$i<7;$i++){
            $week_arr[$i]['active'] = false;
            $week_arr[$i]['start_time'] = $start_time + ($i*86400);
            $week_arr[$i]['end_time'] = strtotime("+1 day",$week_arr[$i]['start_time']) -1 ;

            $week_arr[$i]['start_date'] = date("Y/m/d H:i:s",$week_arr[$i]['start_time']);
            $week_arr[$i]['end_date'] = date("Y/m/d H:i:s",$week_arr[$i]['end_time']);



            $week_arr[$i]['day_text'] = date("m.d",$week_arr[$i]['start_time']);


            $week_arr[$i]['week'] = $i+1;
            $week_arr[$i]['week_text'] = $titles[$i];
            if($week_arr[$i]['week'] == $week){
                $week_arr[$i]['active'] = true;
            }
        }

        return  $week_arr;
    }


    public static function visitNnmberUpdate(){
        $key = "night_school_total_visit";
        $redis = (new \bw\Redis())->getRedis();
            if (!$redis->exists($key)) {
              $redis->set($key, 0);     // 缓存 五秒
            }
        // 进行累加
        return $redis->incr($key);
    }

        public static function getVisitNnmber(){
        $key = "night_school_total_visit";
        $redis = (new \bw\Redis())->getRedis();
        return $redis->get($key);

    }


    public static function getNowCity(){
         $address_city = config("site.the_city");
        //按/符号分割
        $the_city = explode("/",$address_city);
        //初始化省市区变量
        $province = $city = $area = null;
        $province_code = $city_code = $area_code = 0;
        //只分割出一个为省
         //只分割出两个为省和市
        //分割出三个为省、市、县
        if(count($the_city)==1){
            $province = $the_city[0];
        }elseif(count($the_city)==2){
            $province = $the_city[0];
            $city = $the_city[1];
        }elseif(count($the_city)==3){
            $province = $the_city[0];
            $city = $the_city[1];
            $area = $the_city[2];
        }
        //省市区分别模糊查询区域编码表获取编码
        if($province) $province_code = Area::where("level",1)->where("name","like","%$province%")->value("id");
        if($city) $city_code = Area::where("level",2)->where( "pid",$province_code)->where("name","like","%$city%")->value("id");
        if($area) $area_code = Area::where("level",3)->where( "pid",$city_code)->where("name","like","%$area%")->value("id");
       return [
            "address_city"=>$address_city,
            "province"=>$province,
            "city"=>$city,
            "area"=>$area,
            "province_code"=>$province_code,
            "city_code"=>$city_code,
            "area_code"=>$area_code
        ];
    }


    public static function getPath($key,$params=[],$expression = '{{KEYWORD}}'){
       $wx_miniapp_path = config("site.wx_miniapp_path");
       if(!$wx_miniapp_path) throw new \Exception("请先配置小程序路径");
       if(!isset($wx_miniapp_path[$key])) throw new \Exception("请先配置小程序路径");
       $path = $wx_miniapp_path[$key];
       // 参数替换
       $template = Common::parsePrintTemplateString($path,$params,$expression);
       return $template;
    }

    public static function getMiniQrcodeLink($key,$params=[],$expression = '{{KEYWORD}}'){
        $path = self::getPath($key,$params,$expression);
        //如果路径开头有斜杠则去除
        if(substr($path,0,1) == "/"){
            $path = substr($path,1);
        }
        //解析该路径，获取url参数和除去参数的url
        $url_params = [];
        $url = "";
        if(strpos($path,"?") !== false){
            $url_params = explode("?",$path);
            $url = $url_params[0];
            $url_params = $url_params[1];
        }else{
            $url = $path;
        }


        $q_params = [];
        //生成小程序二维码
        $query = $url_params;
       $q_params["path"] = $url;
       if($query)$q_params["query"] = $query;

        // 实例对应的接口对象
        $scheme = new \WeMini\Scheme(Service::wechatConfig());
        $res=  $scheme->urlLink($q_params);
        if(!isset($res["url_link"]))throw new \Exception("生成小程序二维码失败");
        $url_link = $res["url_link"];
        //链接生成二维码
        //二维码
       $response = Common::getQrcode([
            'text'           => $url_link,
            'size'           => 200,
        ],false,false,true);
        //全返回
        return compact("url_link","response");
    }







}