<?php

namespace App\Jobs\Company\LiveLuckyBag;

use App\Servers\DB\DbService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Manager\LiveLuckyBagParticipate as Model;
use App\Facades\Servers\Logs\Log;

/**
 * 参与福袋队列
 * 
 */
class JoinLuckyBagJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $recordDatas;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $recordDatas)
    {
        $this->recordDatas = $recordDatas;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
         try {
            // 接收参数
            $recordData                           = $this->recordDatas;
            // 切换数据
            $result                               = (new DbService())->getConnectionNameByCompanyId($recordData['company_id']);
            // 错误提示
            if( isset($result['error']) )         {
                // 返回结果
                Log::error('join_lucky_bag_jobs',$result['error'],$recordData);
                return 0;
            }
            // 查询
            $result                               = (new Model())->add($recordData);
            // 返回结果
            if( !$result )                        Log::error('join_lucky_bag_jobs','写入失败',$recordData);
            // 返回结果
            return                                0;
        } catch (\Throwable $th) {
            // 返回结果
            Log::error('join_lucky_bag_jobs',$th->getMessage(),$th);
        }
    }

    public function failed(\Throwable $th)
    {
        Log::info('join_lucky_bag_jobs', '直播参与福袋队列失败', ['data' => $this->recordDatas, 'error' => $th->getMessage()]);
    }
}
