<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Models\WangYiYun;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use cccdl\yunxin_sdk\Im\User as ImUser;

class AddWangYiYunUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'add:wang:yi:user';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步网易用户';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $end_time = time();
        $start_time = $end_time - 61;
        $start_date = date('Y-m-d H:i:s',$start_time);
        $end_date = date('Y-m-d H:i:s',$end_time);
        $users = User::whereBetween('created_at',[$start_date,$end_date])->get('id');
        $imUser = new ImUser(config('chat.im.app_id'), config('chat.im.app_secret'));
        foreach ($users as $user){
            $exists = WangYiYun::where('user_id',$user->id)->exists();
            if($exists){
                continue;
            }
            $ac_cid = make_wangyiyun_accid($user->id);
            $insert = $yun = [];
            $insert['user_id'] = $user->id;
            $insert['accid'] = $ac_cid;
            $insert['name'] = $yun['name'] = $user->name;
            $insert['icon'] = $yun['icon'] = $user->avatar;
            $insert['email'] = $yun['email'] = $user->email;
            $insert['birth'] = $yun['birth'] = $user->birthday;
            $insert['mobile'] = $yun['mobile'] = $user->mobile;
            $insert['gender'] = $yun['gender'] = !empty($user->sex) ? $user->sex : 0;

            DB::beginTransaction();
            try {
                $imUserData = $imUser->create($ac_cid, $yun);
                $token = $imUserData['info']['token'] ?? '';
                $insert['token'] = $token;
                WangYiYun::create($insert);
                DB::commit();

                Log::info('AddWangYiYunUser success user_id:'.$user->id);
            } catch (\Exception $e) {
                Log::info('AddWangYiYunUser fail user_id:'.$user->id);
                DB::rollBack();
            }
        }
        return Command::SUCCESS;
    }
}
