<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/5/25
 * Time: 上午9:24
 */

namespace statistics;

use Exception;
use DateTime;
use DateInterval;

class stat_base
{
    const cur_date_type    = 1;
    const last_week_type   = 2;
    const last_hmonth_type = 3;
    const last_month_type  = 4;
    const admin_member_id = 36429;

    protected $mStartm;
    protected $mEndtm;
    protected $mDateId;

    protected $mModel;

    public function __construct($stime)
    {
        $this->mModel = Model('stat_daily');

        $stime = intval($stime);
        $this->mDateId = strtotime(date('Y-m-d',$stime));

        if($stime <= 0 || $this->mDateId === false) {
            throw new Exception(__METHOD__ . ' 输入时间错误');
        }
    }

    protected function calc_time($stype)
    {
        $stime = $this->mDateId;
        if($stype == stat_base::cur_date_type)
        {
            $this->mStartm = strtotime(date('Y-m-d',$stime));
            $this->mEndtm  = $this->mStartm + 86400 - 1;
        }
        elseif($stype == stat_base::last_week_type)
        {
            $coord_time = strtotime(date('Y-m-d',$stime)) + 86400;
            $this->mStartm = $coord_time - 86400 * 7;
            $this->mEndtm = $coord_time -1;
        }
        elseif($stype == stat_base::last_hmonth_type)
        {
            $coord_time = strtotime(date('Y-m-d',$stime)) + 86400;
            $this->mStartm = $coord_time - 86400 * 15;
            $this->mEndtm = $coord_time -1;
        }
        elseif($stype == stat_base::last_month_type)
        {
            $cur_time = strtotime(date('Y-m-d',$stime)) + 86400;
            $cur_date = new DateTime();
            $cur_date->setTimestamp($cur_time);
            $inter = new DateInterval('P1M');
            $cur_date->sub($inter);
            $this->mStartm = $cur_date->getTimestamp();

            $this->mEndtm  = $cur_time - 1;
        }
        else {
            return false;
        }

        return true;
    }

    protected function save($fEdit,$datas)
    {
        if($fEdit) {
            $ret = $this->mModel->where(['date_id' => $this->mDateId])->update($datas);
        } else {
            $datas['date_id'] = $this->mDateId;
            $ret = $this->mModel->insert($datas);
        }
        return $ret;
    }
}