<?php

namespace App\Console\Commands;

use App\Facades\WechatService;
use App\Models\Group;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Group::whereNull('chat_name')->whereNotNull('chat_id')->chunk(100, function ($groups) {
            foreach ($groups as $group) {
                Log::info("UpdateGroupChatName group_id： $group->id");
                $res = WechatService::groupChat($group->chat_id, 1);
                if ($res) {
                    Log::info(json_encode($res));
                    if ($res->errcode == 0 && $res->group_chat && $res->group_chat->name) {//成功
                        $group->update(['chat_name' => $res->group_chat->name]);
                        continue;

                    } elseif ($res->errcode == 86003 || $res->errcode == 49008) {//企业群不存在，解除与系统群关系
                        $group->update(['chat_id' => null]);
                        continue;
                    }
                    if ($res->errcode != 0)
                        throw new \Exception($group->chat_id . "----" . $res->errcode . '----' . $res->errmsg);
                }
                if (empty($res))
                    throw new \Exception($group->chat_id . "请求失败");
            }
            return Command::SUCCESS;
        });
        return Command::SUCCESS;
    }
}
