<?php

namespace App\Web\Services;

use App\Services\CommonUserBaseService;
use App\Web\Models\WebUtmModel;
use Illuminate\Support\Facades\Cache;

class WebUtmService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'WebUtm:';

    public function __construct(WebUtmModel $model)
    {
        $this->model = $model;
    }

    public function getUtm($id)
    {
        return $this->model->getWebUtm($id);
    }

    public function delUtm($ids)
    {
        return $this->model->delWebUtm($ids);
    }

    public function addOrUpdUtm($params)
    {
        $userId = $this->getAuthUserId() ?? 0;
        if (!empty($id)) {
            $this->model->updWebUtm($id, $params);
        } else {
            $oldUtm = $this->model->getUtmByParams($params);
            if (!empty($oldUtm)) {
                $id = $oldUtm['id'];
                $this->model->updWebUtm($id, $params);
            } else {
                $id = $this->model->addWebUtm($userId, $params);
            }
        }
        return $id;
    }

    public function getWebUtmList($campaignName = '', $campaignSource = '', $campaignMedium = '', $pageSize = 10, $orderBy = '', $orderDirect = '')
    {
        return $this->model->getWebUtmList($campaignName, $campaignSource, $campaignMedium, $pageSize, $orderBy, $orderDirect);
    }

    /**
     * UTM缓存pv key获取方式
     * @param $id
     * @return string
     */
    public function getUtmPvCacheKey($id)
    {
        return $this->cacheBucket . '_web_utm_pv_' . $id;
    }

    /**
     * UTM缓存uv key获取方式
     * @param $id
     * @return string
     */
    public function getUtmUvCacheKey($id)
    {
        return $this->cacheBucket . '_web_utm_uv_' . $id;
    }

    /**
     * UTM IP 缓存key获取方式
     * @param $id
     * @param $ip
     * @return string
     */
    public function getUtmIpCacheKey($id, $ip)
    {
        return $this->cacheBucket . '_web_utm_' . $id . '_' . $ip;
    }

    /**
     * @return string
     */
    public function getUtmCacheIdsKey()
    {
        return $this->cacheBucket . '_web_utm_cache_list';
    }

    /**
     * 广告统计分析
     * @param $utmParams
     * @param $clientIp
     * @param $clientHost
     * @param $clientPath
     * @return int
     */
    public function statisticAnalysis($utmParams, $clientIp, $clientHost, $clientPath)
    {
        //判断是否广告渠道进入的用户
        if(!empty($utmParams)) {
            $utmConstParams = ['campaign_id', 'campaign_name', 'campaign_source', 'campaign_term',
                'campaign_medium', 'campaign_content'];
            $utmKeys = array_keys($utmParams);
            $leadArr = array_intersect($utmKeys, $utmConstParams);
            if (!empty($leadArr)) {
                $utm = $this->model->getUtmByParams($utmParams);
                if(!empty($utm)) {
                    $parsedUrl = parse_url($utm['website_url']);
                    if (!empty($parsedUrl['host']) && !empty($parsedUrl['path'])) {
                        $rawClientPath = str_replace('/', '', $clientPath);
                        $rawParsedPath =  str_replace('/', '', $parsedUrl['path']);
                        if ($clientHost == $parsedUrl['host'] &&
                            (empty($rawClientPath) && empty($rawParsedPath)
                                || $rawClientPath == $rawParsedPath)
                        ) {
                            $pvCache = Cache::get($this->getUtmPvCacheKey($utm['id']));
                            if ($pvCache) {
                                $pvCache = $pvCache + 1;
                            } else {
                                $pvCache = 1;
                            }
                            Cache::put($this->getUtmPvCacheKey($utm['id']), $pvCache, 24 * 3600);
//                            if ($clientIp) {
//                                $ipCache = Cache::get($this->getUtmIpCacheKey($utm['id'], $clientIp));
//                                if (empty($ipCache)) {
//                                    $uvCache = Cache::get($this->getUtmUvCacheKey($utm['id']));
//                                    if ($uvCache) {
//                                        $uvCache = $uvCache + 1;
//                                    } else {
//                                        $uvCache = 1;
//                                    }
//                                    Cache::put($this->getUtmUvCacheKey($utm['id']), $uvCache, 24 * 3600);
//                                    Cache::put($this->getUtmIpCacheKey($utm['id'], $clientIp), 1, 24*3600);
//                                }
//                            }
                        }
                    }
                }
            }
        }
        return 1;
    }

    /**
     * 持久化存储Pv，Uv
     * @param $page
     * @return int
     */
    public function persistenceUtmPvUv($page = 1)
    {
        if (config('app.is_utm')) {
            $pageSize = 999;
            $data = $this->model->getWebUtmByPage($page, $pageSize);
            if (!empty($data)) {
                foreach ($data as $utm) {
                    $pvCache = Cache::get($this->getUtmPvCacheKey($utm['id']));
//                    $uvCache = Cache::get($this->getUtmUvCacheKey($utm['id']));
                    if (!empty($pvCache)) {
                        $this->model->where('id', $utm['id'])->increment('pv', $pvCache);
                        Cache::forget($this->getUtmPvCacheKey($utm['id']));
                    }
//                    if (!empty($uvCache)) {
//                        $this->model->increment('uv', $uvCache);
//                        Cache::forget($this->getUtmUvCacheKey($utm['id']));
//                    }
                }
                $page = $page + 1;
                $this->persistenceUtmPvUv($page);
            }
            return 1;
        }
        return 0;
    }
}
