<?php

namespace App\Services\Goodnight;

use App\Events\GoodnightSuccess;
use App\Http\Controllers\Core\Ding;
use App\Models\Goodnight\EnterModel;
use App\Services\Deed\FriendService;
use App\Services\Service;

class MatchService extends Service
{
    /**
     * 启动匹配任务
     */
    public function run()
    {
        if (app()->environment() == 'production') {
            Ding::robot([
                'title' => '[晚安伴侣]匹配|开始',
                'text' => "匹配|开始",
            ]);
        }
        $es = new EnterService();
        $rms = new RoomService();
        $fs = new FriendService();
        // 1. 加载待匹配数据
        $acty = $es->getActivity("匹配");
        $datas = \DB::table('kdgx_goodnight_enters as te')
            ->join('kdgx_goodnight_user as tgu', 'te.uid', '=', 'tgu.uid')
            ->join('kdgx_partner_charge_user as tu', 'te.uid', '=', 'tu.uid')
            ->where([['te.type', '报名'], ['room_id', 0], ['activity_id', $acty->id], ['match_at', 0]])
            ->select('te.*', 'tgu.like_sex', 'tu.sex', 'tu.nickname')->get();
        // 2. 规则匹配
        foreach ($datas as &$data) {
            foreach ($datas as &$value) {
                if ($data->room_id > 0 || $value->room_id > 0) {
                    continue;
                }
                if ($data->id == $value->id) {
                    continue;
                }
                if ($data->like_sex != $value->sex || $value->like_sex != $data->sex) {
                    continue;
                }

                try {
                    $room_id = $rms->create([$data->id, $value->id], $acty->id);
                } catch (\Exception $e) {
                    dump($e);
                }

                $data->room_id = $room_id;
                $value->room_id = $room_id;

                EnterModel::where('id', $data->id)->update(['room_id' => $room_id]);
                EnterModel::where('id', $value->id)->update(['room_id' => $room_id]);

                // 匹配成功通知
                $ns = new NoticeService();
                $ns->matchSuccess($data->uid, $value->uid);
                $ns->matchSuccess($value->uid, $data->uid);
            }
            if ($data->room_id == 0) {
                // 匹配失败通知
                $ns = new NoticeService();
                $ns->matchFail($data->uid);
            }
            EnterModel::where('id', $data->id)->update(['match_at' => time()]);
        }

        if (app()->environment() == 'production') {
            Ding::robot([
                'title' => '[晚安伴侣]匹配|完成',
                'text' => "匹配|完成",
            ]);
        }
    }
}
