<?php

namespace App\Jobs;

use App\Models\Wxkf\UserInfoModel;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class WxkfUserInfoJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    private $userinfos;
    private $wxid;

    /**
     * Create a new job instance.
     *
     * @param  string  $wxid
     * @param  array  $userinfos
     */
    public function __construct(string $wxid, array $userinfos)
    {
        $this->wxid = $wxid;
        $this->userinfos = $userinfos;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        sleep(5);
        foreach ($this->userinfos as $data) {
            try {
                $create = array(
                    'wxkf_wxid' => $this->wxid,
                    'wxid' => $data['wxid'],
                    'sex' => isset($data['sex']) ? $data['sex'] : 0
                );
                if (!empty($data['nickname'])) {
                    $create['nickname'] = $data['nickname'];
                }
                if (!empty($data['head_img'])) {
                    $create['head_img'] = $data['head_img'];
                }
                if (!empty($data['wx_alias'])) {
                    $create['wx_alias'] = $data['wx_alias'];
                }
                UserInfoModel::updateOrCreate(
                    array(
                        'wxkf_wxid' => $this->wxid,
                        'wxid' => $data['wxid']
                    ),
                    $create
                );
            } catch (\Exception $exception) {
                app('sentry')->captureException($exception);
            }
        }
    }

    /**
     * 要处理的失败任务
     * @param  Exception  $exception
     */
    public function failed(Exception $exception)
    {
    }
}
