<?php

namespace App\Console\Commands\Pair;

use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\FormModel;
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 FeedbackNoticeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pair:notice:feedback';

    /**
     * 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('close_time', '<=', time())->orderBy('close_time', 'desc')->value('stage_id');

        $pairs = PairModel::select('uid', 'stage_id')
            ->where('stage_id', $stageId)
            ->whereNotNull('assoc_id')
            ->get();
        $form = FormModel::where('stage_id', $stageId)->where('activity_type', '72h')->first();
        $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',
            'stage_id',
            'form_id'
        ]);
        foreach ($pairs as $pair) {
            $user = UserModel::find($pair->uid);
            fputcsv($fp, [
                json_encode($user->getAuth()),
                $stageId,
                $form->id,
            ]);
        }
        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 = 10108;
        $payload = [
            'memo' => "72小时反馈通知-{$stageId}期",
            'queryType' => 1,
            'queryUrl' => $fileUrl,
            'eventId' => $eventId,
            'startAt' => mktime(9, 45, 0),
            'maxEveryDay' => $maxCount,
            'secondSendRate' => 60,
            'delayPiece' => 10,
        ];
        $response = Curl::to($url)->withData([
            'payload' => $payload
        ])->asJson(true)->post();
        dd($response);
    }
}
