<?php

namespace App\Console\Commands\Qbj;

use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\PairModel;
use App\Models\Fpdx\RoomModel;
use App\Services\Deed\FriendService;
use DB;
use Exception;
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 = 'qbj:into:room';

    /**
     * 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
     * @throws Exception
     */
    public function handle()
    {
        //
        $stage_id = ActivityModel::where('qbj_stage_id', '>', 0)
            ->where('signend_time', '<=', time())
            ->where('close_time', '>=', time())->value('stage_id');
        if (!$stage_id) {
            dd("当前没有正在进行的情报局活动");
        }

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

                Redis::zadd("session_room_{$pair->uid}", time(), $room->room_id);
                Redis::zadd("session_room_{$other->uid}", time(), $room->room_id);
                Redis::sadd("fpdx_pairs_{$pair->uid}", $other->uid);
                Redis::sadd("fpdx_pairs_{$other->uid}", $pair->uid);
                $fs->befriend($pair->uid, $other->uid, 2, $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/{$stage_id}")->get();
    }
}
