<?php

namespace App\Console\Commands;

use App\Helper\Kuaishou;
use App\Helper\UniPlatform\Kuaishou\KuaishouAPI;
use App\Models\Pay;
use App\Models\PayConfig;
use Illuminate\Console\Command;

class KuaishowPush extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'kuaishow:push';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '推送快手订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $app    = $this->getKuishouFactory();
        $orders = Pay::with(['user.info'])->whereHas('user.info', function ($query) {
            $query->where('platform', 2);
        })->where('status', 1)
            ->where('is_settle', 0)
            ->get();

        /* @var Pay $order */
        foreach ($orders as $order) {
            try {
                echo '推送订单号-->',$order->pay_id;
                $res = $app->pushOrder($order->user->open_id, $order->pay_id, $order->created_at);
                echo "\t推送结果-->\033[32m",json_encode($res, JSON_UNESCAPED_UNICODE),"\033[0m",PHP_EOL;
            } catch (\Exception $exception) {
                echo "\t推送结果异常-->\033[31m",$exception->getMessage(),"\033[0m",PHP_EOL;
            }
        }
    }

    protected function getKuishouFactory(): Kuaishou
    {
        $setting = PayConfig::first();

        return (new Kuaishou(app(KuaishouAPI::class)))->factory([
            'app_id'     => $setting->kuaishou_app_id,
            'app_secret' => $setting->kuaishou_app_secret,
        ]);
    }
}
