<?php

namespace app\api\service\statistics;

use app\api\model\GoodsBrowseLog;
use app\api\model\User;
use app\common\service\BaseService;

class UserData extends BaseService
{
    protected User $userModel;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->userModel = new User();
    }
    public function getUserData($startDate = null, $endDate = null): array
    {
        return [
            'visitorCount' => $this->getVisitorCount($startDate, $endDate),
            'viewCount' => $this->getViewCount($startDate, $endDate),
            'newUserCount' => $this->getNewUserCount($startDate, $endDate),
        ];
    }

    /**
     * 用户访问总数
     */
    public function getVisitorCount($startDate = null, $endDate = null) {
        $query = new GoodsBrowseLog();
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['ctime', '>=', $startDate];
            $filter[] = ['ctime', '<', $endDate];
        }
        $value = $query->where($filter)->group('user_id')->count();
        return number_format($value);
    }

    /**
     * 用户浏览总数
     */
    public function getViewCount($startDate = null, $endDate = null): string
    {
        $query = new GoodsBrowseLog();
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['ctime', '>=', $startDate];
            $filter[] = ['ctime', '<', $endDate];
        }
        $value = $query->where($filter)->count();
        return number_format($value);
    }

    /**
     * 新用户数量
     */
    public function getNewUserCount($startDate = null, $endDate = null) {
        $filter = [];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['create_time', '>=', strtotime($startDate)];
            $filter[] = ['create_time', '<', strtotime($endDate) + 86400];
        }
        $value = $this->userModel->where($filter)->group('user_id')->count();
        return number_format($value);
    }
}