<?php namespace App\Jobs\Company\Lottery;


use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

use App\Facades\Servers\Logs\Log;

use App\Models\Manager\CustomAmount;
use App\Models\Manager\CustomCoupon;
use App\Models\Manager\CustomScore;
use App\Models\Manager\Lottery\LiveRecord;

use App\Servers\DB\DbService;


/**
 * 奖品发放
 */
class LiveRewardJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** 奖品数据 **/
    protected $winData;

    /**
     * 任务可尝试的次数
     *
     * @var int
     */
    public $tries = 3;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 获取数据
        $winData                                = $this->winData;
        try {
            // 如果不是1,2,3 类型，不处理
            if( !in_array($winData['reward_type'],[1,2,3]) )  return 0;
            // 切换数据库
            (new DbService())->getConnectionNameByCompanyId($winData['company_id']);
            // 中奖记录
            $LiveRecord                         = (new LiveRecord);
            // 先查询是不是有未处理的
            $oldId                              = $LiveRecord->query()->where([['custom_uid','=',$winData['custom_uid']],['lottery_id','=',$winData['lottery_id']],['reward_id','=',$winData['reward_id']],['status','=',1],['insert_time','=',$winData['insert_time']]])->value('id');
            // 如果有没有的话，不处理
            if( !$oldId )                       return 0;
            // 如果是积分
			if( $winData['reward_type'] == 1 )  {
				// 积分大于0
				if( $winData['reward_info'] > 0 ){
					// 积分发放
					$result                     = (new CustomScore)->trade($winData['custom_uid'],$winData['shop_id'],$winData['company_id'],$winData['lottery_id'],$winData['reward_info'],13,1);
                    // 发放失败，改为未中奖
					if( isset($result['error']) ) Log::info('job_error/live_reward_jobs', $result['error'], $winData);
				}
			}
			// 优惠券，先进行发放
			if( $winData['reward_type'] == 2 )  {
				// 优惠券存在ID
				if( $winData['reward_info'] > 0 ){
					// 积分给与
					$result                     = (new CustomCoupon)->giveCoupon($winData['reward_info'],$winData['custom_uid'],$winData['shop_id'],$winData['company_id']);
                    // 发放失败，改为未中奖
					if( !$result ) Log::info('job_error/live_reward_jobs', '优惠券发放失败', $winData);
				}
			}
			// 红包
			if( $winData['reward_type'] == 3 )  {
				// 积分大于0
				if( $winData['reward_info'] > 0 ){
					// 积分发放
					$result                     = (new CustomAmount)->trade($winData['custom_uid'],$winData['shop_id'],$winData['company_id'],$winData['lottery_id'],$winData['reward_info'],10,1);
                    // 发放失败，改为未中奖
					if( isset($result['error']) ) Log::info('job_error/live_reward_jobs', '优惠券发放失败', $winData);
				}
			}
            // 修改状态
            $result                             = $LiveRecord->edit($oldId,['status'=>8]);
            // 发放失败，改为未中奖
            if( !$result )                      Log::info('job_error/live_reward_jobs', '状态修改失败', $winData);
            // 返回结果
            return                              $result;
        } catch (Throwable $th) {
            Log::info('job_error/live_reward_jobs', $th->getMessage(), $winData);
        }
    }

    public function failed(\Throwable $th)
    {
        Log::info('job_error/live_reward_jobs', '直播参与下单抽奖队列失败', ['data' => $this->recordData, 'error' => $th->getMessage()]);
    }
}
