<?php

namespace App\Managers;

use App\Exceptions\AlertException;
use App\Models\PartnerModel;
use App\Models\PraiseModel;
use App\Models\Share\LikemeCheckModel;
use App\Models\User\UserModel;
use App\Services\Share\NoticeService;
use Illuminate\Support\Facades\DB;

class LikeManager
{
    /**
     * 核销解锁助力
     * @param  int  $uid
     * @param  int  $invite_id
     * @return array
     * @throws \Exception
     */
    public function check(int $uid, int $invite_id): array
    {
        $invite = PraiseModel::findOrFail($invite_id);

        if ($invite->lock >= 100) {
            throw new AlertException("该助力已结束，卡片成功解锁啦", 104);
        }

        if (LikemeCheckModel::where([['praise_id', $invite_id], ['invite_uid', $uid]])->exists()) {
            throw new AlertException("你已经帮ta助力过了哦", 102);
        }

        $user = UserModel::findOrFail($uid);
        if (
            $user->partner_id != $invite->partner_id
            && LikemeCheckModel::where([['invite_uid', $uid], ['created_at', '>', mktime(0, 0, 0)]])->count() > 2
        ) {
            throw new AlertException("你今日的助力机会用完啦，明天再帮ta助力吧", 103);
        }

        DB::beginTransaction();
        try {
            $likememodel = new LikemeCheckModel();
            $likeme = $likememodel->fill([
                'praise_id' => $invite->id,
                'partner_id' => $invite->partner_id,
                'uid' => $invite->uid,
                'invite_uid' => $uid
            ]);

            $dis_score = min(ceil(max((100 - $invite->lock) * max(
                sprintf("%.2f", 0 + mt_rand() / mt_getrandmax() * 1),
                0.2
            ), 15)), 100 - $invite->lock);
            $likeme->dis_score = $dis_score;
            $likeme->save();

            PraiseModel::where('id', $invite->id)->increment('lock', $likeme->dis_score);

            DB::commit();

            $islike = UserModel::where('partner_id', $invite->partner_id)->first();
            if ($user->partner_id != $invite->partner_id) {
                $ns = new NoticeService();
                $ns->inviteToLock($islike->uid, $uid, $invite->id);
            }

            return array(
                'dis_score' => $likeme->dis_score,
                'user' => [
                    'nickname' => $islike->nickname
                ]
            );
        } catch (\Exception $exception) {
            DB::rollBack();
            throw $exception;
        }
    }

    /**
     * 获取某个邀请的助力历史
     * @param  int  $invite_id
     * @return array
     */
    public function history(int $invite_id): array
    {
        $invites = LikemeCheckModel::where('praise_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  $invite_id
     * @return array
     */
    public function get(int $invite_id): array
    {
        $praise = PraiseModel::findOrFail($invite_id);

        $like = UserModel::findOrFail($praise->uid);

        $partner = PartnerModel::findOrFail($like->partner_id);
        $partner->photo_src = empty($partner->photo_src) ? null : "http://oss.pocketuniversity.cn{$partner->photo_src}";
        $partner->photo_1 = empty($partner->photo_1) ? null : "http://oss.pocketuniversity.cn{$partner->photo_1}";
        $partner->photo_2 = empty($partner->photo_2) ? null : "http://oss.pocketuniversity.cn{$partner->photo_2}";
        $partner->photo_3 = empty($partner->photo_3) ? null : "http://oss.pocketuniversity.cn{$partner->photo_3}";
        $partner->photo_4 = empty($partner->photo_4) ? null : "http://oss.pocketuniversity.cn{$partner->photo_4}";

        $islike = UserModel::where('partner_id', $praise->partner_id)->first();

        $lock_cnt = LikemeCheckModel::where('praise_id', $praise->id)->count();

        return array(
            'praise_id' => $praise->id,
            'updated_at' => $praise->updated_at,
            'lock' => $praise->lock,
            'lock_cnt' => $lock_cnt,
            'partner' => array(
                'id' => $partner->id,
                'partner_id' => $partner->id,
                'photo_src' => $partner->photo_src,
                'photo_1' => $partner->photo_1,
                'photo_2' => $partner->photo_2,
                'photo_3' => $partner->photo_3,
                'photo_4' => $partner->photo_4,
                'voice' => $partner->voice,
                'praises' => $partner->praises,
            ),
            'user' => array(
                'uid' => $like->uid,
                'nickname' => $like->nickname,
                'sex' => $like->sex
            )
        );
    }
}
