<?php

namespace App\Managers;

use App\Models\Fpdx\PairModel;
use App\Models\Fpdx\RoomModel as PairRoomModel;
use App\Models\Friends\FriendApply;
use App\Models\Friends\FriendApplyModel;
use App\Models\Friends\FriendContact;
use App\Models\Friends\FriendModel;
use App\Models\Goodnight\RoomModel as goodnightRoomModel;
use App\Models\Gteam\RoomModel as gameRoomModel;
use App\Models\NoticeModel;
use App\Models\PraiseModel;
use App\Models\User\LikeInviteQuestionModel;
use App\Models\User\UserModel;
use App\Models\Friends\LogModel;
use App\Services\IM\CustomElem;
use App\Utils\ImUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

class FriendManager
{

    public function makeZeroUnreadMsg(int $uid, int $contactUid)
    {
        FriendContact::where([
            array('uid', $uid), array('friend_uid', $contactUid)
        ])->update(['unread_cnt' => 0]);
    }

    /**
     * 是否可以IM通信
     * @param int $uid
     * @param int $contactUid
     * @return bool
     */
    public function canIm(int $uid, int $contactUid): bool
    {
        if (
            FriendContact::where([
                array('uid', $uid), array('friend_uid', $contactUid), array('is_blacklist', 1)
            ])->orWhere([
                array('uid', $contactUid), array('friend_uid', $uid), array('is_blacklist', 1)
            ])->exists()
        ) {
            return false;
        }
        return true;
    }

    /**
     * 成为普通联系人
     * @param  int  $uid
     * @param  int  $contactUid
     * @throws \Throwable
     */
    public function beContact(int $uid, int $contactUid)
    {
        $contact = FriendContact::where([
            array('uid', $uid), array('friend_uid', $contactUid)
        ])->first();
        if ($contact && $contact->friend_level == 2) {
            return;
        }
        DB::transaction(function () use ($uid, $contactUid) {
            FriendContact::updateOrCreate([
                'uid' => $uid,
                'friend_uid' => $contactUid
            ], [
                'friend_level' => 1
            ]);
            FriendContact::updateOrCreate([
                'uid' => $contactUid,
                'friend_uid' => $uid
            ], [
                'friend_level' => 1
            ]);
        });

        $imUtil = new ImUtil();

        $receiveUser = UserModel::find($contactUid, ['uid', 'im_account']);
        $message = new CustomElem('EventBeContact', ['Uid' => $contactUid, 'Contact' => $uid]);
        $imUtil->sendMessage("system_event", $receiveUser->im_account, [$message->toArray()]);

        $sendUser = UserModel::find($uid, ['uid', 'im_account']);
        $message = new CustomElem('EventBeContact', ['Uid' => $uid, 'Contact' => $contactUid]);
        $imUtil->sendMessage("system_event", $sendUser->im_account, [$message->toArray()]);
    }

    /**
     * 成为好友联系人
     * @param int $uid
     * @param int $contactUid
     * @throws \Throwable
     */
    public function beFriend(int $uid, int $contactUid)
    {
        DB::transaction(function () use ($uid, $contactUid) {
            FriendContact::updateOrCreate([
                'uid' => $uid,
                'friend_uid' => $contactUid
            ], [
                'friend_level' => 2
            ]);
            FriendContact::updateOrCreate([
                'uid' => $contactUid,
                'friend_uid' => $uid
            ], [
                'friend_level' => 2
            ]);
            // 清理好友申请
            FriendApply::where([
                array('uid', $uid), array('apply_uid', $contactUid)
            ])->orWhere([
                array('uid', $contactUid), array('apply_uid', $uid)
            ])->update(['handle' => 1]);
        });

        $imUtil = new ImUtil();

        $receiveUser = UserModel::find($contactUid, ['uid', 'im_account']);
        $message = new CustomElem('EventBeFriend', ['Uid' => $contactUid, 'Contact' => $uid]);
        $imUtil->sendMessage("system_event", $receiveUser->im_account, [$message->toArray()]);

        $sendUser = UserModel::find($uid, ['uid', 'im_account']);
        $message = new CustomElem('EventBeFriend', ['Uid' => $uid, 'Contact' => $contactUid]);
        $imUtil->sendMessage("system_event", $sendUser->im_account, [$message->toArray()]);
    }

