<?php

namespace App\Console\Commands\GZH;

use Illuminate\Console\Command;
use Redis;
use WechatOP;
use DB;
use Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '公众号获取粉丝昵称';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $task_start_time = time();
        print_r("====start gzh:force_user_property deal ====".date('Y-m-d H:i:s')."\r\n");
        Log::info("====start gzh:fansStat deal ====");

        $active_time = date('Y-m-d H:i:s', time() - 3600*52);
        $update_user_num = 0;
        $official_accounts = DB::connection('command_mysql')->select("select appid,count(1) from yueduyun.temp_force_subscribe_users t where last_interactive_time > '{$active_time}' and `is_subscribed` = 1 and not exists(select 1 from zhuishuyun_user.force_subscribe_user_properties where appid = t.appid and openid = t.openid) group by appid");
        foreach($official_accounts as $official_account)
        {
            print_r("====appid====".$official_account->appid."\r\n");
            $appid = $official_account->appid;
            $redis_key = '[wechat_op.common.component_refresh_token.'.$appid.']';
            $component_refresh_token = Redis::Get($redis_key);

            $options = [
                'app_id'    => $appid,
                'secret'    => env('WECHAT_OP_SECRET'),   // 仅适用于 单独配置公众号
                'token'     => env('WECHAT_OP_TOKEN'),   // 仅适用于 单独配置公众号
                'aes_key'   => env('WECHAT_OP_AES_KEY'),   // 仅适用于 单独配置公众号
                'auth_type' => 'COMPONENT', // COMPONENT 开放平台授权公众号，MANUAL 单独配置公众号
                'component_refresh_token' => $component_refresh_token,   // 授权回调时获取的 authorizer_refresh_token，仅适用于 开放品台授权公众号
                'cache'   => [
                    'driver' => 'redis',   // redis, filesystem, laravel
                    'dir' => storage_path('tmp') // 只有为filesystem时候这个目录才有效
                ],
            ];
            $app = WechatOP::app($options);
            $userService = $app->user;

            $force_users = DB::connection('command_mysql')->select("select t.* from yueduyun.temp_force_subscribe_users t where appid = '{$appid}' and last_interactive_time > '{$active_time}' and `is_subscribed` = 1 and not exists(select 1 from zhuishuyun_user.force_subscribe_user_properties where appid = t.appid and openid=t.openid)");
            $total = count($force_users);
            $len = 100;//微信限制 最大100
            $save_len = 400;
            $openids = [];
            $data = [];
            foreach ($force_users as $k=>$_user)
            {

                $openids[] = $_user->openid;
                if(count($openids) == $len || $k == $total - 1)//批量获取
                {
                    try{
                        $users = $userService->batchGet($openids);
                        $openids = [];
                        foreach ($users->user_info_list as $item)
                        {
                            if(isset($item['nickname']))
                            {
                                $current_time = date('Y-m-d H:i:s');
                                if($item['nickname'])
                                {
                                    $data[] = [
                                        'openid'=>$item['openid'],
                                        'appid'=>$appid,
                                        'current_nickname'=>trim($item['nickname']),
                                        'created_at'=>$current_time,
                                        'updated_at'=>$current_time,
                                    ];

                                }
                            }
                        }

                    }catch (\Exception $e){
                        $error_msg = $e->getMessage();
                        Log::error($appid .'failed '.$error_msg);

                        if(strstr($error_msg,'component is not authorized by this account') || strstr($error_msg, 'api unauthorized'))
                        {
                            //未授权情况下不再采集
                            break;
                        }
                    };
                }
                if(count($data) >= $save_len || $k == $total - 1)//批量存储
                {
                    $update_user_num += count($data);
                    DB::connection('command_mysql')->table('zhuishuyun_user.force_subscribe_user_properties')->insert($data);
                    $data = [];
                }

            }
        }
        $used_time = time() - $task_start_time;
        print_r("====end gzh:force_user_property deal update user num {$update_user_num} used {$used_time} seconds====".date('Y-m-d H:i:s')."\r\n");
        Log::info("====end gzh:force_user_property deal update user num {$update_user_num}  used {$used_time} seconds");
    }
}
