<?php

namespace App\Jobs;

use App\Helper\ByteDance;
use App\Helper\UniPlatform\Bytedance\ByteDanceAPI;
use App\Models\Pay;
use App\Models\PayConfig;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $app = $this->getByteDanceFactory();

        $orders = Pay::with(['user.info'])->whereHas('user.info', function ($query) {
            $query->where('platform', 1);
        })->where('status', 1)
            ->where('created_at', '<=', Carbon::now()->subDays(7)->toDateString() . ' 00:00:00')
            ->where('is_settle', 0)
            ->get()
            ->chunk(30);
        foreach ($orders as $arr) {
            /* @var Pay $order */
            foreach ($arr as $order) {
                try {
                    $res              = $app->settle($order->pay_id);
                    $order->is_settle = 1;
                    $order->settle_no = $res['settle_no'];
                    $order->save();
                    \Log::info("抖音结算--> 支付订单号：{$order->pay_id}\t结算单号：{$res['settle_no']}");
                } catch (\Exception $e) {
                    \Log::info("抖音结算错误--> 支付订单号：{$order->pay_id}\n错误信息：{$e->getMessage()}");
                }
            }
            // 30QPS
            sleep(1);
        }
    }

    protected function getByteDanceFactory(): ByteDance
    {
        $setting = PayConfig::first();

        return (new ByteDance(app(ByteDanceAPI::class)))->factory([
            'app_id'     => $setting->douyin_app_id,
            'app_secret' => $setting->douyin_app_secret,
            'slat'       => $setting->douyin_salt,
            'token'      => $setting->douyin_token,
        ]);
    }
}
