<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\SportGameOrder as SportGameOrderModel;
use App\Models\FundsRecord;
use App\Models\Wallet;
use Exception;
use App\Constants\HttpStatus;
use Illuminate\Support\Facades\DB;

class SportGameOrder extends Controller
{

    /**
     * 订单列表
     */
    public function list()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'ordernum' => ['nullable', 'string'],
                'member_id' => ['nullable', 'integer'],
                'first_name' => ['nullable'],
                'game_name' => ['nullable', 'string'],
                'gameplay_name' => ['nullable', 'string'],
                'status' => ['nullable', 'integer'],
                'id' => ['nullable', 'integer'],
                'start_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:end_time'],
                'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'required_with:start_time'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);

            $query = new SportGameOrderModel();
            
            $query = SportGameOrderModel::join('users', 'users.member_id', '=', 'sport_game_order.member_id')
                        ->join('sport_game', 'sport_game.id', '=', 'sport_game_order.game_id')
                        ->join('sport_gameplay', 'sport_gameplay.id', '=', 'sport_game_order.gameplay_id');
            if (!empty($params['id'])) {
                $query = $query->where('sport_game_order.id', $params['id']);
            }
            if (!empty($params['ordernum'])) {
                $query = $query->where('sport_game_order.ordernum', $params['ordernum']);
            }
            if (!empty($params['member_id'])) {
                $query = $query->where('sport_game_order.member_id', $params['member_id']);
            }
            if (isset($params['status']) && $params['status'] !== null) {
                $query = $query->where('sport_game_order.status', $params['status']);
            }
            if (!empty($params['game_name'])) {
                $query = $query->where('sport_game.name', 'like', '%'.$params['game_name'].'%');
            }
            if (!empty($params['gameplay_name'])) {
                $query = $query->where('sport_gameplay.name', 'like', '%'.$params['gameplay_name'].'%');
            }
            if (!empty($params['first_name'])) {
                $query = $query->where('users.first_name', 'like', "%{$params['first_name']}%");
            }
            if (!empty($params['start_time'])) {
                $startTime = $params['start_time'] . " 00:00:00";
                $query = $query->where('sport_game_order.created_at', '>=', $startTime);
            }
            if (!empty($params['end_time'])) {
                $endTime = $params['end_time'] . " 23:59:59";
                $query = $query->where('sport_game_order.created_at', '<=', $endTime);
            }
            $count = $query->count();
            $list = $query->select('sport_game_order.*','users.first_name','users.member_id', 'sport_game.name as game_name', 'sport_gameplay.name as gameplay_name')
                ->forPage($page, $limit)
                ->orderByDesc('sport_game_order.created_at')
                ->get();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list]);

    }

    //订单详情
    function info()
    {
        try {
            request()->validate([
                'id' => ['required', 'integer'],
            ]);
            $id = request()->input('id');
            $order = SportGameOrderModel::join('users', 'users.member_id', '=', 'sport_game_order.member_id')
                        ->join('sport_game', 'sport_game.id', '=', 'sport_game_order.game_id')
                        ->join('sport_gameplay', 'sport_gameplay.id', '=', 'sport_game_order.gameplay_id')
                        ->where('sport_game_order.id', $id)
                        ->select('sport_game_order.*','users.first_name','users.member_id', 'sport_game.name as game_name', 'sport_gameplay.name as gameplay_name')
                        ->first();
            if (!$order) throw new Exception('订单不存在');
            $order = $order->toArray();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success($order);
    }

    /**
     * @api {post} /sportGameOrder/refund 同意退款
     * @apiGroup 订单管理
     */
    public function refund()
    {
        $errors = [];
        try {
            DB::beginTransaction();
            $params = request()->validate([
                'id' => ['required', 'array', 'min:1'],
                'remark' => ['nullable', 'string'],
            ]);
            $orderList = SportGameOrderModel::whereIn('id', $params['id'])->get();
            foreach ($orderList as $order) {
                if ($order->status != 0) {
                    continue;
                }
                
                $order->status = 3;
                $order->updated_at = time();
                $order->save();

                // 获取用户余额
                $walletInfo = Wallet::where(['member_id' => $order->member_id])->first();
                if (!$walletInfo) continue;
                
                $before = $walletInfo->available_balance;
                $after = bcsub($walletInfo->available_balance, $order->amount, 2);
                $walletInfo->available_balance = $after;
                $walletInfo->save();

                FundsRecord::addData([
                    'change_type' => '足球游戏退款',
                    'amount' => $order->amount,
                    'before_balance' => $before,
                    'after_balance' => $after,
                    'member_id' => $order->member_id,
                    'related_id' => $order->id,
                    'remark' => '足球游戏订单退款',
                ]);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage(), $errors);
        }
        return $this->success();

    }

}