<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2019/3/26
 * Time: 15:09
 */

namespace App\Modules\User\Services;

use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use Redis;

class ForceSubscribeUserIService
{
    private static $official_name = [];

    public static function subscribes($uid, $distribution_channel_id, $send_order_id)
    {
        $subscribe_info = self::getUserSubscribes($uid);
        //没关注
        if ($subscribe_info->isNotEmpty() &&
            $subscribe_info->search(
                function ($item, $k) use ($send_order_id) {
                    return $item->send_order_id == $send_order_id;
                }
            ) !== false
        ) {
            return ['is_subscribed' => true, 'appid' => '','name'=>''];
        }
        $subscribe_appdis = $subscribe_info->pluck('appid')->all();

        $useable_appdis = self::getOfficialAccount($distribution_channel_id);

        //没有可用的公众号
        if (empty($useable_appdis)) return ['is_subscribed' => true, 'appid' => '','name'=>''];
        $appids = collect($useable_appdis)->diff($subscribe_appdis)->toArray();
        if ($appids) {
            return ['is_subscribed' => false, 'appid' => $appids[0],'name'=>self::$official_name[$appids[0]]];
        }
        return ['is_subscribed' => true, 'appid' => '','name'=>''];
    }

    //用户强关公众号
    public static function getUserSubscribes($uid)
    {
        return ForceSubscribeUsers::where('uid', $uid)->where('is_subscribed', 1)->select('appid', 'send_order_id')->get();
    }

    //可用公众号
    public static function getOfficialAccount($distribution_channel_id)
    {
        $result = OfficialAccount::where('distribution_channel_id', $distribution_channel_id)
            ->where('is_auth', 1)
            ->where('is_enabled', 1)
            ->where('subscribe_top_num', '>', 0)
            ->where('subscribe_day_maximum', '>', 0)
            ->orderBy('sort_no', 'desc')
            ->select('appid', 'subscribe_top_num', 'subscribe_day_maximum','nickname')
            ->get();
        if ($result->isEmpty()) return [];
        $data = [];
        foreach ($result as $value) {
            self::$official_name[$value->appid] = $value->nickname;
            $fans_stats = self::getOfficialAccountFanStats($value->appid);
            {
                $fans_stats['day_fans'] < $value->subscribe_day_maximum
                && $fans_stats['all_fans'] < $value->subscribe_top_num && array_push($data, $value->appid);
            }
        }
        return $data;
    }

    //粉丝数
    public static function getOfficialAccountFanStats($appid)
    {
        $total_fans_cancel_nums = (int)Redis::hget('day_appid_fans_nums_appid:cancel:' . $appid, 'total');

        $total_fan_info = Redis::hmget('day_appid_fans_nums_appid:add:' . $appid, ['total', date('Y-m-d')]);
        $total_fans_add_nums = $total_fan_info[0] ? $total_fan_info[0] : 0;
        $day_fans = $total_fan_info[1] ? $total_fan_info[1] : 0;
        $all_fans = $total_fans_add_nums - $total_fans_cancel_nums;
        return compact('day_fans', 'all_fans');
    }

    public static function getForceSubscribeByUidOpenid($uid) {
        $user_info = UserService::getById($uid);
        if($user_info) {
           $force_subs_info = ForceSubscribeUsers::join('users','users.id','=','force_subscribe_users.uid')
               ->select(['force_subscribe_users.uid','force_subscribe_users.subscribe_time',
                   'force_subscribe_users.created_at','users.openid','force_subscribe_users.is_subscribed'])
               ->where('users.openid',$user_info->openid)
               ->where('force_subscribe_users.is_subscribed',1)
               ->orderBy('force_subscribe_users.id','asc')
               ->first();
           return $force_subs_info;
        }
        return false;
    }
}