<?php

namespace App\Jobs;

use App\Consts\ErrorConst;
use App\Libs\Utils;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Throwable;

class ReportDy implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务可尝试次数
     *
     * @var int
     */
    public $tries = 5;          // 重试次数
    public $timeout = 120;      // 超时秒数
    public $backoff = 3;        // 重试任务前等待的秒数
    public $params = [];
    public $url = 'https://analytics.oceanengine.com/api/v2/conversion';    // 上报url

    /**
     * Create a new job instance.
     *
     * @param $params
     */
    public function __construct($params)
    {
        $this->params = $params;
        $this->onQueue('{ReportDy}');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        dLog('reportDy')->info('开始执行上报抖音队列', $this->params);
        $clickid = getProp($this->params, 'clickid');
        $event_type = getProp($this->params, 'event_type');
        if (!$clickid || !$event_type) {
            dLog('reportDy')->info('抖音上报参数错误', $this->params);
            return ;
        }
        $trade_no = '';
        if (isset($this->params['trade_no'])) {
            $trade_no = $this->params['trade_no'];
            unset($this->params['trade_no']);
        }

        try {
            $client = new Client(['verify' => false]);
            $response = $client->post($this->url, ['json' => $this->params]);
            $response_json = $response->getBody()->getContents();
            $result = json_decode($response_json, true);

            $update_data = [
                'event_type'        => $event_type,
                'callback_result'   => isset($result['message']) ? $result['message'] : '回参有误',
                'callback_response' => $response_json,
                'updated_at'        => date('Y-m-d H:i:s')
            ];
            if ($trade_no) $update_data['trade_no'] = $trade_no;

            DB::beginTransaction();

            // 写入抖音广告主投放回调日志表
            $boolen = DB::table('dy_report_logs')->where('clickid', $clickid)->where('event_type', '')->update($update_data);
            if (!$boolen) {
                DB::rollBack();
                dLog('reportDy')->info('写入抖音广告主投放回调日志表失败: ', $update_data);
                Utils::throwError(ErrorConst::REPORT_FAILED);
            }

            // 如果是充值事件则更新派单级别回传上报总数
            if ($event_type == 'active_pay') {
                $send_order_id = DB::table('dy_report_logs')->where('clickid', $clickid)->value('send_order_id');
                $boolen1 = DB::table('send_orders')->where('id', $send_order_id)->increment('report_post_num');
                if (!$boolen1) {
                    DB::rollBack();
                    dLog('reportDy')->info('派单表更新回传上报总数失败: ', $this->params);
                    Utils::throwError(ErrorConst::REPORT_FAILED);
                }
            }
            DB::commit();

            dLog('reportDy')->info('上报结果: ', $result);
        }catch (\Exception $e) {
            dLog('reportDy')->info('上报异常: ', ['error'=>$e->getMessage()]);
        }
    }

    public function failed(Throwable $exception)
    {
        dLog('reportDy')->info('上报抖音队列失败', ['error'=>$exception->getMessage()]);
    }
}
