<?php

namespace App\Services\Share;

use App\Exceptions\AlertException;
use App\Exceptions\ApiException;
use App\Models\Gteam\ActivityModel;
use App\Models\Gteam\EnterInviteModel;
use App\Models\Gteam\EnterModel;
use App\Models\User\UserModel;
use App\Services\Service;

class GteamService extends Service
{
    /**
     * 正在进行的分享列表
     * @param  int  $uid
     * @return array
     */
    public function inglist(int $uid): array
    {
        $activitys = ActivityModel::where('match_end_at', '>', time())->get();
        $res = array();
        foreach ($activitys as $activity) {
            $data = EnterModel::where([
                ['activity_id', $activity->id],
                ['uid', $uid],
            ])->first();
            if (collect($data)->isEmpty()) {
                continue;
            } else {
                $tmp = [
                    'id' => $data->id,
                    'expired_at' => $activity->match_end_at,
                ];
                $tmp['type'] = 6;
                $tmp['photo'] = 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c43125ec.png';
                $tmp['title'] = '成功率提升分享';
                $tmp['desc'] = "成功后可提升活动匹配优先级";
                $tmp['completeness'] = $data->score;
                $res[] = $tmp;
            }
        }

        return $res;
    }

    /**
     * 成功率列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function succlist(int $uid, array $pages): array
    {
        $activity = ActivityModel::where('match_end_at', '<', time())->orderBy('id', 'desc')->first();
        $total = EnterModel::where([
            ['activity_id', '<=', $activity->id],
            ['uid', $uid],
        ])->count();
        $datas = EnterModel::where([
            ['activity_id', '<=', $activity->id],
            ['uid', $uid],
            ['score', 90],
        ])->orderBy('id', 'desc')->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $res = array();
        foreach ($datas as $data) {
            $res[] = array(
                'id' => $data->id,
                'expired_at' => time() - 86400,
                'photo' => 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c43125ec.png',
                'title' => '成功率提升分享',
                'desc' => '成功后可提升活动匹配优先级',
                'completeness' => $data->score + $data->add_score,
                'type' => 6,
            );
        }

        return [
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $res,
        ];
    }

    /**
     * 获取最近的报名气泡
     * @param  int  $activity_id
     * @return array
     */
    public function lastInvite(int $activity_id): array
    {
        $invites = EnterInviteModel::where([
            ['activity_id', $activity_id],
            ['state', '!=', 2],
        ])->take(30)->groupBy('enter_id')->get(['uid', 'enter_id']);
        foreach ($invites as $k => &$invite) {
            try {
                $invite->user = UserModel::findOrFail(
                    $invite->uid,
                    ['uid', 'headimgurl', 'nickname', 'sex', 'address', 'home']
                );
                $invite->invite = array(
                    'count' => EnterInviteModel::where([
                        ['state', 0],
                        ['enter_id', $invite->enter_id],
                    ])->count(),
                    'dis_score' => EnterInviteModel::where([
                        ['state', 0],
                        ['enter_id', $invite->enter_id],
                    ])->sum('dis_score'),
                );
            } catch (\Exception $e) {
                unset($invites->$k);
                continue;
            }
        }

        return $invites->toArray();
    }

    /**
     * 获取某个邀请的助力历史
     * @param  int  $invite_id
     * @return array
     */
    public function history(int $invite_id): array
    {
        $invites = EnterInviteModel::where('enter_id', $invite_id)->get();
        foreach ($invites as $k => &$invite) {
            try {
                $invite->user = UserModel::findOrFail($invite->invite_uid, ['uid', 'headimgurl', 'nickname', 'sex']);
            } catch (\Exception $e) {
                unset($invites->$k);
                continue;
            }
        }

        return $invites->toArray();
    }

    /**
     * 公众号助力
     * @param  int  $uid
     * @param  int  $invite_id
     * @return array
     * @throws AlertException
     */
    public function vipCheck(int $uid, int $invite_id): array
    {
        $user = UserModel::findOrFail($uid);
        if ($user->be_vip_at == 0) {
            throw new AlertException("你还不是会员", 101);
        }

        $enter = EnterModel::findOrFail($invite_id);
        if ($enter->uid != $uid) {
            throw new AlertException("只能助力自己", 101);
        }

        $data = $this->check(1, $enter->id);

        return $data;
    }

