<?php

namespace App\Http\Controllers\H5;

use App\Facades\HttpService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\Lottery;
use App\Models\LotteryAward;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class LotteryController extends Controller
{
    use ResponseJson;

    public function lottery(Lottery $lottery)
    {
        $lottery->awards = $lottery->awards()->withCount('members')->get();
        return $this->success('ok', $lottery);
    }

    public function members(Lottery $lottery)
    {
        $members = $lottery->members;
        //缓存当前用户
        Cache::put("lottery:{$lottery->id}:members", $members, now()->addDays(7));
        return $this->success('ok', $members);
    }

    public function winningMembers(Lottery $lottery)
    {
        $limit = 0;
        $award_id = request()->award_id;
        $members = $lottery->winMembers()->with('award:id,lottery_id,level,awards')->whereHas('award');
        if ($award_id) {
            $members = $members->where('award_id', $award_id);
            $award = LotteryAward::find($award_id);
            if ($award->is_refresh) {
                $limit = $award->each_num;
            }
        }
        if ($limit) {
            $members = $members->limit($limit);
        }
        $members = $members->orderByDesc('id')->get();
        $win_count = $lottery->winMembers()->count();
        return $this->success('ok', compact('members', 'win_count'));
    }

    public function storeMembers(Request $request, Lottery $lottery)
    {
        if ($lottery->id == 1) return $this->failure("经销商活动不允许报名");
        $data = $request->all();
        $user_id = auth()->id();
        $res = $lottery->members()->where("user_id", $user_id)->exists();
        if ($res) return $this->failure("已报名成功,请勿反复操作");
        $data['user_id'] = $user_id;
        $lottery->members()->create($data);
        return $this->success('ok');
    }

    public function lotto(Lottery $lottery, LotteryAward $award)
    {
        //中奖人数
        $award_num = $lottery->winMembers()->whereHas('award')->award($award->id)->count();
        if ($award->num <= $award_num) return $this->failure("中奖人数上限");
        if ($lottery->id != $award->lottery_id) throw new \Exception("奖品和抽奖活动不对应");
        $members = Cache::get("lottery:{$lottery->id}:members");
        if (empty($members))  {
            $members = $lottery->members;
        }
        $user_ids = $members->pluck('user_id')->toArray();
//        $user_ids = $lottery->members()->pluck('user_id')->toArray();
        if (!$lottery->repeat) {//不可重复中奖
            $winning_user_ids = $lottery->winMembers()->whereHas('award')->pluck('user_id')->toArray();
            $user_ids = array_diff($user_ids, $winning_user_ids);
        }
        // if (!count($user_ids)) return $this->failure("抽奖池不足");

        //如果是id=1经销商活动， 更新抽奖码中奖信息
        if ($lottery->id == 1) {
            $index = array_rand($user_ids);
            $user_id = $user_ids[$index];
            $member = $members->where('user_id', $user_id)->first()->toArray();
            $member['award_id'] = $award->id;
            $win_member = $lottery->winMembers()->create($member);
            $id = $member['id'];
            // $url = config('app.shop_url') . "admin/sync/agent/lotto/info";
            // $param = ['code'=>$win_member->code, 'award'=>$award->awards, 'title'=>$award->level, 'member_id'=>$id];
            // HttpService::postData($url, $param);
            return $this->success('ok', compact('id'));
        }else {
            if (count($user_ids) < 10) return $this->failure("抽奖池不足");
            shuffle($user_ids);
            $out_user_ids = array_slice($user_ids, 0, 10);
            $member = $members->where('user_id', $out_user_ids[0])->first()->toArray();
            $id = $member['id'];
            $members = $members->whereIn('user_id', $out_user_ids)->all();
            $data = [];
            foreach ($members as $member) {
                // $data[] = ['user_id'=>$member['user_id'], 'lottery_id'=>$member['lottery_id'],'name'=>$member['name'],
                //             "mobile"=>$member['mobile'], 'award_id'=>$award->id];
                $member['award_id'] = $award->id;
                $win_member = $lottery->winMembers()->create($member->toArray());

            }

            // $lottery->winMembers()->upsert($data,['user_id', 'lottery_id']);
            return $this->success('ok', compact('id'));
        }
    }

    public function lottoV2(Lottery $lottery, LotteryAward $award)
    {
        //中奖人数
        $award_num = $lottery->winMembers()->whereHas('award')->award($award->id)->count();
        if ($award->num <= $award_num) return $this->failure("中奖人数上限");
        if ($lottery->id != $award->lottery_id) throw new \Exception("奖品和抽奖活动不对应");
        $members = Cache::get("lottery:{$lottery->id}:members");
        if (empty($members))  {
            $members = $lottery->members;
        }
        //总报名成员id
        $member_ids = $members->pluck('id')->toArray();
        if (!$lottery->repeat) {//不可重复中奖
            $winning_member_ids = $lottery->winMembers()->whereHas('award')->pluck('member_id')->toArray();
            $member_ids = array_diff($member_ids, $winning_member_ids);
        }
        //剩余中奖人数
        $remain_num = $award->num - $award_num;
        if ($remain_num > $award->each_num) {
            $remain_num = $award->each_num;
        }
        if (count($member_ids) < $remain_num) return $this->failure("抽奖池不足");
        shuffle($member_ids);
        $ids = array_slice($member_ids, 0, $remain_num);
        $members = $members->whereIn('id', $ids)->all();
        $data = [];
        foreach ($members as $member) {
             $data[] = ['member_id'=>$member->id,  'user_id'=>$member['user_id'], 'lottery_id'=>$member['lottery_id'],'name'=>$member['name'],
                         "mobile"=>$member['mobile'], 'code'=>$member['code'], 'award_id'=>$award->id];
        }
        $lottery->winMembers()->upsert($data,['user_id', 'lottery_id']);
        return $this->success('ok', compact('ids'));

    }

    public function addQuotas($lottery_id, LotteryAward $award)
    {
        $award->increment('num');
        return $this->success('ok');
    }
}
