<?php

namespace App\Console\Commands\Pair;

use App\Events\PairSuccess;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\PairModel;
use App\Models\Fpdx\RoomModel;
use App\Services\Deed\FriendService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '分配对象::匹配成功送入房间';

    private $stage_id;

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


    public function handle()
    {
        $this->stage_id = ActivityModel::where('signend_time', '<=', time())
            ->where('close_time', '>=', time())->value('stage_id');

        $pairs = PairModel::where([
            'stage_id' => $this->stage_id,
            'room_id' => 0,
            'activity_type' => '72h'
        ])->whereNotNull('assoc_id')
            ->where('partner', 1)->get();
        $fs = new FriendService();
        foreach ($pairs as /** @var PairModel $pair */ $pair) {
            try {
                \DB::beginTransaction();
                /** @var PairModel $other */
                $other = PairModel::findOrFail($pair->assoc_id);
                $room = RoomModel::create([
                    'stage_id' => $this->stage_id,
                    'room_name' => "第{$this->stage_id}期的房间",
                    'member' => implode(',', [$pair->uid, $other->uid]),
                    'create_time' => time(),
                    'type' => 1
                ]);
                $pair->room_id = $room->room_id;
                $pair->save();
                $other->room_id = $room->room_id;
                $other->save();

                Redis::zadd("session_room_{$pair->uid}", [$room->room_id => time()]);
                Redis::zadd("session_room_{$other->uid}", [$room->room_id => time()]);
                Redis::sadd("fpdx_pairs_{$pair->uid}", [$other->uid]);
                Redis::sadd("fpdx_pairs_{$other->uid}", [$pair->uid]);
                event(new PairSuccess($pair->uid, $other->uid, $room->room_id));
                \DB::commit();
            } catch (\Exception $e) {
                \DB::rollBack();
                app('sentry')->captureException($e);
                \Log::warning("创建房间失败：【{$pair->id}】|【{$pair->assoc_id}】");
            }
        }
        // 结束钉钉通知
        \Curl::to("http://api.deep.fenpeiduixiang.com/api/ding/roomstate/end/{$this->stage_id}")->get();
    }
}
