<?php

namespace App\Managers;

use App\Exceptions\AlertException;
use App\Models\User\AuthKey;
use App\Services\Pair\NoticeService;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\InviteModel;
use App\Models\Fpdx\PairModel;
use App\Models\User\OpenidUserModel;
use App\Models\User\UserModel;
use App\Services\Pay\OrderService;

class SharePairManager
{
    /**
     * 获取邀请信息
     * @param  int  $list_id
     * @return array
     */
    public function get(int $list_id)
    {
        $score_count = InviteModel::where(array(['pair_id', $list_id], ['state', 0], ['invite_uid', '!=', 1]))->count();
        $pay_count = InviteModel::where(array(['pair_id', $list_id], ['state', 1]))->count();
        $invalid_count = InviteModel::where(array(['pair_id', $list_id], ['state', 2]))->count();
        $invites = InviteModel::where('pair_id', $list_id)->get();
        $auths = AuthKey::whereIn('auth_key', $invites->pluck('invite_uid')->toArray())->get();
        $users = UserModel::whereIn('uid', $auths->pluck('uid')->toArray())->get([
            'uid',
            'sex',
            'headimgurl',
            'nickname'
        ]);

        foreach ($invites as &$invite) {
            if (1 == $invite->invite_uid) {
                $invite->invite_user = [
                    'sex' => 0,
                    'headimgurl' => "https://oss.pocketuniversity.cn/media/2019-07-01/5d19dbb0260a7.jpg",
                    'nickname' => "公众号助力"
                ];
            } else {
                $auth = $auths->where('auth_key', $invite->invite_uid)->first();
                if (is_null($auth)) {
                    $openid = collect(OpenidUserModel::where("openid", $invite->invite_uid)->first())->toArray();
                    if (empty($openid)) {
                        $invite->invite_user = [];
                    } else {
                        $invite->invite_user = [
                            'sex' => $openid['sex'],
                            'headimgurl' => null,
                            'nickname' => null
                        ];
                    }
                } else {
                    $invite->invite_user = $users->where('uid', $auth->uid)->first();
                }
            }
        }

        return array(
            'score_count' => $score_count,
            'pay_count' => $pay_count,
            'invalid_count' => $invalid_count,
            'list' => $invites
        );
    }

    /**
     * 正在进行的分享列表
     * @param  int  $uid
     * @return array
     */
    public function inglist(int $uid): array
    {
        $ings = ActivityModel::getActivitys();
        $data = PairModel::where([
            ['stage_id', $ings['next']],
            ['uid', $uid]
        ])->first();
        if (collect($data)->isEmpty()) {
            return array();
        } else {
            $activity = ActivityModel::find($ings['next']);
            $tmp = [
                'id' => $data->id,
                'expired_at' => $activity->signend_time,
            ];
            if ($data->order_id > 0) {
                $tmp['type'] = 5;
                $tmp['photo'] = 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c7ac8c90.png';
                $tmp['title'] = '报名费退款分享';
                $tmp['desc'] = "分享成功后可退还你的报名费";
                $tmp['completeness'] = sprintf('%d', (9.9 - $data->pay) / 9.9 * 100);
            } else {
                $tmp['type'] = 2;
                $tmp['photo'] = 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c43125ec.png';
                $tmp['title'] = '成功率提升分享';
                $tmp['desc'] = "成功后可提升活动匹配优先级";
                $tmp['completeness'] = $data->score + $data->add_score;
            }
            $res[] = $tmp;
            return $res;
        }
    }

