<?php

namespace App\Http\Controllers\Fpdx;

use App\Exceptions\DBException;
use App\Http\Resources\Fpdx\PairResource;
use App\Models\Common\CityModel;
use App\Models\Fpdx\OperationalLogModel;
use App\Models\Fpdx\RoomModel;
use App\Models\NoticeModel;
use App\Models\SchoolModel;
use App\Models\TagModel;
use App\Services\Pay\OrderService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Exceptions\AlertException;
use App\Exceptions\ApiException;
use App\Http\Controllers\Order;
use App\Models\User\UserModel;
use App\Services\Pair\PairService;
use App\Http\Controllers\Core\Auth;
use App\Http\Controllers\Controller;
use App\Models\Fpdx\PairModel;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\MediaOrderModel;
use App\Models\OrderModel;
use Illuminate\Support\Facades\DB;

class PairController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @deprecated Pair/GetActivityConductStageId
     */
    public function getActivityConductStageId()
    {
        $ings = ActivityModel::getActivitys();
        $data = ActivityModel::findOrFail($ings['ing']);
        return response([
            'errcode' => 0,
            'errmsg' => $data
        ]);
    }

    public function activityLogin(Request $request)
    {
        $this->validate($request, ['stage_id' => 'required']);
        $stage_id = $request->post("stage_id");

        $uid = Auth::auth();

        $pair = PairModel::where([['uid', $uid], ['stage_id', $stage_id]])->firstOrFail();
        $pair->login_time = time();
        $pair->save();

        return response(array(
            'errcode' => 0,
            'errmsg' => 'success'
        ));
    }

    public function cpData(Request $request)
    {
        $media_id = $request->get("media_id");

        $stages = ActivityModel::get()->toArray();

        foreach ($stages as &$stage) {
            $where = array(
                ['stage_id', $stage['stage_id']],
                ['media_id', $media_id]
            );
            $stage['all_count'] = PairModel::where($where)->count();
            $where = array(
                ['stage_id', $stage['stage_id']],
                ['media_id', $media_id],
                ['state', 801]
            );
            $stage['success_count'] = PairModel::where($where)->count();
        }

        return response([
            'errcode' => 0,
            'errmsg' => $stages
        ]);
    }

    public function allKfList()
    {
        $listGirl = [
            [
                'kf_account' => "201@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZTM3gMohG7j6Jfgea9kHKcfqdaQZC1yvXfBEn8gR5iaELzQQh48rUiaAA/300?wx_fmt=jpeg",
                'kf_id' => 2033,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "202@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZPjcgQ9Ax0LR6Faxdp1PGicGuXfDUFMs3ibzTY9My4K3CKxDZwNIN9U1g/300?wx_fmt=jpeg",
                'kf_id' => 2034,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "203@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZQdFAB0D6j8SYecPRhHTFaUMKGrPHp5CLusfuAxia78wxYsB4C9cHia7g/300?wx_fmt=jpeg",
                'kf_id' => 2035,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "204@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZPdEJrXCLvH5DBFIplODvx0QGoOOsZicPh7w13jHDfLqYTa2lh2ojAIQ/300?wx_fmt=jpeg",
                'kf_id' => 2036,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "205@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZlNfJ9g161ZIMuyR5U9n7C0d4YkpSCq3sAcnibufjmkibT6FF1zgbWJug/300?wx_fmt=jpeg",
                'kf_id' => 2037,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "206@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZjwlNm4wFJ1ghtwB34md5jah6ib4fHbiagHczFcyuKk2xPa5NU49Eulhg/300?wx_fmt=jpeg",
                'kf_id' => 2038,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "207@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZQDuLYnIzsPAqNU3tNYmNaamz43PXSXFH97CVmia9FMPqJy4CakvibaDQ/300?wx_fmt=jpeg",
                'kf_id' => 2039,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "208@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZXwtzu5aGhvZ9uqfbuPKnEGblIoVjwlpFvjiaf5BPj2w9vSian5LmWZEw/300?wx_fmt=jpeg",
                'kf_id' => 2040,
                'kf_nick' => "来自对象的消息"
            ],
        ];

        $listBoy = [
            [
                'kf_account' => "106@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZJDenRWsWoRSdclNG0q3Hgqu0eHO3yrxHibRNbqmkPCqrYV0rRSibsg6w/300?wx_fmt=jpeg",
                'kf_id' => 2043,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "105@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZybjZa1YtSuSe7RSfwf2b9SwfqDibTAJ8q5nUarCOk7A2hxcOLfgomibg/300?wx_fmt=jpeg",
                'kf_id' => 2044,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "108@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZ9k1FW9gGgiaAKRcMOBfAyU3v9CZEiarXbtRuzz2z0nHcgPRFcibKsYvzg/300?wx_fmt=jpeg",
                'kf_id' => 2041,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "104@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZy6JpJtJib30kYzNcIkUVe7T24ZZ8SNGJiaA9oxWoKPsdRdfkTWLPPuLg/300?wx_fmt=jpeg",
                'kf_id' => 2032,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "103@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZdcgBa3zbHvqwD1f798w6SIapuUNOt2CibxRgVibjvYDOf1uBjvOqtPKw/300?wx_fmt=jpeg",
                'kf_id' => 2031,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "102@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZakcrSfaxibVFFSffXfQLxpyMyZzY0tmhMJo6pn8WsmSUYIFac3Zj6dg/300?wx_fmt=jpeg",
                'kf_id' => 2030,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "101@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZt4slyf61tqzyWmgAcBXH8kgXX1TJMlZiaVOtzSPibEMIblvuvoJlcfVA/300?wx_fmt=jpeg",
                'kf_id' => 2029,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "107@duixiang",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZOenzCSY9hEU96VWrjbZg01uIw620XHTUrcazG0aj3lLLPNYZtA0ygA/300?wx_fmt=jpeg",
                'kf_id' => 2042,
                'kf_nick' => "来自对象的消息"
            ],
        ];

        $listSystem = [
            [
                'kf_account' => "duixiang@fpdx",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZibgGP0z2q8vXV5H6PEMdhHeerSItlUk7JT8MzQtibVPNDyA6SnI7n14Q/300?wx_fmt=jpeg",
                'kf_id' => 2002,
                'kf_nick' => "来自对象的消息"
            ],
            [
                'kf_account' => "notice@admin",
                'kf_headimgurl' => "http://mmbiz.qpic.cn/mmbiz_jpg/nAiaqJTVXP8XeDClnB1kUIydnyaQ6BSqZibgGP0z2q8vXV5H6PEMdhHeerSItlUk7JT8MzQtibVPNDyA6SnI7n14Q/300?wx_fmt=jpeg",
                'kf_id' => 2007,
                'kf_nick' => "系统消息"
            ],
        ];
        $data = [
            'boy' => $listBoy,
            'girl' => $listGirl,
            'system' => $listSystem
        ];

        return response([
            'errcode' => 0,
            'errmsg' => $data
        ]);
    }

    public function getActivityList()
    {
        $uid = Auth::auth();

        $lists = DB::table("kdgx_partner_charge_activity")
            ->join(
                "kdgx_partner_charge_pair",
                "kdgx_partner_charge_activity.stage_id",
                "kdgx_partner_charge_pair.stage_id"
            )
            ->where([['kdgx_partner_charge_pair.uid', $uid], ['kdgx_partner_charge_pair.hidden_at', 0]])
            ->orderBy("kdgx_partner_charge_pair.stage_id", "desc")->get();

        foreach ($lists as &$list) {
            $pair = PairModel::find($list->id);
            $progress = $pair->progress();
            $list->progress = $progress;

            $userInfo = DB::table("kdgx_partner_charge_pair")
                ->join("kdgx_partner_charge_user", "kdgx_partner_charge_pair.uid", "kdgx_partner_charge_user.uid")
                ->where([
                    ['kdgx_partner_charge_pair.uid', $uid],
                    ['kdgx_partner_charge_pair.stage_id', $list->stage_id]
                ])
                ->first();
            if (is_null($userInfo->assoc_id)) {
                $list->pair_info = ['user_info' => $userInfo];
            } else {
                $partnerInfo = DB::table("kdgx_partner_charge_pair")
                    ->join("kdgx_partner_charge_user", "kdgx_partner_charge_pair.uid", "kdgx_partner_charge_user.uid")
                    ->where('kdgx_partner_charge_pair.id', $userInfo->assoc_id)
                    ->first();
                if ($partnerInfo) {
                    try {
                        $roomInfo = RoomModel::findOrFail($partnerInfo->room_id);
                        $roomInfo->online = null;
                        $roomInfo->unread_msg = 0;
                    } catch (ModelNotFoundException $exception) {
                        $roomInfo = [];
                    }
                } else {
                    $roomInfo = [];
                }

                $list->pair_info = ['user_info' => $userInfo, 'partner_info' => $partnerInfo, 'room_info' => $roomInfo];
            }
        }
        return response([
            'errcode' => 0,
            'errmsg' => $lists
        ]);
    }

    public function getPair(Request $request)
    {
        $stage_id = $request->get('stage_id');
        $uid = Auth::auth();
        $data = PairModel::where([['uid', $uid], ['stage_id', $stage_id]])->firstOrFail();
        return response([
            'errcode' => 0,
            'errmsg' => $data
        ]);
    }

    public function getPairRoom(Request $request)
    {
        $stage_id = $request->get('stage_id');
        $uid = Auth::auth();
        $userInfo = DB::table("kdgx_partner_charge_pair")
            ->join("kdgx_partner_charge_user", "kdgx_partner_charge_pair.uid", "kdgx_partner_charge_user.uid")
            ->where([['kdgx_partner_charge_pair.uid', $uid], ['kdgx_partner_charge_pair.stage_id', $stage_id]])
            ->first();
        if (is_null($userInfo->assoc_id)) {
            $data = ['user_info' => $userInfo];
        } else {
            $partnerInfo = DB::table("kdgx_partner_charge_pair")
                ->join("kdgx_partner_charge_user", "kdgx_partner_charge_pair.uid", "kdgx_partner_charge_user.uid")
                ->where('kdgx_partner_charge_pair.id', $userInfo->assoc_id)
                ->first();
            try {
                $roomInfo = RoomModel::findOrFail($partnerInfo->room_id);
                $roomInfo->online = null;
                $roomInfo->unread_msg = 0;
            } catch (ModelNotFoundException $exception) {
                $roomInfo = [];
            }
            $data = ['user_info' => $userInfo, 'partner_info' => $partnerInfo, 'room_info' => $roomInfo];
        }
        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => $data
        ]);
    }

    /**
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @deprecated
     */
    public function getAll()
    {
        $datas = TagModel::get()->toArray();
        $result = array();
        foreach ($datas as $data) {
            $tmp = array(
                'id' => (string)$data['id'],
                'name' => $data['name'],
                'group' => (string)$data['group']
            );
            $result[$data['group']][$data['id']] = $tmp;
        }
        return response([
            'errcode' => 0,
            'errmsg' => $result
        ]);
    }

    public function getNotive(Request $request)
    {
        $id = $request->get('id');
        $result = NoticeModel::findOrFail($id);
        return response([
            'errcode' => 0,
            'errmsg' => $result
        ]);
    }

    public function readNotive(Request $request)
    {
        $id = $request->get('id');
        $data = NoticeModel::findOrFail($id);
        $data->is_read = 1;
        return response([
            'errcode' => 0,
            'errmsg' => true
        ]);
    }

    /**
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @deprecated Pair/Citylist
     */
    public function citylist()
    {
        $arrays = CityModel::groupBy("province")->get(['province']);
        $data = array();
        foreach ($arrays as &$array) {
            $data[$array->province] = CityModel::where(
                "province",
                $array->province
            )->groupBy("city")->orderBy("city")->get(['city'])->pluck('city')->toArray();
        }
        return response([
            'errcode' => 0,
            'errmsg' => $data
        ]);
    }

    /**
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @deprecated Pair/SearchSchool
     */
    public function searchSchool(Request $request)
    {
        $keyword = $request->get("keyword");
        $data = SchoolModel::where(
            "school",
            "like",
            "%{$keyword}%"
        )->orderBy("id")->get(['school'])->pluck('school')->toArray();
        return response([
            'errcode' => 0,
            'errmsg' => $data
        ]);
    }

    /** ************************************************************************************** */

    /**
     * 操作报名成功
     * @return array
     */
    public function successEnroll()
    {
        $uid = Auth::auth();
        $activitys = ActivityModel::getActivitys();
        $pair = PairModel::where([
            ['uid', $uid],
            ['stage_id', $activitys['next']]
        ])->first();
        if (collect($pair)->isEmpty()) {
            return [
                'code' => 101,
                'message' => '错误的卡片'
            ];
        }
        if ($pair->state < 100) {
            $pair->state += 100;
            $pair->save();
            return [
                'code' => 200,
                'message' => 'success'
            ];
        } else {
            return [
                'code' => 200,
                'message' => '已经报名成功'
            ];
        }
    }

    /**
     * 对卡片是否点赞
     * @param  Request  $request
     * @return array
     */
    public function isPraise(Request $request)
    {
        $partner_id = $request->partner_id;
        $uid = Auth::auth();
        $praise = \DB::table('kdgx_partner_charge_praise')->where([
            'uid' => $uid,
            'partner_id' => $partner_id,
            'type' => 1
        ])->first();
        if ($praise) {
            return [
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'praise' => 1,
                ]
            ];
        } else {
            return [
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'praise' => 0,
                ]
            ];
        }
    }

    /**
     * 获取某学校的男/女生数量
     * @param  Request  $request
     * @return array
     */
    public function getCountBySchool(Request $request)
    {
        $school = $request->input('school');
        $activitys = ActivityModel::getActivitys();
        $stage_id = $activitys['next'];
        $pairs = PairModel::where('stage_id', '=', $stage_id)
            ->whereNull('assoc_id')
            ->whereBetween('state', [100, 199])->get(['uid']);
        $boys = UserModel::where([
            ['school', $school],
            ['sex', 1]
        ])->whereIn('uid', $pairs->pluck('uid'))->count();
        $girls = UserModel::where([
            ['school', $school],
            ['sex', 2]
        ])->whereIn('uid', $pairs->pluck('uid'))->count();
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'boys' => $boys,
                'girls' => $girls
            ],
        );
    }

    /**
     * 获取某城市的男/女生数量
     * @param  Request  $request
     * @return array
     */
    public function getCountByAddress(Request $request)
    {
        $address = $request->input('address');
        $activitys = ActivityModel::getActivitys();
        $stage_id = $activitys['next'];
        $pairs = PairModel::where('stage_id', '=', $stage_id)
            ->whereNull('assoc_id')
            ->whereBetween('state', [100, 199])->get(['uid']);
        $boys = UserModel::where([
            ['address', $address],
            ['sex', 1]
        ])->whereIn('uid', $pairs->pluck('uid'))->count();
        $girls = UserModel::where([
            ['address', $address],
            ['sex', 2]
        ])->whereIn('uid', $pairs->pluck('uid'))->count();
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'boys' => $boys,
                'girls' => $girls
            ],
        );
    }

    /**
     * fpdx退款
     * @param  int  $pair_id
     * @return array
     * @throws DBException
     */
    public function refund(int $pair_id)
    {
        $uid = Auth::auth();
        $pair = PairModel::findOrFail($pair_id);
        if ($uid != $pair->uid) {
            return array(
                'code' => 403001,
                'message' => '无权限'
            );
        }
        if (
            $pair->state >= 300
            && $pair->state < 400
            || $pair->state >= 500
            && $pair->state < 600
            || $pair->state >= 900
            && $pair->state < 1000
        ) {
            switch ($pair->state % 100) {
                case 1:
                case 4:
                    if ($pair->pay > 0) {
                        $pay = $pair->pay;
                        $state = $pair->state;
                        $pair->pay = 0;
                        $pair->state = 600 + $pair->state % 100;
                        if ($pair->save()) {
                            try {
                                $order = new OrderService();
                                $order->refund($pair->order_id, $pay * 100, "72小时CP退款", true);
                                if ($pair->fx_money) {
                                    MediaOrderModel::create([
                                        'media_id' => $pair->media_id,
                                        'type' => 'refund',
                                        'amount' => -($pair->fx_money * 100),
                                        'tag' => '分配对象',
                                        'describe' => "用户分配对象活动第{$pair->stage_id}期退款（订单ID：{$pair->order_id}）",
                                    ]);
                                }
                                return array(
                                    'code' => 200,
                                    'message' => 'success'
                                );
                            } catch (\Exception $e) {
                                $pair->pay = $pay;
                                $pair->state = $state;
                                $pair->save();
                                return array(
                                    'code' => 504,
                                    'message' => $e->getMessage()
                                );
                            }
                        } else {
                            throw new DBException();
                        }
                    }
                    if ($pair->state > 900 && $pair->state < 1000) {
                        $pair->state = 1101;
                        if ($pair->save()) {
                            return array(
                                'code' => 200,
                                'message' => 'success'
                            );
                        } else {
                            throw new DBException();
                        }
                    } else {
                        $pair->state = 601;
                        if ($pair->save()) {
                            return array(
                                'code' => 200,
                                'message' => 'success'
                            );
                        } else {
                            throw new DBException();
                        }
                    }
                case 2:
                    $pair->state = 1102;
                    if ($pair->save()) {
                        return array(
                            'code' => 200,
                            'message' => 'success'
                        );
                    } else {
                        throw new DBException();
                    }
                case 3:
                    if ($pair->pay > 0) {
                        $pay = $pair->pay;
                        $state = $pair->state;
                        $pair->pay = 0;
                        if ($pair->state > 900 && $pair->state < 1000) {
                            $pair->state = 1103;
                        } else {
                            $pair->state = 603;
                        }
                        if ($pair->save()) {
                            try {
                                $order = new OrderService();
                                $order->refund($pair->order_id, $pay * 100, "72小时CP退款", true);
                                if ($pair->fx_money) {
                                    MediaOrderModel::create([
                                        'media_id' => $pair->media_id,
                                        'type' => 'refund',
                                        'amount' => -($pair->fx_money * 100),
                                        'tag' => '分配对象',
                                        'describe' => "用户分配对象活动第{$pair->stage_id}期退款（订单ID：{$pair->order_id}）",
                                    ]);
                                }
                                return array(
                                    'code' => 200,
                                    'message' => 'success'
                                );
                            } catch (\Exception $e) {
                                $pair->pay = $pay;
                                $pair->state = $state;
                                $pair->save();
                                return array(
                                    'code' => 504,
                                    'message' => $e->getMessage()
                                );
                            }
                        } else {
                            throw new DBException();
                        }
                    } else {
                        if ($pair->state > 900 && $pair->state < 1000) {
                            $pair->state = 1103;
                        } else {
                            $pair->state = 603;
                        }
                        if ($pair->save()) {
                            return array(
                                'code' => 200,
                                'message' => 'success'
                            );
                        } else {
                            throw new DBException();
                        }
                    }
            }
        } else {
            return array(
                'code' => 102,
                'message' => '订单不可退款'
            );
        }
    }

    /**
     * 报名下一期
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function enrollnext(Request $request)
    {
        $uid = Auth::auth();
        $this->validate($request, [
            'last_stage_id' => 'required',
            'allow_photo' => ''
        ]);
        $last_stage_id = $request->post('last_stage_id');
        $enroll = array(
            'allow_photo' => $request->post('allow_photo') ?? 0
        );
        $agent = $request->header('user-agent');
        $os = 'other';
        if (
            strpos($agent, 'macintosh')
            || strpos($agent, 'iPod')
            || strpos($agent, 'iPhone')
            || strpos($agent, 'iPad')
        ) {
            $os = "ios";
        }
        if (strpos($agent, 'Android')) {
            $os = 'android';
        }
        $ps = new PairService();
        $id = $ps->enrollNext($last_stage_id, $uid, $enroll, $os);
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'pair_id' => $id
            ]
        );
    }

    /**
     * 分配对象报名下单
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws ApiException
     * @deprecated
     */
    public function preEnroll(Request $request)
    {
        $this->validate($request, [
            'media_id' => 'required',
            'total_fee' => 'required',
            'stage_id' => 'required',
            'add_score' => '',
            'state' => '',
            'allow_photo' => '',
            'activity_type' => "in:72h,qbj"
        ]);
        $state = $request->input('state') ?? 101;
        $activity_type = $request->input('activity_type', '72h');
        $total_fee = $request->input('total_fee', 9.9);
        if ('qbj' == $activity_type) {
            $total_fee = 29.9;
        }

        $uid = Auth::auth();
        $user = UserModel::find($uid);
        if (!in_array($user->sex, [1, 2])) {
            return array(
                'code' => 202,
                'message' => "请补全性别"
            );
        }
        $stage_id = $request->input('stage_id');
        if (0 == $stage_id) {
            $ings = ActivityModel::getActivitys();
            $stage_id = $ings['next'];
        } else {
            /** @var ActivityModel $activity */
            $activity = ActivityModel::findOrFail($stage_id);
            if ($activity->signbegin_time > time() || $activity->signend_time < time()) {
                throw new AlertException("「{$stage_id}」期报名时间已结束");
            }
        }
        if ('qbj' == $activity_type) {
            // 当前期是否开启情报局
            $stage = ActivityModel::findOrFail($stage_id);
            if (0 == $stage->qbj_stage_id) {
                throw new AlertException("时遇记情报局暂未开放", 102);
            }

            // 72小时匹配成功过
            if (
                !PairModel::where('uid', $uid)->where(function ($query) {
                /** @var PairModel $query */
                    return $query->whereNotNull('assoc_id')
                    ->orWhere('last_assoc', '>', 0);
                })->first()
            ) {
                throw new AlertException("在72小时体验匹配成功过，才开启时遇记情报局资格");
            }
        }
        $pair = PairModel::where([['uid', $uid], ['stage_id', $stage_id]])->first();
        if ('qbj' == $activity_type && !collect($pair)->isEmpty()) {
            throw new AlertException("你已经报名了72小时恋爱体验，请勿重复报名哦", 101);
        }
        if (isset($pair->order_id) && $pair->order_id > 0) {
            return response([
                'code' => 203,
                'message' => '一次活动只能付费一次'
            ]);
        }
        $agent = $request->header('user-agent');
        $os = 'other';
        if (
            strpos($agent, 'macintosh')
            || strpos($agent, 'iPod')
            || strpos($agent, 'iPhone')
            || strpos($agent, 'iPad')
        ) {
            $os = "ios";
        }
        if (strpos($agent, 'Android')) {
            $os = 'android';
        }
        $media_id = $request->input('media_id');
        $data = [
            'uid' => $uid,
            'stage_id' => $stage_id,
            'media_id' => $media_id,
            'add_score' => $request->input('add_score') ?? 0,
            'allow_photo' => $request->input('allow_photo') ?? 0,
            'state' => $state,
            'sex' => $user->sex,
            'os' => $os,
            'activity_type' => $activity_type
        ];

        $orderObj = new Order();
        $order_id = $orderObj->unifyByFpdx($total_fee * 100, $data, $request);
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'order_id' => $order_id
            ],
        );
    }

    /**
     * 免费报名
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @deprecated
     */
    public function freeEnroll(Request $request)
    {
        $uid = Auth::auth();
        $this->validate($request, [
            'stage_id' => 'required',
            'media_id' => 'required',
            'state' => 'required',
            'add_score' => '',
            'allow_photo' => ''
        ]);
        $agent = $request->header('user-agent');
        $os = 'other';
        if (
            strpos($agent, 'macintosh')
            || strpos($agent, 'iPod')
            || strpos($agent, 'iPhone')
            || strpos($agent, 'iPad')
        ) {
            $os = "ios";
        }
        if (strpos($agent, 'Android')) {
            $os = 'android';
        }
        $data = array(
            'media_id' => $request->post('media_id') ?? config('miniprogram.public_id'),
            'state' => $request->post('state') ?? 2,
            'data' => $os,
            'add_score' => $request->post('score') ?? 0,
            'allow_photo' => $request->post('allow_photo') ?? 0
        );
        $stage_id = $request->post('stage_id');
        $ps = new PairService();
        $pair_id = $ps->freeEnroll($uid, $stage_id, $data);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => [
                'pair_id' => $pair_id
            ]
        ]);
    }

    /**
     * 超级VIP报名
     * @throws AlertException
     */
    public function supvipEnroll()
    {
        throw new AlertException("服务暂停");
    }

    /**
     * 分配对象支付成功业务处理
     * @param  OrderModel  $order
     * @return bool
     */
    public function payment(OrderModel $order)
    {
        if ($order->type != 3 || empty($order->attach_data)) {
            return false;
        } else {
            $attach = json_decode($order->attach_data, true);
            $user = UserModel::findOrFail($attach['uid']);
            if ($user->supvip_endat > time()) {
                $attach['state'] = 104;
                $max_score = 92;
            } else {
                $attach['state'] = 103;
                $max_score = 91;
            }
            $pair = PairModel::where('uid', $user->uid)
                ->where('stage_id', $attach['stage_id'])
                ->first();
            if (collect($pair)->isEmpty()) {
                $attach = array_merge($attach, [
                    'score' => $max_score,
                    'pay' => sprintf('%.2f', $order->cash_fee / 100),
                    'order_id' => $order->id,
                ]);
                $pair = PairModel::create($attach);
            } else {
                $pair->pay = $pair->pay + sprintf('%.2f', $order->cash_fee / 100);
                $pair->score = $max_score;
                $pair->order_id = $order->id;
                if ($pair->state < 100) {
                    $pair->state += 100;
                }
                $pair->save();
            }
        }
    }

    /**
     * @return array
     * @throws AlertException
     * @api 获取最近三个人的报名气泡
     * @deprecated Pair/Lastenroll
     */
    public function lastEnroll()
    {
        try {
            $ings = ActivityModel::getActivitys();
            /** @var Collection $pairs */
            $pairs = PairModel::where([
                ['stage_id', $ings['next']],
                ['state', '>', 100]
            ])->take(30)->orderBy('id', 'desc')
                ->get(['id', 'sex', 'stage_id', 'create_time', 'uid']);
            $users = UserModel::whereIn('uid', $pairs->pluck('uid'))->get([
                'uid',
                'headimgurl',
                'nickname',
                'sex',
                'address',
                'home'
            ]);
            foreach ($pairs as &$pair) {
                /** @var UserModel $tmp */
                $tmp = $users->where('uid', $pair->uid) ?? [];
                foreach ($tmp as $v) {
                    $pair->user = $v;
                }
            }
            return response([
                'code' => 200,
                'message' => 'success',
                'data' => $pairs
            ]);
        } catch (\Exception $e) {
            throw new AlertException($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取当前期男女比例
     * @return array
     * @deprecated Pair/SexProportion
     */
    public function sexProportion()
    {
        $ings = ActivityModel::getActivitys();
        $total = PairModel::where([
                ['stage_id', $ings['next']],
                ['state', '>', 100]
            ])->count() + 1;
        $boy = PairModel::where([
            ['stage_id', $ings['next']],
            ['state', '>', 100],
            ['sex', 1]
        ])->count();
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'boy' => $boy * 6,
                'girl' => ($total - $boy) * 6,
                'bl' => [
                    'boy' => 56,
                    'girl' => 44,
                ],
            ],
        );
    }

    /**
     * 通过小花提升成功率
     * @param  int  $pair_id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws ApiException
     * @throws DBException
     * @deprecated
     */
    public function addscorebyflower(int $pair_id, Request $request)
    {
        Auth::auth();
        $flowers = $request->only(['red_flower', 'gold_flower']);
        if (empty($flowers)) {
            throw new ApiException("网络繁忙|request", 101);
        }
        $ps = new PairService();
        $ps->addScoreByFlower($pair_id, $flowers);
        return response()->json([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 通过超级会员卡提升成功率
     * @param  int  $pair_id
     * @throws AlertException
     */
    public function addscorebysupvip(int $pair_id)
    {
        throw new AlertException("服务暂停{$pair_id}");
    }

    /**
     * 匹配成功-72-签到
     * @param  int  $pair_id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws DBException
     */
    public function confirm(int $pair_id, Request $request)
    {
        $this->validate($request, [
            'confirm' => 'required|in:-1,1'
        ]);
        Auth::auth();

        $ps = new PairService();
        $ps->confirmPair($pair_id, $request->input("confirm"));
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 匹配成功-72-签到反悔
     * @param  int  $pair_id
     * @return array
     * @throws AlertException
     */
    public function goBackConfirm(int $pair_id)
    {
        $uid = Auth::auth();

        $ps = new PairService();
        $ps->goBackConfirm($pair_id);

        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * @param  int  $stage_id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @deprecated Pair/ActivityInfo
     */
    public function getActivityInfo(int $stage_id)
    {
        $uid = Auth::auth();
        $ps = new PairService();
        $data = $ps->getActivityInfo($uid, $stage_id);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $data
        ]);
    }

    /**
     * 获取某人最近一期的活动状态
     *
     * @deprecated Pair/ActivityRecent
     */
    public function getRecentActivity()
    {
        $uid = Auth::auth();
        $ps = new PairService();
        $data = $ps->getRecentState($uid);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $data
        ]);
    }

    /**
     * 获取某人是否可以使用微信kf
     */
    public function isopenwxkf()
    {
        $uid = Auth::auth();
        $ps = new PairService();
        $bool = $ps->isopenwxkf($uid);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $bool
        ]);
    }


    /**
     * 报名列表
     * @param  Request  $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $uid = Auth::auth();
        $includes = explode(",", $request->get('include'));
        $pairs = PairModel::where('uid', $uid)->hidden()->paginate($request->get('pre_page', 10));
        foreach ($pairs as $pair) {
            foreach ($includes as $include) {
                $pair->$include;
            }
        }
        return PairResource::collection($pairs);
    }


    /**
     * 报名信息
     * @param  int  $pair_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(int $pair_id)
    {
        $uid = Auth::auth();
        $pair = PairModel::where('id', $pair_id)->firstOrFail();
        if ($pair->uid != $uid) {
            return response([
                'code' => 403001,
                'message' => '无权限'
            ]);
        }

        $pair->activity;
        $pair->user;

        // 伴侣
        if ($pair->assoc_id) {
            $partner_pair = PairModel::where('id', $pair->assoc_id)->first();
            if ($partner_pair) {
                $partner_pair->user;
            }
            $pair->partner_pair = $partner_pair;
            $pair->room;
            $pair->group;
        }
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $pair
        ]);
    }


    /**
     * 正在进行中的报名
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function currently(Request $request)
    {
        $uid = Auth::auth();
        $includes = explode(",", $request->get('includes', 'user'));
        $pair = PairModel::where('uid', $uid)->firstOrFail();
        if ($pair->uid != $uid) {
            return response([
                'code' => 403001,
                'message' => '无权限'
            ]);
        }
        foreach ($includes as $include) {
            $pair->$include;
        }
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $pair
        ]);
    }


    /**
     * 根据条件查找报名信息
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function find(Request $request)
    {
        $uid = Auth::auth();
        $pair = PairModel::where('uid', $uid)
            ->when($request->filled('stage_id'), function ($query) use ($request) {
                /** @var Builder $query */
                return $query->where('stage_id', $request->stage_id);
            })
            ->when($request->get('pair_id'), function ($query) use ($request) {
                /** @var Builder $query */
                return $query->where('id', $request->pair_id);
            })
            ->when($request->get('room_id'), function ($query) use ($request) {
                /** @var Builder $query */
                return $query->where('room_id', $request->room_id);
            })
            ->when($request->filled('group_id'), function ($query) use ($request) {
                /** @var Builder $query */
                return $query->where('group_id', $request->group_id);
            })->firstOrFail();
        $pair->activity;
        $pair->user;
        // 伴侣
        if ($pair->assoc_id) {
            $partner_pair = PairModel::where('id', $pair->assoc_id)->first();
            if ($partner_pair) {
                $partner_pair->user;
            }
            $pair->partner_pair = $partner_pair;
            $pair->room;
            $pair->group;
        }
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $pair
        ]);
    }


    /**
     * 最后一次匹配
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function last(Request $request)
    {
        $uid = Auth::auth();
        $includes = explode(",", $request->get('includes', 'user'));
        $pair = PairModel::where('uid', $uid)->orderBy('id', 'desc')->firstOrFail();
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $pair
        ]);
    }


    /**
     * 修改匹配信息
     * @param  Request  $request
     * @param $pair_id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function update(Request $request, $pair_id)
    {
        $uid = Auth::auth();
        $pair = PairModel::findOrFail($pair_id);
        if ($pair->uid != $uid) {
            return response([
                'code' => 403001,
                'message' => '无权限'
            ]);
        }
        if ($request->filled('hidden')) {
            $pair->hidden_at = $request->hidden ? time() : 0;
        }
        $pair->save();
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }


    /**
     * 添加落单，反悔日志
     * @param  Request  $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function operational(Request $request)
    {
        $this->validate($request, [
            'stage_id' => 'integer',
            'type' => 'required|in:alone,regrets',
            'content' => 'required|max:64',
        ]);
        $uid = Auth::auth();
        OperationalLogModel::create($request->merge(['uid' => $uid])->all());
        return response([
            'code' => 200,
            'message' => 'Success'
        ]);
    }
}