    /**
     * 全部好友列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function getAllList(int $uid, array $pages): array
    {
        $total = FriendModel::where(array(['uid', $uid], ['is_hide', 0]))->count();
        $datas = FriendModel::where([['uid', $uid], ['is_hide', 0]])->orderBy('last_at', 'desc')
            ->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $friend_uids = $datas->pluck('friend_uid')->toArray();
        $users = UserModel::whereIn('uid', $friend_uids)->get([
            'uid',
            'headimgurl',
            'nickname',
            'sex',
            'weixin',
            'qq',
            'identity_auth',
            'wx_auth',
            'be_vip_at',
            'supvip_endat'
        ]);
        $datas->map(function (/** @var FriendModel $data */ &$data) use ($users) {
            $data->setAttribute('friend', $users->where('uid', $data->friend_uid)->first());
        });
        return array(
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas
        );
    }

    /**
     * 获取全部申请
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function getApplyAllList(int $uid, array $pages): array
    {
        $total = FriendApplyModel::where([['uid', $uid], ['is_hide', 0]])->count();

        $datas = FriendApplyModel::where([['uid', $uid], ['is_hide', 0]])
            ->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])
            ->orderByDesc('last_at')
            ->get();
        $applyUids = $datas->pluck('apply_uid')->toArray();
        $users = UserModel::whereIn('uid', $applyUids)->get([
            'uid',
            'headimgurl',
            'nickname',
            'sex',
            'weixin',
            'qq',
            'identity_auth',
            'wx_auth',
            'be_vip_at',
            'supvip_endat'
        ]);
        $datas->map(function (&$data) use ($users) {
            $data->apply_user = $users->where('uid', $data->apply_uid)->first();
        });
        return array(
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas
        );
    }

    /**
     * 发出的好友申请
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function getSendList(int $uid, array $pages): array
    {
        $total = FriendApplyModel::where([['uid', $uid], ['is_apply', 1], ['is_hide', 0]])->count();

        $datas = FriendApplyModel::where([['uid', $uid], ['is_apply', 1], ['is_hide', 0]])
            ->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])
            ->orderByDesc('last_at')
            ->get();
        $toUids = $datas->pluck('apply_uid')->toArray();
        $users = UserModel::whereIn('uid', $toUids)->get([
            'uid',
            'headimgurl',
            'nickname',
            'sex',
            'weixin',
            'qq',
            'identity_auth',
            'wx_auth',
            'be_vip_at',
            'supvip_endat'
        ]);
        $datas->map(function (/** @var FriendApplyModel $data */ &$data) use ($users) {
            $data->setAttribute('apply_user', $users->where('uid', $data->apply_uid)->first());
        });
        return array(
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas
        );
    }

    /**
     * 收到的好友申请
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function getReceiveList(int $uid, array $pages): array
    {
        $total = FriendApplyModel::where([['uid', $uid], ['is_receive', 1], ['is_hide', 0]])->count();

        $datas = FriendApplyModel::where([['uid', $uid], ['is_receive', 1], ['is_hide', 0]])
            ->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])
            ->orderByDesc('last_at')
            ->get();
        $toUids = $datas->pluck('apply_uid')->toArray();
        $users = UserModel::whereIn('uid', $toUids)->get([
            'uid',
            'headimgurl',
            'nickname',
            'sex',
            'weixin',
            'qq',
            'identity_auth',
            'wx_auth',
            'be_vip_at',
            'supvip_endat'
        ]);
        $datas->map(function (/** @var FriendApplyModel $data */ &$data) use ($users) {
            $data->setAttribute('apply_user', $users->where('uid', $data->apply_uid)->first());
        });
        return array(
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas
        );
    }

    /**
     * 相互心动列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function getEachLikeList(int $uid, array $pages): array
    {
        $total = FriendModel::where(array(['uid', $uid], ['each_like', 1], ['is_hide', 0]))->count();
        $datas = FriendModel::where([['uid', $uid], ['each_like', 1], ['is_hide', 0]])->orderByDesc('last_at')
            ->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $friend_uids = $datas->pluck('friend_uid')->toArray();
        $users = UserModel::whereIn('uid', $friend_uids)->get([
            'uid',
            'headimgurl',
            'nickname',
            'sex',
            'weixin',
            'qq',
            'identity_auth',
            'wx_auth',
            'be_vip_at',
            'supvip_endat'
        ]);
        $datas->map(function (/** @var FriendModel $data */ &$data) use ($users) {
            $data->setAttribute('friend', $users->where('uid', $data->friend_uid)->first());
        });
        return array(
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas
        );
    }

    /**
     * 星标好友列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function getStarList(int $uid, array $pages): array
    {
        $total = FriendModel::where(array(['uid', $uid], ['star_at', '>', 0], ['is_hide', 0]))->count();
        $datas = FriendModel::where([['uid', $uid], ['star_at', '>', 0], ['is_hide', 0]])->orderByDesc('last_at')
            ->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $friend_uids = $datas->pluck('friend_uid')->toArray();
        $users = UserModel::whereIn('uid', $friend_uids)->get([
            'uid',
            'headimgurl',
            'nickname',
            'sex',
            'weixin',
            'qq',
            'identity_auth',
            'wx_auth',
            'be_vip_at',
            'supvip_endat'
        ]);
        $datas->map(function (&$data) use ($users) {
            $data->friend = $users->where('uid', $data->friend_uid)->first();
        });
        return array(
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas
        );
    }

    /**
     * 交互历史
     * @param  int  $uid
     * @param  int  $friend_uid
     * @param  array  $pages
     * @return array
     */
    public function getHistory(int $uid, int $friend_uid, array $pages)
    {
        $total = LogModel::where(array(['uid', $uid], ['tuid', $friend_uid]))
            ->orWhere(array(['uid', $friend_uid], ['tuid', $uid]))
            ->count();
        $datas = LogModel::where(array(['uid', $uid], ['tuid', $friend_uid]))
            ->orWhere(array(['uid', $friend_uid], ['tuid', $uid]))
            ->skip(($pages['page'] - 1) * $pages['limit'])
            ->take($pages['limit'])
            ->orderBy('created_at')
            ->get();

        $datas->map(function (/** @var LogModel $data */ &$data) use ($uid) {
            switch ($data->do) {
                case 0: // 相互心动
                    $data->setAttribute('type', 'each_like');
                    $data->setAttribute('app_type', 'each_like');
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "恭喜！你们相互心动啦，已交换联系方式");
                    } else {
                        $data->setAttribute("msg", "恭喜！你们相互心动啦，已交换联系方式");
                    }
                    break;
                case 1: // 取消心动
                    $data->setAttribute('type', 'each_like');
                    $data->setAttribute('app_type', 'each_like');
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "你取消了心动，好友关系解除");
                    } else {
                        $data->setAttribute("msg", "对方取消了心动，好友关系解除");
                    }
                    break;
                case 2: // 72h匹配
                    $attach = $data->attach;
                    /** @var PairRoomModel $room */
                    $room = PairRoomModel::find($attach['room_id'], ['created_at', 'room_id', 'stage_id']);
                    if (PairModel::where(['room_id' => $room->room_id])->value('activity_type') == 'qbj') {
                        $data->setAttribute('type', 'qbj');
                    } else {
                        $data->setAttribute('type', 'pair');
                    }
                    $data->setAttribute('app_type', 'pair');
                    $data->attach = $room;
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "你们通过72小时CP相识，成为好友");
                    } else {
                        $data->setAttribute("msg", "你们通过72小时CP相识，成为好友");
                    }
                    break;
                case 3: // 好友申请
                    if ($data->uid == $uid) {
                        $data->setAttribute('type', 'my_invite');
                    } else {
                        $data->setAttribute('type', 'friend_invite');
                    }
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "你向ta发出了好友申请");
                    } else {
                        $data->setAttribute("msg", "你收到ta发出的好友申请");
                    }
                    $data->setAttribute('app_type', 'invalid');
                    $attachs = $data->attach;
                    if (is_array($attachs)) {
                        foreach ($attachs as &$attach) {
                            if (isset($attach['type'])) {
                                switch ($attach['type']) {
                                    case 0:  # 打招呼
                                        $data->setAttribute('app_type', 'friend_invite_hello');
                                        $data->setAttribute("msg", $attach['answer']['value']);
                                        break;
                                    case -1: # 无考验
                                    case 1:  # 爆照
                                        break;
                                    case 2: # 问答
                                        $data->setAttribute('app_type', 'friend_invite_anwser');
                                        $data->setAttribute("msg", "我还回答了你的一个问题");
                                        $question = LikeInviteQuestionModel::withTrashed()->find($attach['question']);
                                        $question->question = json_decode($question->question, true);
                                        $attach['question'] = $question;
                                        break;
                                    case 3: # 接唱
                                        $data->setAttribute('app_type', 'friend_invite_sing');
                                        $data->setAttribute("msg", "我还给你唱了一首歌");
                                        $question = LikeInviteQuestionModel::withTrashed()->find($attach['question']);
                                        $question->question = json_decode($question->question, true);
                                        $attach['question'] = $question;
                                        break;
                                    case 4: # 走心一画
                                        $data->setAttribute('app_type', 'friend_invite_draw');
                                        $data->setAttribute("msg", "我还给你画了一幅画");
                                        break;
                                    default:
                                        $data->setAttribute('app_type', 'invalid');
                                        $question = LikeInviteQuestionModel::withTrashed()->find($attach['question']);
                                        $question->question = json_decode($question->question, true);
                                        $attach['question'] = $question;
                                        break;
                                }
                            } else {
                                $attachs = [$attachs];
                                break;
                            }
                        }
                    }
                    $data->attach = $attachs;
                    break;
                case 4: // 同意好友申请
                    $data->setAttribute('type', 'agree_apply');
                    $data->setAttribute('app_type', 'agree_apply');
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "你接受了对方的好友申请，成功交换联系方式");
                    } else {
                        $data->setAttribute("msg", "对方接受了你的好友申请，成功交换联系方式");
                    }
                    break;
                case 5: // 开黑-王者荣耀
                    $data->setAttribute('type', 'game_wz');
                    $data->setAttribute('app_type', 'game_wz');
                    $attach = $data->attach;
                    /** @var gameRoomModel $room */
                    $room = gameRoomModel::find($attach['id'], ['id', 'created_at', 'type']);
                    $data->attach = $room;
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "你们通过组CP打王者相识，成为好友");
                    } else {
                        $data->setAttribute("msg", "你们通过组CP打王者相识，成为好友");
                    }
                    break;
                case 6: // 开黑-吃鸡
                    $data->setAttribute('type', 'game_cj');
                    $data->setAttribute('app_type', 'game_cj');
                    $attach = $data->attach;
                    /** @var gameRoomModel $room */
                    $room = gameRoomModel::find($attach['id'], ['id', 'created_at', 'type']);
                    $data->attach = $room;
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "你们通过组CP玩吃鸡相识，成为好友");
                    } else {
                        $data->setAttribute("msg", "你们通过组CP玩吃鸡相识，成为好友");
                    }
                    break;
                case 7: // 晚安
                    $data->setAttribute('type', 'goodnight');
                    $data->setAttribute('app_type', 'goodnight');
                    $attach = $data->attach;
                    $room = goodnightRoomModel::find($attach['id'], ['id', 'created_at']);
                    $data->attach = $room;
                    if ($data->uid == $uid) {
                        $data->setAttribute("msg", "你们通过晚安伴侣相识，成为好友");
                    } else {
                        $data->setAttribute("msg", "你们通过晚安伴侣相识，成为好友");
                    }
                    break;
                default:
                    $data->setAttribute('app_type', 'invide');
                    break;
            }
        });
        $apply_friend = FriendModel::applyOrFriend($uid, $friend_uid);
        // 清空未读标记
        FriendModel::where([['uid', $uid], ['friend_uid', $friend_uid]])->update(['unread_cnt' => 0]);
        FriendApplyModel::where([['uid', $uid], ['apply_uid', $friend_uid]])->update(['unread_cnt' => 0]);
        return array(
            'apply_friend' => $apply_friend,
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $datas
        );
    }

    /**
     * 好友列表数字 全部：未读 | 相互喜欢：未读 | 收到邀请：未读 | 发出邀请：未读
     * @param  int  $uid
     * @return array
     */
    public function getUnreadCount(int $uid)
    {
        /** @var UserModel $user */
        $user = UserModel::findOrFail($uid);

        // 喜欢我的
        /** @var PraiseModel $like_me */
        $like_me = PraiseModel::where([['read', 0], ['partner_id', $user->partner_id], ['type', 1]])->count();

        // 相互喜欢的
        /** @var FriendModel $model */
        $eachlike = FriendModel::where([['uid', $uid], ['each_like', 1], ['is_hide', 0]])->sum('unread_cnt');

        $invite_me = FriendApplyModel::where([
            ['uid', $uid],
            ['is_hide', 0]
        ])->sum('unread_cnt');
        $send_invite = 0;

        // 系统消息
        if (in_array(Config::get("platform"), ['ios', 'android'])) {
            // APP通知
            if (Config::get("version") < "2.17.6") {
                $shield = [20, 13, 14];
            } else {
                $shield = [20];
            }
        } else {
            // 小程序通知
            $shield = [5];
        }
        $sys_notice = NoticeModel::where([['uid', $uid], ['is_read', 0]])->whereIn('type', $shield)->count();

        // 全部好友
        $all = FriendModel::where([
            ['uid', $uid],
            ['is_hide', 0]
        ])->sum('unread_cnt');

        return array(
            'all' => (int)$all,
            'each_like' => (int)$eachlike,
            'invite_me' => (int)$invite_me,
            'send_invite' => (int)$send_invite,
            'like_me' => (int)$like_me,
            'sys_notice' => (int)$sys_notice
        );
    }
}
