<?php

namespace App\Http\Controllers\api;

use App\Constants\HttpStatus;
use App\Models\PaymentOrder;
use App\Models\ActivityReward as ActivityRewardModel;
use App\Models\ActivityUser;
use App\Models\Config;
use App\Models\Recharge;
use App\Services\ActivityRewardService;
use App\Services\ActivityUserService;
use App\Services\ConfigService;
use App\Services\PhoneCodeService;
use App\Services\SmsService;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;


class ActivityReward extends BaseController
{

    //活动规则
    public function rule(): JsonResponse
    {
        try {
            $data['rule'] = ConfigService::getVal("activity_rule");
            $data['service_customer'] = ConfigService::getVal("benefits_service_customer");
            $data['rebate']['title'] = ConfigService::getRemark("benefits_bibi_return");
            $data['rebate']['sub_title'] = ConfigService::getVal("benefits_bibi_return");
        } catch (Exception $e) {
            return $this->error($e->getMessage(), [], $e->getCode());
        }
        return $this->success($data);
    }

    //验证手机号
    public function verifyPhone(): JsonResponse
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'member_id' => ['required', 'integer'],
                'phone' => ['required', 'string'],
                'code' => ['required', 'string'],
                'visitor_id' => ['required', 'string', 'min:1', 'max:32'],
            ]);
            PhoneCodeService::verify($params['phone'], $params['code'], $params['member_id'], $params['visitor_id']);
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage(), [], $e->getCode());
        }
        return $this->success();
    }

    //发送手机验证码
    public function sendPhoneCode(): JsonResponse
    {
        try {
            $params = request()->validate([
                'phone' => ['required', 'string'],
            ]);
            $keys = [
                'phone' => $params['phone'],
                'ip' => request()->ip(),
                'action' => request()->route()->getActionName(),
            ];
            $key = 'api_request_' . md5(json_encode($keys));
            if (!Cache::has($key)) {
                Cache::put($key, true, 60);
                $code = SmsService::sendPhoneCode($params['phone']);
                PhoneCodeService::add($params['phone'], $code);
            }
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage(), [], $e->getCode());
        }
        return $this->success();
    }

    //参与活动
    public function participate(): JsonResponse
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'member_id' => ['required', 'integer', 'exists:users,member_id'],
                'activity_id' => ['required', 'integer'],
            ]);
            $memberId = request()->input('member_id');
            $user = UserService::findOne(['member_id' => $memberId]);
            if (empty($user->phone)) throw new Exception('请先绑定手机号', HttpStatus::NOT_BIND_PHONE);


            $activityId = request()->input('activity_id');
            if (ActivityUser::where('member_id', $memberId)->where('activity_id', $activityId)->exists()) {
                throw new Exception('已参与过此活动，每个活动仅可参加一次', HttpStatus::CUSTOM_ERROR);
            }

            if (ActivityUser::where('member_id', $memberId)->whereIn('status', [ActivityUser::STATUS_APPLY, ActivityUser::STATUS_IN_PROGRESS])->exists()) {
                throw new Exception('您有正在进行的活动，不可同时参与多个活动', HttpStatus::CUSTOM_ERROR);
            }



            if(
            !PaymentOrder::where('member_id', $memberId)->where('type',1)->where('status', 2)->exists() &&
                !Recharge::where('member_id', $memberId)->where('status', 1)->exists()
                    ){
                throw new Exception('请先完成充值，再申请活动', HttpStatus::CUSTOM_ERROR);
            }

            $first_amount = PaymentOrder::where('member_id', $memberId)->where('type',1)->where('status', 2)->value('amount');

            if(empty($first_amount) || $first_amount > 1000){
                throw new Exception('充值大于1000才能参加活动', HttpStatus::CUSTOM_ERROR);
            }

            $time = time();
            $activity = ActivityRewardService::findOne([
//                'start_time' => ['<=', $time],
//                'end_time' => ['>=', $time],
                'status' => ActivityRewardModel::STATUS_UP,
                'id' => $activityId
            ]);
            if (!$activity) throw new Exception('活动不存在', HttpStatus::CUSTOM_ERROR);
            if (strtotime($activity->start_time) > $time) throw new Exception("活动未开始$activity->start_time", HttpStatus::CUSTOM_ERROR);
            if (strtotime($activity->end_time) < $time) throw new Exception('活动已结束', HttpStatus::CUSTOM_ERROR);


            ActivityUserService::submit([
                'activity_id' => $activityId,
                'title' => $activity->title,
                'sub_title' => $activity->sub_title,
                'start_time' => $activity->start_time,
                'end_time' => $activity->end_time,
                'detail_image' => $activity->detail_image,
                'part_in_time' => $time,
                'member_id' => $memberId,
                'status' => 0
            ]);
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage(), [], $e->getCode());
        }
        return $this->success();
    }

    public function index(): JsonResponse
    {
        try {
            request()->validate(['member_id' => ['nullable', 'string']]);
            $memberId = request()->input('member_id');
            $time = time();
            $query = ActivityRewardModel::where(ActivityRewardService::getWhere([
//                'start_time' => ['<=', $time],
                'end_time' => ['>=', $time],
                'status' => ActivityRewardModel::STATUS_UP,
                'type' => 1,
            ]));
            if (!empty($memberId)) {
                $query->with(['activityUser' => function ($query1) use ($memberId) {
                    $query1->where('member_id', $memberId);
                }]);
            }
            $list = $query->orderByDesc('id')->get();
            $list->transform(function ($activity) use ($memberId) {
                if (!empty($memberId)) {
                    $activity->is_claimed = $activity->activityUser->isNotEmpty();
                } else {
                    $activity->is_claimed = false;
                }
                unset($activity->activityUser);
                return $activity;
            })->toArray();
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($list);
    }
}