<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\FundsRecord;
use App\Models\User;
use App\Models\Order as OrderModel;
use App\Models\Sport;
use Exception;
use Illuminate\Support\Facades\DB;
use App\Constants\HttpStatus;
use App\Models\Wallet;
use App\Models\SportStatistics;

/**
 * 足球订单
 */
class Order extends Controller
{
    /**
     * 订单手动退款
     */
    public function refund()
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'id' => ['required', 'array', 'min:1'],
            ]);
            $orderList = OrderModel::whereIn('id', $params['id'])->get();
            foreach ($orderList as $order) {
                if ($order->return_status != 0 || $order->pay_status != 1 || $order->settlement_status != 0) {
                    continue;
                }
                
                $order->status = 2;
                $order->return_status = 2;
                $order->return_operation_time = time();
                $order->save();
                // 获取用户余额
                $walletInfo = Wallet::where(['member_id' => $order->user_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->user_id,
                    'related_id' => $order->id,
                    'remark' => '体彩订单退款',
                ]);
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success();
    }

    /**
     * 订单列表
     */
    public function list()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'id' => ['nullable', 'string'],
                'user_id' => ['nullable', 'string'],
                'member_id' => ['nullable'],
                'first_name' => ['nullable'],
                'user_id' => ['nullable', 'string'],
                'id' => ['nullable'],
                'order_id' => ['nullable', 'string'],
                'issue' => ['nullable', 'integer'],
                'pay_status' => ['nullable', 'integer', 'in:0,1'],
                'is_win' => ['nullable', 'integer', 'in:0,1'],
                'is_roll' => ['nullable', 'integer', 'in:0,1'],
                'settlement_status' => ['nullable', 'integer', 'in:0,1,2,3'],
                'return_status' => ['nullable', 'integer', 'in:0,1,2,3'],
                'status' => ['nullable', 'integer', 'in:0,1,2,-1'],
                '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', 'after_or_equal:start_time'],
                'league' => ['nullable'],
                'home_team' => ['nullable'],
                'guest_team' => ['nullable'],
                // 注册来源：users.from（-1 tg / 0 后台客服 / 1 真实用户 / 2 虚拟用户）
                'from' => ['nullable', 'integer', 'in:-1,0,1,2'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);

            $query = OrderModel::join('sport_odds', 'sport_odds.odd_name_en', '=', 'sport_order.odd_name')
                        ->join('sport', 'sport.data_id', '=', 'sport_order.issue')
                        ->join('users', 'users.user_id', '=', 'sport_order.user_id');
            if (!empty($params['id'])) {
                $query = $query->where('sport_order.id', $params['id']);
            }
            if (!empty($params['start_time'])) {
                $startTime = strtotime($params['start_time'] . " 00:00:00");
                $query = $query->where('sport_order.create_time', '>=', $startTime);
            }
            if (!empty($params['end_time'])) {
                $endTime = strtotime($params['end_time'] . " 23:59:59");
                $query = $query->where('sport_order.create_time', '<=', $endTime);
            }
            if (!empty($params['issue'])) {
                $query = $query->where('sport_order.issue', $params['issue']);
            }
            if (!empty($params['order_id'])) {
                $query = $query->where('order_id', $params['order_id']);
            }
            if (!empty($params['user_id'])) {
                $query = $query->where('sport_order.user_id', $params['user_id']);
            }
            if (isset($params['status'])) {
                $query = $query->where('sport_order.status', $params['status']);
            }
            if (isset($params['return_status'])) {
                $query = $query->where('sport_order.return_status', $params['return_status']);
            }
            if (isset($params['pay_status'])) {
                $query = $query->where('sport_order.pay_status', $params['pay_status']);
            }
            if (isset($params['is_win'])) {
                $query = $query->where('sport_order.is_win', $params['is_win']);
            }
            if (isset($params['settlement_status'])) {
                $query = $query->where('sport_order.settlement_status', $params['settlement_status']);
            }
            if (isset($params['is_roll'])) {
                $query = $query->where('sport_order.is_roll', $params['is_roll']);
            }
            if (!empty($params['league'])) {
                $query = $query->where('league|league_en', 'like', '%' . $params['league'] . '%');
            }
            if (!empty($params['home_team'])) {
                $query = $query->where('home_team|home_team_en', 'like', '%' . $params['home_team'] . '%');
            }
            if (!empty($params['guest_team'])) {
                $query = $query->where('guest_team|guest_team_en', 'like', '%' . $params['guest_team'] . '%');
            }
            if (!empty($params['member_id'])) {
                $query = $query->where('users.member_id', $params['member_id']);
            }
            if (!empty($params['first_name'])) {
                $query = $query->where('users.first_name', 'like', "%{$params['first_name']}%");
            }
            // from=0 合法，不能用 empty()
            if (array_key_exists('from', $params) && $params['from'] !== null && $params['from'] !== '') {
                $query = $query->where('users.from', (int)$params['from']);
            }
            
            $count = $query->distinct()->count('sport_order.id');
            $list = $query->distinct()
                ->select(['sport_order.*','sport_odds.odd_name as odd_name', 'sport.league', 'sport.league_en', 'sport.home_team', 'sport.home_team_en','sport.home_team_logo', 'sport.guest_team', 'sport.guest_team_en','sport.guest_team_logo',
                    'users.member_id','users.first_name','users.from as user_from'
                ])
                ->forPage($page, $limit)
                ->orderByDesc('sport_order.create_time')
                ->get();
            foreach($list as &$item) {
                $item['odd_name'] = Sport::doOddName($item['odd_name']);
                $item['odd_value'] = Sport::doOddValue($item['odd_value']);
                $item['odd'] = formatDecimal($item['odd'], 2);
            }
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list]);

    }

    //订单详情
    function info()
    {
        try {
            request()->validate([
                'order_id' => ['required', 'string'],
            ]);
            $order_id = request()->input('order_id');
            $order = OrderModel::join('sport_odds', 'sport_odds.odd_name_en', '=', 'sport_order.odd_name')
                        ->join('sport', 'sport.data_id', '=', 'sport_order.issue')
                        ->where('sport_order.order_id', $order_id)
                        ->select(['sport_order.*','sport_odds.odd_name as odd_name', 'sport.league', 'sport.league_en', 'sport.home_team', 'sport.home_team_en','sport.home_team_logo', 'sport.guest_team', 'sport.guest_team_en','sport.guest_team_logo'])
                        ->first();
            if (!$order) throw new Exception('订单不存在');
            $order = $order->toArray();
            $order['game_result']  = $order['game_result'] ? json_decode($order['game_result'],true) : null;
            $order['first_name'] = User::where('user_id', $order['user_id'])->value('first_name');
            $order['odd_name'] = Sport::doOddName($order['odd_name']);
            $order['odd_value'] = Sport::doOddValue($order['odd_value']);
            $order['odd'] = formatDecimal($order['odd'], 2);
            
            if (!empty($order['detail']['fixture_status'])) {
                $order['detail']['fixture_status'] = Sport::getFixtureStatus($order['detail']['fixture_status']);
            } 
            
            //赛事统计数据
            $order['statistics'] = SportStatistics::where('data_id', $order['issue'])->get()->toArray();
            ksort($order);
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR,$e->getMessage());
        }
        return $this->success($order);
    }

}