<?php

namespace app\common\model\school\classes;

use app\common\model\BaseModel;
use think\Model;


class VisitDistribution extends BaseModel
{

    

    

    // 表名
    protected $name = 'school_visit_distribution';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'index_text',
        'statistics_time_text'
    ];
    

    
    public function getIndexList()
    {
        return ['access_source_session_cnt' => __('Index access_source_session_cnt'), 'access_staytime_info' => __('Index access_staytime_info'), 'access_depth_info' => __('Index access_depth_info')];
    }


    public function getIndexTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['index']) ? $data['index'] : '');
        $list = $this->getIndexList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatisticsTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['statistics_time']) ? $data['statistics_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setStatisticsTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public static function setlog($begin_date,$end_date,$res){
        if(!isset($res["ref_date"]) || !isset($res["list"]))return false;
        //statistics_time = 开始时间的时间戳
         //begin_date 和 end_date如果带字符串‘-’ 则去除
        $begin_date = str_replace("-","",$begin_date);
        $end_date = str_replace("-","",$end_date);
        $data = [
            "ref_date"=>$res["ref_date"],
            "begin_date" =>$begin_date,
            "end_date" =>$end_date,
            "miniapp_id"=>config("site.wx_miniapp_id"),
            "statistics_time" => strtotime($res["ref_date"]." 0:0:0"),
        ];

       $list = $res["list"];
        foreach ($list as $k=>$v){
            if(isset($v['index']) && isset($v['item_list'])){
                     foreach ($v['item_list'] as $kk=>$vv){
                         $data["index"] = $v['index'];
                         $data["key"] = $vv['key'];
                         $data["value"] = $vv['value'];
//                         var_dump(!self::where($data)->find());
                         if(!self::where($data)->find()){

                             self::create($data);
                         }
                     }
            }
        }
    }

}
