<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\JisuGameOrder as JisuGameOrderModel;
use App\Models\FundsRecord;
use App\Models\JisuGameplay;
use App\Models\Wallet;
use Exception;
use App\Constants\HttpStatus;
use Illuminate\Support\Facades\DB;

class JisuGameOrder 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'],
                'gameplay' => ['nullable', 'string'],
                'status' => ['nullable', 'integer'],
                'id' => ['nullable', 'integer'],
                'type' => ['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 JisuGameOrderModel();
            
            $query = JisuGameOrderModel::join('users', 'users.member_id', '=', 'jisu_game_order.member_id')
                        ->join('jisu_gameplay', 'jisu_gameplay.id', '=', 'jisu_game_order.gameplay_id')
                        ->leftJoin('jisu_lottery', function($join) {
                            $join->on('jisu_game_order.type', '=', 'jisu_lottery.type')
                                 ->on('jisu_game_order.issue', '=', 'jisu_lottery.issue');
                        });
            if (!empty($params['id'])) {
                $query = $query->where('jisu_game_order.id', $params['id']);
            }
            if (!empty($params['type'])) {
                $query = $query->where('jisu_game_order.type', $params['type']);
            }
            if (!empty($params['ordernum'])) {
                $query = $query->where('jisu_game_order.ordernum', $params['ordernum']);
            }
            if (!empty($params['member_id'])) {
                $query = $query->where('jisu_game_order.member_id', $params['member_id']);
            }
            if (isset($params['status']) && $params['status'] !== null) {
                $query = $query->where('jisu_game_order.status', $params['status']);
            }
            if (!empty($params['gameplay'])) {
                $query = $query->where('jisu_gameplay.gameplay', 'like', '%'.$params['gameplay'].'%');
            }
            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('jisu_game_order.created_at', '>=', $startTime);
            }
            if (!empty($params['end_time'])) {
                $endTime = $params['end_time'] . " 23:59:59";
                $query = $query->where('jisu_game_order.created_at', '<=', $endTime);
            }
            $count = $query->count();
            $list = $query->select('jisu_game_order.*','users.first_name','users.member_id', 'jisu_gameplay.gameplay','jisu_gameplay.number','jisu_lottery.open_code','jisu_lottery.open_code_other')
                ->forPage($page, $limit)
                ->orderByDesc('jisu_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 = JisuGameOrderModel::join('users', 'users.member_id', '=', 'jisu_game_order.member_id')
                        ->join('jisu_gameplay', 'jisu_gameplay.id', '=', 'jisu_game_order.gameplay_id')
                        ->leftJoin('jisu_lottery', function($join) {
                            $join->on('jisu_game_order.type', '=', 'jisu_lottery.type')
                                 ->on('jisu_game_order.issue', '=', 'jisu_lottery.issue');
                        })
                        ->where('jisu_game_order.id', $id)
                        ->select('jisu_game_order.*','users.first_name','users.member_id', 'jisu_gameplay.gameplay','jisu_lottery.open_code','jisu_lottery.open_code_other')
                        ->first();
            if (!$order) throw new Exception('订单不存在');
            $order = $order->toArray();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success($order);
    }

    /**
     * 同意退款
     */
    public function refund()
    {
        $errors = [];
        try {
            DB::beginTransaction();
            $params = request()->validate([
                'id' => ['required', 'array', 'min:1'],
                'remark' => ['nullable', 'string'],
            ]);
            $orderList = JisuGameOrderModel::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();

                $before = $walletInfo->available_balance;
                $after = bcsub($walletInfo->available_balance, $order->amount, 2);
                $walletInfo->available_balance = $after;
                $walletInfo->save();
                $remark = JisuGameplay::getRemark($order->type);
                
                FundsRecord::addData([
                    'change_type' => $remark.'退款',
                    'amount' => $order->amount,
                    'before_balance' => $before,
                    'after_balance' => $after,
                    'member_id' => $order->member_id,
                    'related_id' => $order->id,
                    'remark' => $remark.'退款',
                ]);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage(), $errors);
        }
        return $this->success();

    }

}