<?php

namespace app\common\library;


use addons\epay\library\Service;
use app\common\model\BaseModel;
use app\common\model\manystore\Shop;
use app\common\model\school\Area;
use app\common\model\school\classes\activity\Activity;
use app\common\model\school\classes\ClassesLib;
use app\common\model\school\classes\hourorder\Order;
use app\common\model\school\classes\Teacher;
use app\common\model\school\classes\Type;
use app\common\model\school\classes\Visit;
use app\common\model\school\classes\VisitDistribution;
use app\common\model\User;

/**
 *  夜校大数据类
 */
class NightSchoolBigData extends BaseModel
{


    public static function getAreaBaseData($province,$city,$district){
       $have_time = false;
       if($district)$have_time = true;

       $whereArea = function ($query)use($province,$city,$district){
           $query = $query->where('1=1');
          if( $province)$query = $query->where('province',$province);
          if( $city)$query = $query->where('city',$city);
          if( $district)$query = $query->where('district',$district);
       };
       //统计当前课程总数
        $classes_num = ClassesLib::where($whereArea)->count();

        $activity_num = Activity::where($whereArea)->count();
        if($have_time){
            //统计当前总报名人数
            $classes_sign_num = ClassesLib::where($whereArea)->sum('sign_num');
        }else{
            //统计当前总报名人数
            $classes_sign_num = (config("site.sign_up_toal_number")?:0) + ClassesLib::where($whereArea)->sum('sign_num');

        }


        $activity_sign_num = Activity::where($whereArea)->sum('sign_num');

       //认证讲师数量
        $shop_ids = implode(",",Shop::where($whereArea)->column("id"));

        if($shop_ids){
            $teacher_num = Teacher::where('shop_id','in',$shop_ids)->count();
            //近七天报名数量
            $classes_sign_num_7 =   Order::where("shop_id",'in',$shop_ids)->where("status","in",["-1","0","3"])->whereTime('createtime', 'between', [strtotime("-7 day"), time()])->count();
            $activity_sign_num_7 =  \app\common\model\school\classes\activity\order\Order::where("shop_id",'in',$shop_ids)->whereTime('createtime', 'between', [strtotime("-7 day"), time()])->where("status","not in",["-3","6"])->count();
        }else{
            $teacher_num = Teacher::count();
            $classes_sign_num_7 =   Order::where("status","in",["-1","0","3"])->whereTime('createtime', 'between', [strtotime("-7 day"), time()])->count();
            $activity_sign_num_7 =  \app\common\model\school\classes\activity\order\Order::whereTime('createtime', 'between', [strtotime("-7 day"), time()])->where("status","not in",["-3","6"])->count();
        }
        //所有课程累计访问
        $classes_views = ClassesLib::where($whereArea)->sum('views');

        $activity_views = Activity::where($whereArea)->sum('views');

        //注册总人数
        $user_num = (config("site.register_total_numebr")?:0) + User::count();
        //总点击
        $visitn_nmber = Virtual::getVisitNnmber();

        return compact(  "activity_views","activity_sign_num" , "activity_sign_num_7","user_num","activity_num","visitn_nmber",'classes_num','classes_sign_num','teacher_num','classes_sign_num_7','classes_views');
    }


    /** 累计报名人数
     * @return
     */
    public static function accumulatedNumberOfApplicants(){
            //得到所有类型课程类型
        $types = Type::where("status",'1')->select();
        foreach ($types as &$type){
            $type["classes_views"] = ClassesLib::where("classes_type",$type["id"])->sum('views');

            $type["classes_sign_num"] = ClassesLib::where("classes_type",$type["id"])->sum('sign_num');
            $type["classes_num"] = ClassesLib::where("classes_type",$type["id"])->count();
        }
        return $types;
    }


    public static function getAreaData($province,$city){
        $model = new Area();
        if($province && !$city){
            $model = $model->where("pid",$province)->where("level",2);
        }elseif ($city){
            $model = $model->where("pid",$city)->where("level",3);
        }else{
            $model = $model->where("level",1);
        }
        $data = $model->order('id asc')->field('id as value, name as label, pid, level')->select();
        return $data;
    }

    public static function getAreaDataLevel($province,$city){
        if($province && !$city){
            $level = "city";
        }elseif ($city){
            $level = "district";
        }else{
            $level = "province";
        }
        return $level;
    }



