<?php

namespace App\Console\Commands\Push;


use App\Consts\PushConst;
use App\Libs\Push\HuaWei\HwPushCommon;
use App\Libs\Push\VPush\VPush;
use App\Libs\Push\OPPOPush\OPPOPushCommon;
use App\Modules\Push\Services\PushAppService;
use Illuminate\Console\Command;

class PushTagBind extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'push:tag:bind {provider} {last_id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '推送标签绑定';

    /**
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        # 标签
        $tag      = PushConst::TOPIC_ALL;
        $provider = $this->argument('provider');
        $id       = (int)$this->argument('last_id');

        # 获取所有oppo app，初始化推送
        $apps = PushAppService::getAppsByProvider($provider);

        # 查询所有oppo用户
        while (True) {
            var_dump('last id:'.$id);

            # 获取用户列表
            $users = PushAppService::getAppUsersByProvider($provider, $id);
            if (empty($users)) {
                break;
            }

            $groupUsers = collect($users)->groupBy('app_id')->all();
            foreach($groupUsers as $appId => $userList) {
                $regIds  = collect($userList)->pluck('reg_id')->all();
                $pushApp = collect($apps)->firstWhere('app_id', $appId);
                var_dump($appId, count($regIds));

                // 初始化
                $appId        = getProp($pushApp, 'app_id');
                $appSecret    = getProp($pushApp, 'app_secret');
                $appKey       = getProp($pushApp, 'app_key');
                $masterSecret = getProp($pushApp, 'master_secret');

                // 循环绑定
                if ($provider === PushConst::PROVIDER_OPPO) {
                    $client = new OPPOPushCommon($appKey, $masterSecret);
                    if ($regIds && $client) {
                        foreach($regIds as $regId) {
                            $client->subscribeTags($regId, $tag);
                        }
                    }
                }elseif ($provider === PushConst::PROVIDER_VIVO) {
                    $client = new VPush($appId, $appKey, $appSecret);
                    $client->addTagForUsers($tag, $regIds);
                } else if ($provider === PushConst::PROVIDER_HW) {
                    $client = new HwPushCommon($appId, $appSecret);
                    $client->subscribeTopic($tag, $regIds);
                }
            }

            # 分页id
            $len = count($users);
            $id  = $users[$len - 1]['id'];
            var_dump('next id:'.$id);
        }
    }

}