    /**
     * 邀请助力
     * @param  int  $uid
     * @param  int  $enter_id
     * @return array
     * @throws AlertException
     */
    public function check(int $uid, int $enter_id): array
    {
        $enter = EnterModel::findOrFail($enter_id);

        $activity = ActivityModel::findOrFail($enter->activity_id);
        if (time() > $activity->match_end_at) {
            throw new AlertException('啊偶，该助力申请过期啦。', 103);
        }

        if (
            EnterInviteModel::where([
            ['enter_id', $enter->id],
            ['invite_uid', $uid],
            ])->exists()
        ) {
            if ($uid == 1) {
                throw new AlertException('你已领取会员专属成功率，用其他方式提升吧。', 104);
            }
            throw new AlertException('你已经帮ta助力过了哦', 104);
        }
        if (
            EnterInviteModel::where([
                ['invite_uid', $uid],
                ['created_at', '>', mktime(0, 0, 0)],
            ])->count() > 2 && $uid != 1
        ) {
            throw new AlertException('你今日的助力机会用完啦，明天再帮ta助力吧', 105);
        }

        $sex_k = 0.5;
        $comment = array(
            '希望这世界上从此少一个单身狗',
            '希望你不在是一个人过',
            '祝脱单',
            '成了别忘了发红包',
            '等着吃你的喜糖',
            '直觉告诉我，你这次要脱单',
            '坐等吃狗粮',
            '我已经准备好，喝喜酒的红包',
            '你这波突然袭击，很skr',
            '单身的终点，浪漫的节点，幸福的起点',
            '这波操作很骚',
            '大吉大利，今晚脱单',
            '请接收我1w点的助力暴击',
            '行动才是脱单的纲领，你做到了',
            '我很介意你单身，so赶紧脱单',
            '明天，我希望可以给你发来脱单贺电',
            '我感受到爱情的航班在呼唤你',
            '这波操作很骚',
        );
        $data = array(
            'uid' => $enter->uid,
            'enter_id' => $enter->id,
            'activity_id' => $enter->activity_id,
            'invite_uid' => $uid,
            'comment' => $comment[rand(0, 16)],
            'created_at' => time(),
        );
        if ($enter->score < 90) {
            // 增加score
            $data['state'] = 0;
            $r = sprintf('%.1f', rand(3, 10) / 10);
            $rand = sprintf('%d', (90 - $enter->score) * $sex_k * $r);
            if ($uid == $enter->uid) {
                $rand = rand(5, 10);
            }
            if ($uid == 1) {
                $rand = rand(10, 20);
            }
            $rand = intval($rand) < 1 ? 1 : intval($rand);
            $dis_score = ($enter->score + $rand) > 90 ? 90 - $enter->score : $rand;
            $data['dis_score'] = $dis_score;
            EnterModel::where('id', $enter_id)->increment('score', $dis_score);
            // 通知
            try {
                $ns = new \App\Services\Gteam\NoticeService();
                $ns->inviteToScore($enter->uid, $uid, $enter->id);

                $ns->helpToScore($uid, $enter->uid, $enter->id);
            } catch (\Exception $e) {
                app('sentry')->captureException($e);
            }
        } else {
            // 无效的邀请
            $data['state'] = 2;
            $data['dis_score'] = 0;
        }
        $inviteModel = new EnterInviteModel();
        $invite = $inviteModel->fill($data);
        if ($invite->save()) {
            $enterUser = UserModel::find($enter->uid);

            return array(
                'state' => $data['state'],
                'dis_score' => $data['dis_score'],
                'comment' => $data['comment'],
                'user' => [
                    'nickname' => $enterUser->nickname,
                    'headimgurl' => $enterUser->headimgurl,
                ],
            );
        } else {
            throw new AlertException('如有疑问，可以联系客服，请将问题反馈给我们', 505);
        }
    }

    /**
     * 公众号助力
     * @param  string  $openid
     * @return int
     * @throws AlertException
     * @throws ApiException
     */
    public function gzhzl(string $openid): int
    {
        $resp = \DB::table('kddx_user_openid')->where("openid", $openid)->first();
        if (collect($resp)->isEmpty()) {
            throw new ApiException("未绑定uid,点此回到活动首页");
        }
        $activity = ActivityModel::whereBetween(
            'match_end_at',
            [mktime(0, 0, 0), mktime(0, 0, 0) + 86400]
        )->firstOrFail();
        $enter = EnterModel::where([
            ['activity_id', $activity->id],
            ['uid', $resp->uid],
        ])->first();
        if (collect($enter)->isEmpty()) {
            throw new ApiException("未找到本期报名记录,点此回到活动首页");
        }
        if ($enter->score >= 90) {
            throw new ApiException("本期助力已经达上限,点此回到活动首页");
        }
        $data = $this->check(1, $enter->id);

        return $enter->id;
    }
}
