<?php

namespace App\Console\Commands\Pair;

use App\Jobs\GrowingIO\PairSuccessReportJob;
use App\Models\Fpdx\ActivityModel;
use App\Models\User\UserModel;
use Illuminate\Console\Command;
use App\Models\Fpdx\PairModel;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Ixudra\Curl\Facades\Curl;

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

    /**
     * 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 mixed
     */
    public function handle()
    {
        $stageId = ActivityModel::where('signend_time', '<=', time())
            ->where('close_time', '>=', time())->value('stage_id');

        $pairs = PairModel::where('stage_id', $stageId)
            ->select('uid', 'stage_id', 'assoc_id')
            ->get();
        $maxCount = $pairs->count();
        $uuid = uuid();
        $path = sprintf("media/%s", date('Y-m-d'));
        $local_file = sprintf("storage/app/public/%s.csv", $uuid);
        $fp = fopen($local_file, 'w');
        fputcsv($fp, [
            'to_user',
            'pair.stage_id'
        ]);
        foreach ($pairs as $pair) {
            $user = UserModel::find($pair->uid);
            fputcsv($fp, [
                json_encode($user->getAuth()),
                $stageId,
            ]);

            if ($pair->assoc_id) {
                $other = PairModel::find($pair->assoc_id);
                PairSuccessReportJob::dispatch($pair->uid, $other->uid, $stageId, 1);
            }
        }
        fclose($fp);

        $file = new File($local_file);
        $file = Storage::disk('oss')->putFileAs($path, $file, $uuid . '.' . $file->getExtension());
        $fileUrl = Storage::disk('oss')->url($file);


        // 导入通知
        $url = "https://push.fenpeiduixiang.com/api/v1/marketing/set_up_activity";
        $eventId = 10106;
        $payload = [
            'memo' => "72小时匹配通知-{$stageId}期",
            'queryType' => 1,
            'queryUrl' => $fileUrl,
            'eventId' => $eventId,
            'startAt' => mktime(18, 25, 0),
            'maxEveryDay' => $maxCount,
            'secondSendRate' => 60,
            'delayPiece' => 10,
        ];
        $response = Curl::to($url)->withData([
            'payload' => $payload
        ])->asJson(true)->post();
        dd($response);
    }
}