    /**
     * 成功率列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function scorelist(int $uid, array $pages): array
    {
        $ings = ActivityModel::getActivitys();
        $total = PairModel::where([
            ['stage_id', '<', $ings['next']],
            ['uid', $uid],
            ['order_id', 0]
        ])->count();
        $datas = PairModel::where([
            ['stage_id', '<', $ings['next']],
            ['uid', $uid],
            ['score', 90],
            ['order_id', 0]
        ])->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' => 2,
            );
        }
        return [
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $res
        ];
    }

    /**
     * 退费列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function refundlist(int $uid, array $pages): array
    {
        $ings = ActivityModel::getActivitys();
        $total = PairModel::where([
            ['stage_id', '<', $ings['next']],
            ['uid', $uid],
            ['score', 90],
            ['order_id', '>', 0]
        ])->count();
        $datas = PairModel::where([
            ['stage_id', '<', $ings['next']],
            ['uid', $uid],
            ['score', 90],
            ['order_id', '>', 0]
        ])->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/5bbd7c7ac8c90.png',
                'title' => '报名费退款分享',
                'desc' => '分享成功后可退还你的报名费',
                'completeness' => sprintf('%d', (9.9 - $data->pay) / 9.9 * 100),
                'type' => 5,
            );
        }
        return [
            'total' => $total,
            'page' => $pages['page'],
            'limit' => $pages['limit'],
            'list' => $res
        ];
    }

    /**
     * 邀请助力
     * @param  string  $openid
     * @param  int  $pair_id
     * @return array
     * @throws AlertException
     * @throws \Throwable
     */
    public function check(string $openid, int $pair_id): array
    {
        /** @var PairModel $pair */
        $pair = PairModel::findOrFail($pair_id);
        $authkey = AuthKey::where('uid', $pair->uid)->get()->pluck('auth_key')->toArray();
        if (in_array($openid, $authkey)) {
            throw new AlertException("不能给自己助力", 101);
        }

        $activitys = ActivityModel::getActivitys();
        if ($pair->stage_id != $activitys['next']) {
            throw new AlertException('啊偶，该助力申请过期啦。', 103);
        }
        if (
            InviteModel::where([
            ['pair_id', $pair->id],
            ['invite_uid', $openid]
            ])->exists()
        ) {
            if ($openid == 1) {
                throw new AlertException('你已领取会员专属成功率，用其他方式提升吧。', 104);
            }
            throw new AlertException('你已经帮ta助力过了哦', 104);
        }
        if (
            InviteModel::where([
                ['invite_uid', $openid],
                ['create_at', '>', mktime(0, 0, 0)]
            ])->count() > 2 && $openid != 1
        ) {
            throw new AlertException('你今日的助力机会用完啦，明天再帮ta助力吧', 105);
        }

        $sex_k = 0.5;
        $comment = array(
            '希望这世界上从此少一个单身狗',
            '希望你不在是一个人过',
            '祝脱单',
            '成了别忘了发红包',
            '等着吃你的喜糖',
            '直觉告诉我，你这次要脱单',
            '坐等吃狗粮',
            '我已经准备好，喝喜酒的红包',
            '你这波突然袭击，很skr',
            '单身的终点，浪漫的节点，幸福的起点',
            '这波操作很骚',
            '大吉大利，今晚脱单',
            '请接收我1w点的助力暴击',
            '行动才是脱单的纲领，你做到了',
            '我很介意你单身，so赶紧脱单',
            '明天，我希望可以给你发来脱单贺电',
            '我感受到爱情的航班在呼唤你',
            '这波操作很骚',
        );
        $data = array(
            'uid' => $pair->uid,
            'pair_id' => $pair->id,
            'stage_id' => $pair->stage_id,
            'invite_uid' => $openid,
            'comment' => $comment[rand(0, 16)],
            'create_at' => time(),
        );
        if ($pair->score < 90) {
            // 增加score
            $data['state'] = 0;
            $r = sprintf('%.1f', rand(3, 10) / 10);
            $rand = sprintf('%d', (90 - $pair->score) * $sex_k * $r);
            if ($openid == 1) {
                $rand = rand(10, 20);
            }
            $rand = intval($rand) < 1 ? 1 : intval($rand);
            $dis_score = ($pair->score + $rand) > 90 ? 90 - $pair->score : $rand;
            $data['dis_score'] = $dis_score;
            PairModel::where('id', $pair_id)->increment('score', $dis_score);
            if ($pair->state < 100) {
                PairModel::where('id', $pair_id)->where('state', '<', 100)->increment('state', 100);
                try {
                    $noticeService = new NoticeService();
                    $noticeService->inviteToSuccess($pair->uid);
                } catch (\Exception $e) {
                }
            } else {
                try {
                    // 邀请好友助力通知
                    $noticeService = new NoticeService();
                    $noticeService->inviteToScore($pair->uid, $pair->id);
                    // 帮助好友助力通知
                    // $noticeService->HelpToScore($openid, $pair->id);
                } catch (\Exception $e) {
                }
            }
        } elseif ($pair->pay > 0 && $openid != 1) {
            // 退款
            $data['state'] = 1;
            $r = sprintf('%.1f', rand(3, 10) / 10);
            $rand = 1;
            $dis_score = ($pair->pay - $rand) < 0 ? $pair->pay : $rand;
            $data['dis_score'] = $dis_score;
            if ($dis_score > 0) {
                try {
                    $orderObj = new OrderService();
                    $orderObj->refund($pair->order_id, $dis_score * 100, "72小时助力退款", true);
                    PairModel::where('id', $pair->id)->decrement('pay', $dis_score);
                    try {
                        $noticeService = new NoticeService();
                        $noticeService->inviteToRefund($pair->uid, $pair->id, $dis_score);
                    } catch (\Exception $e) {
                    }
                } catch (\Exception $exception) {
                    $data['state'] = 2;
                    $data['dis_score'] = 0;
                }
            } else {
                throw new AlertException('如有疑问，可以联系客服，请将问题反馈给我们', 505);
            }
        } else {
            // 无效的邀请
            $data['state'] = 2;
            $data['dis_score'] = 0;
        }
        $inviteModel = new InviteModel();
        $invite = $inviteModel->fill($data);
        if ($invite->save()) {
            $pairUser = UserModel::find($pair->uid);
            return array(
                'state' => $data['state'],
                'dis_score' => $data['dis_score'],
                'comment' => $data['comment'],
                'user' => [
                    'nickname' => $pairUser->nickname
                ]
            );
        } else {
            throw new AlertException('如有疑问，可以联系客服，请将问题反馈给我们', 505);
        }
    }

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

        $pair = PairModel::findOrFail($pairId);
        if ($uid != $pair->uid) {
            throw new AlertException("只能为助力自己", 102);
        }

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

        return $data;
    }
}
