<?php

namespace App\Console\Commands\Wechat;

use App\Jobs\WeChatFansJob;
use Illuminate\Console\Command;

class FansCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:fans';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '公众号粉丝入库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    private $publicId;

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->publicId = $this->ask("公众号ID");
        $option = $this->choice('请选择执行操作', [
            'openid' => '获取全部openid',
            'user' => '用户信息',
            'tag' => '打tag',
            'user_info' => '获取openid信息'
        ]);
        switch ($option) {
            case "openid":
                $this->batchOpenid();
                break;
            case "user":
                $this->batchUser();
                break;
            case "tag":
                $this->batchTag();
                break;
            case "user_info":
                $this->getUserInfo();
                break;
        }
    }


    public function batchOpenid()
    {
        \DB::table("kddx_user_openid")->where('public_id', $this->publicId)->update(['subscribe' => 0]);
        \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))
            ->where('public_id', $this->publicId)
            ->update(['subscribe' => 0]);
        $next_openid = '';
        $i = 0;
        do {
            $response = \WeChat::Fans($this->publicId)->getAll($next_openid);
            $openid_list = $response->data->openid;
            $next_openid = $response->next_openid;
            $i += 10000;
            foreach ($openid_list as $openid) {
                if (\DB::table("kddx_user_openid")->where('openid', $openid)->first()) {
                    \DB::table("kddx_user_openid")
                        ->where('openid', $openid)->update([
                            'subscribe' => 1,
                        ]);
                } else {
                    \DB::table("kddx_user_openid")
                        ->insert([
                            'public_id' => $this->publicId,
                            'openid' => $openid,
                            'subscribe' => 1,
                        ]);
                }

                if (\DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))->where('openid', $openid)->first()) {
                    \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))
                        ->where('openid', $openid)->update([
                            'subscribe' => 1,
                        ]);
                } else {
                    \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))
                        ->insert([
                            'public_id' => $this->publicId,
                            'openid' => $openid,
                            'subscribe' => 1,
                        ]);
                }
            }
        } while ($i < $response->total);
    }


    public function batchUser()
    {
        $offset = 0;

        while (
            $openids = \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))
            ->where('public_id', $this->publicId)
            ->where("subscribe", 1)
            ->offset($offset)
            ->limit(100)
            ->pluck('openid')->toarray()
        ) {
            dump($offset);
            WeChatFansJob::dispatch($this->publicId, $openids)->onQueue("{wechat:fans:info}");

            $offset += 100;
        }
    }


    public function batchTag()
    {

        $where = [
            ['public_id', $this->publicId],
            ['subscribe', 1],
            ['subscribe_scene', 'ADD_SCENE_ACCOUNT_MIGRATION'],
            ['subscribe_time', '>', 1561021200]
        ];

        $tagId = \WeChat::Tags($this->publicId)->get("西安培华-无");
        if (!$tagId) {
            $tagId = WeChat::Tags($this->publicId)->create("西安培华-无")->tag->id;
        }
        $openids = \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))->where($where)->where('sex', 0)
            ->pluck('openid')->toarray();
        for ($i = 0; $i < count($openids); $i += 50) {
            \WeChat::Tags($this->publicId)->batchTagging(array_slice($openids, $i, 50), $tagId);
        }
        dump("性别-无{$tagId}", count($openids));


        $tagId = \WeChat::Tags($this->publicId)->get("西安培华-男");
        if (!$tagId) {
            $tagId = \WeChat::Tags($this->publicId)->create("西安培华-男")->tag->id;
        }
        $openids = \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))->where($where)->where('sex', 1)
            ->pluck('openid')->toarray();
        for ($i = 0; $i < count($openids); $i += 50) {
            \WeChat::Tags($this->publicId)->batchTagging(array_slice($openids, $i, 50), $tagId);
        }
        dump("性别-男{$tagId}", count($openids));


        $tagId = \WeChat::Tags($this->publicId)->get("西安培华-女");
        if (!$tagId) {
            $tagId = \WeChat::Tags($this->publicId)->create("西安培华-女")->tag->id;
        }
        $openids = \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))->where($where)->where('sex', 2)
            ->pluck('openid')->toarray();
        for ($i = 0; $i < count($openids); $i += 50) {
            \WeChat::Tags($this->publicId)->batchTagging(array_slice($openids, $i, 50), $tagId);
        }
        dump("性别-女{$tagId}", count($openids));

        dump(\WeChat::Tags($this->publicId)->get());
    }


    public function getUserInfo()
    {
        $openid = $this->ask("输入openid");

        $user_info = \WeChat::Fans($this->publicId)->info($openid);
        dump($user_info);
        if ($user_info->subscribe == 1) {
            try {
                \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))
                    ->where('openid', $user_info->openid)
                    ->update([
                        'nickname' => trim($user_info->nickname) ?: "",
                        'sex' => $user_info->sex,
                        'language' => $user_info->language ?: "",
                        'city' => $user_info->city ?: "",
                        'province' => $user_info->province ?: "",
                        'country' => $user_info->country ?: "",
                        'headimgurl' => $user_info->headimgurl ?: "",
                        'unionid' => isset($user_info->unionid) ? $user_info->unionid : "",
                        'subscribe_time' => $user_info->subscribe_time,
                        'remark' => $user_info->remark ?: "",
                        'groupid' => $user_info->groupid,
                        'tagid_list' => json_encode($user_info->tagid_list),
                        'subscribe_scene' => $user_info->subscribe_scene ?: "",
                        'qr_scene' => $user_info->qr_scene ?: $user_info->qr_scene_str
                    ]);
            } catch (\Exception $e) {
                dump($e);
            }
        } else {
            \DB::table("pocket.kdgx_fans_" . substr($this->publicId, -1))
                ->where('openid', $user_info->openid)
                ->update([
                    'subscribe' => 0
                ]);
        }
    }
}
