<?php

namespace App\Services\Share;

use App\Exceptions\AlertException;
use App\Exceptions\DBException;
use App\Models\BuyInviteListModel;
use App\Models\BuyInviteModel;
use App\Models\PartnerModel;
use App\Models\RecodeModel;
use App\Models\User\UserModel;
use App\Services\Service;
use App\Services\User\PartnerService;
use Illuminate\Http\Response;

class LockService extends Service
{
    /**
     * 正在解锁的卡片
     * @param  int  $uid
     * @return array
     */
    public function inglist(int $uid): array
    {
        $recodes = RecodeModel::where('uid', $uid)->get();
        $listmodel = new BuyInviteListModel();
        $datas = $listmodel->where([
            ['uid', $uid],
            ['expired_at', '>', time()],
        ])->whereNotIn('partner_id', $recodes->pluck('partner_id'))
            ->orderBy('id', 'desc')->get();
        $ps = new PartnerService();
        foreach ($datas as &$data) {
            $partner = $ps->get($data->partner_id);
            $data->photo = "https://oss.pocketuniversity.cn/media/2018-10-10/5bbd93dbc013b.png";
            isset($partner->photo_4) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_4}";
            isset($partner->photo_3) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_3}";
            isset($partner->photo_2) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_2}";
            isset($partner->photo_1) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_1}";
            isset($partner->photo_src) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_src}";
            $data->type = 1;
            $data->title = '解锁分享';
            $data->desc = "成功后可解锁对方联系方式";
            $data->completeness = $listmodel->effectiveInvite($data->id);
        }

        return $datas->toArray();
    }

    /**
     * 成功列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function succlist(int $uid, array $pages): array
    {
        $recodes = RecodeModel::where('uid', $uid)->get();
        $listmodel = new BuyInviteListModel();
        $total = $listmodel->where('uid', $uid)->whereIn('partner_id', $recodes->pluck('partner_id'))->count();
        $datas = $listmodel->where('uid', $uid)->whereIn('partner_id', $recodes->pluck('partner_id'))
            ->orderBy('id', 'desc')->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $ps = new PartnerService();
        foreach ($datas as &$data) {
            $partner = $ps->get($data->partner_id);
            $data->photo = "https://oss.pocketuniversity.cn/media/2018-10-10/5bbd93dbc013b.png";
            isset($partner->photo_4) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_4}";
            isset($partner->photo_3) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_3}";
            isset($partner->photo_2) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_2}";
            isset($partner->photo_1) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_1}";
            isset($partner->photo_src) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_src}";
            $data->type = 1;
            $data->title = '解锁分享';
            $data->desc = "成功后可解锁对方联系方式";
        }

        return [
            'page' => $pages['page'],
            'total' => $total,
            'limit' => $pages['limit'],
            'list' => $datas->toArray(),
        ];
    }

    /**
     * 失败列表
     * @param  int  $uid
     * @param  array  $pages
     * https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7bedb5f9b.png
     * @return array
     */
    public function faillist(int $uid, array $pages): array
    {
        $recodes = RecodeModel::where('uid', $uid)->get();
        $listmodel = new BuyInviteListModel();
        $total = $listmodel->where([
            ['uid', $uid],
            ['expired_at', '<', time()],
        ])->whereNotIn('partner_id', $recodes->pluck('partner_id'))->count();
        $datas = $listmodel->where([
            ['uid', $uid],
            ['expired_at', '<', time()],
        ])->whereNotIn('partner_id', $recodes->pluck('partner_id'))->orderBy('id', 'desc')
            ->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $ps = new PartnerService();
        foreach ($datas as &$data) {
            $partner = $ps->get($data->partner_id);
            $data->photo = "https://oss.pocketuniversity.cn/media/2018-10-10/5bbd93dbc013b.png";
            isset($partner->photo_4) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_4}";
            isset($partner->photo_3) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_3}";
            isset($partner->photo_2) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_2}";
            isset($partner->photo_1) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_1}";
            isset($partner->photo_src) && $data->photo = "https://oss.pocketuniversity.cn{$partner->photo_src}";
            $data->type = 1;
            $data->title = '解锁分享';
            $data->desc = "成功后可解锁对方联系方式";
        }

        return [
            'page' => $pages['page'],
            'total' => $total,
            'limit' => $pages['limit'],
            'list' => $datas->toArray(),
        ];
    }

    /**
     * 核销解锁助力
     * @param  int  $uid
     * @param  int  $list_id
     * @return Response
     * @throws AlertException
     * @throws DBException
     * @throws \Throwable
     */
    public function check(int $uid, int $list_id): array
    {
        $invite = BuyInviteListModel::findOrFail($list_id);
        $rs = new RedpackService();
        try {
            $rs->check($uid, $invite->uid);
        } catch (\Exception $e) {
        }
        if ($invite->expired_at < time()) {
            throw new AlertException("链接失效", 105);
        }
        if (
            BuyInviteModel::where([
            ['invite_id', $list_id],
            ['invite_uid', $uid],
            ])->exists()
        ) {
            throw new AlertException("你已经帮ta助力过了哦", 102);
        }
        $inviteModel = new BuyInviteModel();
        if (
            $inviteModel->where([
                ['invite_uid', $uid],
                ['created_at', '>', mktime(0, 0, 0)],
            ])->count() > 2
        ) {
            throw new AlertException("你今日的助力机会用完啦，明天再帮ta助力吧", 103);
        }
        $model = new BuyInviteListModel();
        $process = $model->effectiveInvite($list_id);
        if ($process == 100) {
            throw new AlertException("该助力已结束，卡片成功解锁啦", 104);
        }
        $comment = array(
            '希望这世界上从此少一个单身狗',
            '希望你不在是一个人过',
            '祝脱单',
            '成了别忘了发红包',
            '等着吃你的喜糖',
            '直觉告诉我，你这次要脱单',
            '坐等吃狗粮',
            '我已经准备好，喝喜酒的红包',
            '你这波突然袭击，很skr',
            '单身的终点，浪漫的节点，幸福的起点',
            '这波操作很骚',
            '大吉大利，今晚脱单',
            '请接收我1w点的助力暴击',
            '行动才是脱单的纲领，你做到了',
            '我很介意你单身，so赶紧脱单',
            '明天，我希望可以给你发来脱单贺电',
            '我感受到爱情的航班在呼唤你',
            '这波操作很骚',
        );
        $rand = rand(0, 16);
        $fill = array(
            'invite_id' => $list_id,
            'invite_uid' => $uid,
            'state' => 0,
            'comment' => $comment[$rand],
        );
        $user = UserModel::findOrFail($uid);
        if ($user->sex == 2) {
            $sex_k = 0.8;
        } else {
            $sex_k = 0.5;
        }
        $r = sprintf('%.1f', rand(3, 10) / 10);
        $dis_score = sprintf('%d', (100 - $process) * $sex_k * $r);
        $dis_score = $dis_score < 1 ? 1 : $dis_score;
        $fill['dis_score'] = $dis_score;
        $list = new BuyInviteModel();
        $liModel = $list->fill($fill);
        $liModel->save();
        try {
            $lModel = new BuyInviteListModel();
            $lModel->autoUnlock($list_id);
        } catch (\Exception $e) {
            $liModel->delete();
            throw new DBException("解锁异常, 请将问题反馈给我们", 505);
        }
        $user = UserModel::findOrFail($invite->uid);
        return response([
            'score' => $dis_score,
            'user' => [
                'nickname' => $user->nickname,
            ],
        ]);
    }

    /**
     * 创建卡片分享
     * @param  int  $uid
     * @param  int  $partner_id
     * @return array
     * @throws AlertException
     * @throws DBException
     */
    public function store(int $uid, int $partner_id)
    {
        $partner = PartnerModel::findOrFail($partner_id);
        if (1 != $partner->is_sell || 0 != $partner->is_hide) {
            throw new AlertException("卡片不存在", 404);
        }
        if (
            RecodeModel::where([
            ['uid', $uid],
            ['partner_id', $partner_id],
            ])->exists()
        ) {
            throw new AlertException("该卡片已经被解锁", 202);
        }
        $listmodel = new BuyInviteListModel();
        $list = $listmodel->where([
            ['uid', $uid],
            ['partner_id', $partner_id],
            ['expired_at', '>', time()],
        ])->first();
        if (collect($list)->isEmpty()) {
            $list = $listmodel->fill([
                'uid' => $uid,
                'partner_id' => $partner_id,
                'expired_at' => time() + 86400,
            ]);
            if ($list->save()) {
                return $list->toArray();
            } else {
                throw new DBException("网络异常，请重新尝试或联系客服", 500);
            }
        } else {
            return $list->toArray();
        }
    }
}