    /** 各区域上课数量和上课人数
     *
     */
    public static function numberOfClassesInEachRegion($province,$city,$time=null){
        $areas = self::getAreaData($province,$city);
        $level = self::getAreaDataLevel($province,$city);
        foreach ($areas as &$area){
            $classes_num_model = new ClassesLib;
            if ($time){
                $classes_num_model = $classes_num_model->time(["createtime",$time]);
            }
            //课程数量
            $area["classes_num"] = $classes_num_model->where($level,$area["value"])->count();
            if ($time){
                $classesLibIds = implode(",",ClassesLib::where($level,$area["value"])->column('id'));
                $area["classes_sign_num"] = Order::where("classes_lib_id",'in',$classesLibIds)->where("status","in",["-1","0","3"])->time(["createtime",$time])->count();
            }else{
                $area["classes_sign_num"] = ClassesLib::where($level,$area["value"])->sum('sign_num');
            }

            //结束时间过了当前时间为往期课程
            // 往期直接统计限定人数
//            $area["classes_sign_num_past"] = ClassesLib::where($level,$area["value"])->where("end_time","<",time())->sum('limit_num');
//
//            //非往期课程统计报名人数
//            $area["classes_sign_num"] = ClassesLib::where($level,$area["value"])->where("end_time",">=",time())->sum('sign_num');
//            $area["classes_sign_num"] = $area["classes_sign_num"]+$area["classes_sign_num_past"];
//            unset( $area["classes_sign_num_past"]);
        }

        return $areas;
    }



    /** 七天内报名人数
     * @return
     */
    public static function accumulatedSevenNumberOfApplicants(){
        //得到所有类型课程类型
        $types = Type::where("status",'1')->select();

        //得到从今天开始往前七天的每天的开始和结束时间
        $dates = [];
        for ($i=0;$i<7;$i++){
            $date = [
                "today"=>false,
                "start"=>strtotime("-".$i." day",strtotime(date("Y-m-d 0:0:0",time())) ),
                "end"=>strtotime("-".($i-1)." day",strtotime(date("Y-m-d 0:0:0",time())))-1,
            ];
            $date["text"] = date("m.d",$date["start"]);
            if ($i==0){
                $date["today"] = true;
                $date["text"] = "今日";
            }
            $dates[] = $date;
        }
        $dates = array_reverse($dates);
        $type_data = [];
       foreach ($dates as &$time){
           foreach ($types as &$type){

               $classesLibIds = implode(",",ClassesLib::where("classes_type",$type["id"])->column('id'));
               if(!isset($type_data[$type["id"]]))$type_data[$type["id"]]= $type->toArray();
                //加入时间查询条件
               $type_data[$type["id"]]["classes_sign_num"][] = Order::where( "createtime",'between',[$time["start"],$time["end"]])->where("classes_lib_id",'in',$classesLibIds)->where("status","in",["-1","0","3"])->count();

               $type_data[$type["id"]]["classes_nums"][] = ClassesLib::where( "createtime",'between',[$time["start"],$time["end"]])->where("classes_type",$type["id"])->count();
           }
       }

        return compact("dates","type_data");
    }

    /**前N名累计活跃课程
     *
     */
    public static function topNCumulativeActiveCourses($N){
          //浏览量views 前N的课程
        $classes_views = ClassesLib::field( "id,title,views,sign_num,weigh")->order("views desc,sign_num desc,id desc")->limit($N)->select();
       return ["classes_views"=>$classes_views];
    }



    /** 七天内活动报名人数和活跃热度
     * @return
     */
    public static function accumulatedSevenNumberOfActivity(){

        //得到从今天开始往前七天的每天的开始和结束时间
        $dates = [];
        for ($i=0;$i<7;$i++){
            $date = [
                "today"=>false,
                "start"=>strtotime("-".$i." day",strtotime(date("Y-m-d 0:0:0",time())) ),
                "end"=>strtotime("-".($i-1)." day",strtotime(date("Y-m-d 0:0:0",time())))-1,
            ];
            $date["text"] = date("m.d",$date["start"]);
            if ($i==0){
                $date["today"] = true;
                $date["text"] = "今日";
            }
            $dates[] = $date;
        }
        $dates = array_reverse($dates);
        $type_data = [];
        foreach ($dates as &$time){
                //加入时间查询条件
            $type_data["activity_sign_num_text"] = "报名人次";
            $type_data["activity_num_text"] = "活动热度";
                $type_data["activity_sign_num"][] = \app\common\model\school\classes\activity\order\Order::where( "createtime",'between',[$time["start"],$time["end"]])->where("status","not in",["-3","6"])->count();
                $type_data["activity_num"][] = Activity::where( "createtime",'between',[$time["start"],$time["end"]])->count();
                $type_data["activity_views"][] = Visit::where("status",'2')->where( "createtime",'between',[$time["start"],$time["end"]])->count();
        }

        return compact("dates","type_data");
    }




