<?php

namespace App\Http\Controllers\Welfare;

use App\Models\User\UserModel;
use App\Services\Welfare\NoticeService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Miniprogram\Auth;
use App\Models\Welfare\LotteryModel;
use App\Models\Welfare\TicketModel;

class LotteryController extends Controller
{


    /**
     * 抽奖活动列表
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function lotterys(Request $request)
    {
        $per_page = $request->input('per_page', 20);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $per_page;
        $uid = Auth::auth();
        $builder = LotteryModel::where('drawed_at', '>', time())->where('showed_at', '<=', time())->where(
            'deleted_at',
            0
        );
        $count = $builder->count();
        $lotterys = $builder->orderBy('drawed_at', 'asc')->offset($offset)->limit($per_page)->get();
        foreach ($lotterys as $item) {
            $item->get_ticket = TicketModel::where('lottery_id', $item->id)->where('uid', $uid)->first() ? true : false;
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'list' => $lotterys,
                'count' => $count,
                'per_page' => $per_page,
                'page' => $page
            ]
        ]);
    }


    public function historys(Request $request)
    {
        $per_page = $request->input('per_page', 14);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $per_page;
        $builder = LotteryModel::where('drawed_at', '<', time())->where('deleted_at', 0);
        $count = $builder->count();
        $lotterys = $builder->orderBy('drawed_at', 'desc')->offset($offset)->limit($per_page)->get();
        foreach ($lotterys as $item) {
            $tickets = TicketModel::where('lucky', '>', 0)->where('lottery_id', $item->id)->get();
            foreach ($tickets as $ticket) {
                $user = UserModel::find($ticket->uid);
                $ticket->nickname = $user->nickname;
                $ticket->headimgurl = $user->headimgurl;
            }
            $item->luckys = $tickets;
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'list' => $lotterys,
                'count' => $count,
                'per_page' => $per_page,
                'page' => $page
            ]
        ]);
    }


    /**
     * 抽中的列表
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function luckys(Request $request)
    {
        $lotterys = LotteryModel::where('drawed_at', '<', time())->pluck('id');
        $tickets = TicketModel::where('lucky', '>', 0)->whereIn('lottery_id', $lotterys)->orderBy(
            'created_at',
            'desc'
        )->limit(50)->get();
        foreach ($tickets as $ticket) {
            $user = UserModel::find($ticket->uid);
            $ticket->nickname = $user->nickname;
            $ticket->headimgurl = $user->headimgurl;
            $lottery = LotteryModel::find($ticket->lottery_id);
            $ticket->title = $lottery->title;
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'list' => $tickets
            ]
        ]);
    }


    /**
     * 我的抽奖历史
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function myLotterys(Request $request)
    {
        $uid = Auth::auth();
        $per_page = $request->input('per_page', 20);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $per_page;
        $builder = LotteryModel::where(function ($query) use ($uid) {
            return $query->whereIn('id', TicketModel::where('uid', $uid)->distinct()->pluck('lottery_id'));
        })->where('deleted_at', 0);
        $count = $builder->count();
        $lotterys = $builder->orderBy('drawed_at', 'desc')->offset($offset)->limit($per_page)->get();

        foreach ($lotterys as $lottery) {
            $lottery->lucky_ticket_count = TicketModel::where('lottery_id', $lottery->id)->where(
                'uid',
                $uid
            )->where('lucky', '>', 0)->count();
            $lottery->unlucky_ticket_count = TicketModel::where('lottery_id', $lottery->id)->where(
                'uid',
                $uid
            )->where('lucky', 0)->count();
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'list' => $lotterys,
                'count' => $count,
                'per_page' => $per_page,
                'page' => $page
            ]
        ]);
    }


    /**
     * 抽奖活动详情
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function lottery(Request $request)
    {
        $lottery = LotteryModel::find($request->id);
        if (!$lottery) {
            return response()->json([
                'code' => 404,
                'message' => '不存在',
            ]);
        }
        if ($lottery->drawed_at < time()) {
            $luckys = TicketModel::where('lottery_id', $lottery->id)->where('lucky', 1)->get();
            foreach ($luckys as $lucky) {
                $user = UserModel::find($lucky->uid);
                $lucky->nickname = $user->nickname;
                $lucky->headimgurl = $user->headimgurl;
            }
            $lottery->luckys = $luckys;
        }
        $lottery->lucky_ticket_count = 0;
        $lottery->unlucky_ticket_count = 0;
        $uid = Auth::auth();
        $tickets = TicketModel::where('lottery_id', $lottery->id)->where('uid', $uid)->orderBy('id', 'desc')->get();
        foreach ($tickets as $ticket) {
            switch ($ticket->type) {
                case '领取':
                case '分享助力':
                    $userinfo = UserModel::where('uid', $ticket->uid)->first();
                    $ticket->nickname = $userinfo->nickname;
                    $ticket->headimgurl = $userinfo->headimgurl;
                    break;
                case '好友助力':
                    $userinfo = UserModel::where('uid', $ticket->value)->first();
                    $ticket->nickname = $userinfo->nickname;
                    $ticket->headimgurl = $userinfo->headimgurl;
                    break;
            }
            if ($ticket->lucky) {
                $lottery->lucky_ticket_count += 1;
            } else {
                $lottery->unlucky_ticket_count += 1;
            }
        }
        $lottery->tickets = $tickets;
        return response()->json([
            'code' => 200,
            'data' => $lottery
        ]);
    }


    /**
     * 领取我的抽奖码
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function ticket(Request $request)
    {
        $uid = Auth::auth();
        $lottery = LotteryModel::find($request->id);
        if (!$lottery) {
            return response()->json([
                'code' => 404,
                'message' => '不存在',
            ]);
        }
        if ($lottery->drawed_at < time()) {
            return response()->json([
                'code' => 10001,
                'message' => '活动已开奖'
            ]);
        }
        if (TicketModel::where('uid', $uid)->where('type', '领取')->where('lottery_id', $lottery->id)->first()) {
            return response()->json([
                'code' => 10002,
                'message' => '已经领取'
            ]);
        }
        $ticket = TicketModel::create([
            'uid' => $uid,
            'type' => '领取',
            'lottery_id' => $lottery->id,
            'ticket_code' => getChars(6),
        ]);
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => $ticket
        ]);
    }


    /**
     * 邀请
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function invitation(Request $request)
    {
        $uid = Auth::auth();
        $lottery_id = $request->input('id');
        $inviter_uid = $request->input('inviter');

        if (TicketModel::where(['lottery_id' => $lottery_id, 'uid' => $uid, 'type' => '领取'])->first()) {
            return response()->json([
                'code' => 10001,
                'message' => '已经领取',
            ]);
        }

        // 邀请者+3，最多10个
        for ($i = 0; $i < 3; $i++) {
            if (TicketModel::where(['uid' => $inviter_uid, 'lottery_id' => $lottery_id])->count() < 10) {
                TicketModel::create([
                    'uid' => $inviter_uid,
                    'type' => '好友助力',
                    'value' => $uid,
                    'lottery_id' => $lottery_id,
                    'ticket_code' => getChars(6),
                ]);
            }
        }

        try {
            $ns = new NoticeService();
            $ns->helpToScore($uid, $inviter_uid);

            $ns->inviteToScore($inviter_uid, $uid);
        } catch (\Exception $e) {
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK'
        ]);
    }


    /**
     * 首次分享
     * @param  Request  $request
     * @return array|\Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function firstInvitation(Request $request)
    {
        $uid = Auth::auth();
        $id = $request->id;
        $ticket = TicketModel::where('uid', $uid)->where('type', '分享助力')->where('lottery_id', $id)->first();
        if ($ticket) {
            return ['code' => 10001, 'message' => '已分享'];
        }
        $ticket = TicketModel::create([
            'uid' => $uid,
            'type' => '分享助力',
            'lottery_id' => $id,
            'ticket_code' => getChars(6),
        ]);
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => $ticket
        ]);
    }
}
