<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2018/12/18
 * Time: 10:52
 */

namespace App\Modules\Statistic\Services;

use App\Modules\Statistic\Models\DataAnalysisSelectUser;
use DB;
use Redis;

class DataAnalysisSelectUserService
{
    public static function create($uid, $distribution_channel_id, $type, $max, $attach = '')
    {
        if (empty($uid) || empty($type) || empty($distribution_channel_id) || empty($max)) {
            return false;
        }
        $type = strtoupper(trim($type));

        if(self::getByUidAndType($uid, $type)){
            return true;
        }
        if($max != -1){
            $num = self::getCountRedis($type);
            if ($num > $max) {
                return false;
            }
        }

        return self::add($uid, $distribution_channel_id, $type, $attach,$max);

    }


    public static function getByUidAndType($uid, $type)
    {
        if (empty($uid) || empty($type)) {
            return false;
        }
        $type = strtoupper($type);
        try {
            return DataAnalysisSelectUser::where('uid', $uid)
                ->where('type', $type)
                ->select('uid','attach')
                ->first();
        } catch (\Exception $e) {
        }
        return false;
    }

    public static function getCount($type)
    {
        if (empty($type)) return 0;
        if (is_array($type)) {
            $type = array_map(function ($i) {
                return strtoupper(trim($i));
            }, $type);
            return DataAnalysisSelectUser::whereIn('type', $type)->count();
        } else {
            return DataAnalysisSelectUser::where('type', strtoupper(trim($type)))->count();
        }
    }

    private static function add($uid, $distribution_channel_id, $type, $attach,$max=1)
    {
        if($max != -1){
            self::setCountRedis($type);
        }
        try {
            return DataAnalysisSelectUser::create(compact('uid', 'type', 'distribution_channel_id', 'attach'));
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function setCountRedis($type)
    {
        try {
            Redis::incr('DataAnalysisSelectUser:type:' . $type);
        } catch (\Exception $e) {
        }
    }

    public static function getCountRedis($type)
    {
        $type = strtoupper(trim($type));
        try {
            return (int)(Redis::get('DataAnalysisSelectUser:type:' . $type));
        } catch (\Exception $e) {
        }
        return 0;
    }

}