    public static function getLastSevenDaysDate($time=null){
        //如果是非数字，转成时间戳
        if ($time &&!is_numeric($time)){
            $time = strtotime($time);
        }


        if(!$time)$time = time();
//           var_dump($time);
        //时间如果是当天，需要减去一天
        if (date("Ymd",$time)==date("Ymd",time())){
            $time = strtotime("-1 day",$time);
        }

//        //得到当前是几号
//        $day = date("d",$time);
//        //用7进行除余，得到余数和整数商
//        $mod = $day%7;
//        //进行除7，截取整数部分(不需要向下或向上取整！)
//        $day = $day-$mod;
//        $last_seven = bcdiv($day,7,0);
//        //如果=0.取上个月的最后一个七天
//        if ($last_seven<=0){
//            //得到上月最后一天 date('Y-m-d H:i');
//            $last_mouth_last_day = strtotime(date("Y-m-01 00:00:00",$time))-1;
//            $start_date = date("Ymd",strtotime("-6 days",$last_mouth_last_day));
//            $end_date = date("Ymd",$last_mouth_last_day);
//        }
        //如果>0,则取本月第$last_seven 个七天
//        if ($last_seven>0){
//            $last_seven_days = $last_seven * 7;
            $start_date = date("Ymd",strtotime("-6 days",$time));
            $end_date = date("Ymd",$time);

//            $start_date = date("Ymd",strtotime("+".($last_seven_days-7)." days",strtotime(date("Y-m-01 00:00:00",$time))));
//            $end_date = date("Ymd",strtotime("+".($last_seven_days-1)." days",strtotime(date("Y-m-01 00:00:00",$time))));
//        }
      return compact("start_date","end_date");
    }


    public static function getLastThirtyDaysDate($time=null){
        //如果是非数字，转成时间戳
        if ($time &&!is_numeric($time)){
            $time = strtotime($time);
        }
        if(!$time)$time = time();
        //时间如果是当天，需要减去一天
        if (date("Ymd",$time)==date("Ymd",time())){
            $time = strtotime("-1 day",$time);
        }

        $start_date = date("Ymd",strtotime("-29 days",$time));
        $end_date = date("Ymd",$time);

        return compact("start_date","end_date");
    }





    public static function getLastMonthDate($time=null){
        //如果是非数字，转成时间戳
        if ($time &&!is_numeric($time)){
            $time = strtotime($time);
        }


        if(!$time)$time = time();
//           var_dump($time);
        //时间如果是当天，需要减去一天
        if (date("Ymd",$time)==date("Ymd",time())){
            $last_time = strtotime("-1 month",$time);
            $start_date = date("Ym01",$last_time);
            $last_mouth_last_day = strtotime(date("Y-m-01 00:00:00",$time))-1;
            $end_date = date("Ymd",$last_mouth_last_day);

        }else{

            //如果=0.取上个月的最后一个七天
            $start_date = date("Ym01",$time);
            $last_time = strtotime("+1 month",$time);
            $last_mouth_last_day = strtotime(date("Y-m-01 00:00:00",$last_time))-1;
            $end_date = date("Ymd",$last_mouth_last_day);
        }



        return compact("start_date","end_date");
    }




    public static function getLastDaysDate($time=null){
        //如果是非数字，转成时间戳
        if ($time &&!is_numeric($time)){
            $time = strtotime($time);
        }

        if(!$time)$time = time();
//           var_dump($time);
        //时间如果是当天，需要减去一天
        if (date("Ymd",$time)==date("Ymd",time())){
            $time = strtotime("-1 day",$time);
        }

            $start_date = date("Ymd",$time);
            $end_date = date("Ymd",$time);

        return compact("start_date","end_date");
    }




    public static function getLastWeekDate($time=null){
        //如果是非数字，转成时间戳
        if ($time &&!is_numeric($time)){
            $time = strtotime($time);
        }


        if(!$time)$time = time();
//           var_dump($time);

        if (date("Ymd",$time)==date("Ymd",time())){
            $last_time = strtotime("-1 week",$time);
        }else{
            $last_time = $time;
        }


        //得到$last_time 的周一日期
        $start_date_time = strtotime("-".(date("w",$last_time)-1)." day",$last_time);
        $start_date = date("Ymd",$start_date_time);
        //得到$last_time 的周日日期
        $end_date = date("Ymd", strtotime("+6 days",$start_date_time));



        return compact("start_date","end_date");
    }


    public static function visitDistribution($start_time=null,$end_time=null){
        $wheretime= [[]];
        if($start_time && $end_time){
            if(!is_numeric($start_time)) $start_time = strtotime($start_time);
            if(!is_numeric($end_time)) $end_time = strtotime($end_time);
            $wheretime= [ "statistics_time",'between',[$start_time,$end_time]];
        }
        $res  = [];
        $data = [];
        $data["46"] = VisitDistribution::where("index","access_source_session_cnt")->where("key","46")->sum("value");

        $data["29"] = VisitDistribution::where("index","access_source_session_cnt")->where("key","29")->sum("value");
        $data["2"] = VisitDistribution::where("index","access_source_session_cnt")->where("key","2")->sum("value");
        $data["total"] = VisitDistribution::where("index","access_source_session_cnt")->sum("value");
        $data["sum"] = $data["46"] + $data["29"] + $data["2"];
        $res['access_source_session_cnt'] = $data;
        return $res;

    }

}