<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Exception;
use App\Models\User;
use App\Models\FundsRecord;
use App\Models\Order;
use App\Models\Operation as OperationModel;
use App\Constants\HttpStatus;

class Operation extends Controller
{
    /**
     * 用户报表
     */
    function exchangeList()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
                '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'],
                'user_id' => ['nullable', 'string'],
                'member_id' => ['nullable'],
                'first_name' => ['nullable'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);
            $query = User::where('users.from','<>', 2);
            if (isset($params['user_id'])) {
                $user_id = $params['user_id'] ?? null;
                $query->where(function ($query1) use ($user_id) {
                    $query1->where('users.member_id', $user_id)
                    ->orWhere('users.first_name', 'like', "%{$user_id}%");
                });
            }
            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']}%");
            }

            $count = $query->count();
            $list = $query->join('wallets', 'users.member_id', '=', 'wallets.member_id')
                ->select(['users.id', 'users.user_id','users.member_id', 'users.first_name', 'wallets.available_balance as money'])
                ->forPage($page, $limit)
                ->orderByDesc("users.created_at")
                ->get()->toArray();
            
            $start = !empty($params['start_time']) ? "{$params['start_time']} 00:00:00" : null;
            $end = !empty($params['end_time']) ? "{$params['end_time']} 23:59:59" : null;

            foreach ($list as &$item) {
                $item['recharge'] = number_format(FundsRecord::where('member_id', $item['member_id'])
                    ->whereIn('change_type', ['充值','人工充值','三方充值'])
                    ->where(function ($query1) use ($start, $end) {
                        if ($start && $end) {
                            $query1->where('created_at', '>=', $start)
                                ->where('created_at', '<=', $end);
                        }
                    })
                    ->sum('amount'), 2);

                $item['withdraw'] = number_format(FundsRecord::where('member_id', $item['member_id'])
                    ->whereIn('change_type', ['提现','三方提现'])
                    ->where(function ($query1) use ($start, $end) {
                        if ($start && $end) {
                            $query1->where('created_at', '>=', $start)
                                ->where('created_at', '<=', $end);
                        }
                    })
                    ->sum('amount'), 2);
                //订单总额
                $item['order_amount'] = number_format(Order::where('user_id', $item['user_id'])
                    ->where('status', 1)
                    ->where('pay_status', 1)
                    ->where('return_status', 0)
                    ->where(function ($query1) use ($start, $end) {
                        if ($start && $end) {
                            $start = strtotime($start.' 00:00:00');
                            $end = strtotime($end.' 23:59:59');
                            $query1->where('create_time', '>=', $start)
                                ->where('create_time', '<=', $end);
                        }
                    })
                    ->sum('amount'), 2);
            }
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list]);

    }

    /**
     * 运营数据
     * @apiParam {String{'day','week','month','all'}} type 类型
     * - day 今日
     * - week 本周
     * - month 本月
     * - all 全部
     */
    function index()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
                'type' => ['required', 'string', 'in:day,week,month,all'],
                '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'],
            ]);
            $data = [
                'recharge' => 0,
                'withdraw' => 0,
                'total_price' => 0,
                'profit_price' => 0
            ];
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);
            $query = OperationModel::query();
            $query1 = OperationModel::query();
            if (!empty($params['start_time'])) {
                $query->where('date', '>=', $params['start_time'])
                    ->where('date', '<=', $params['end_time']);
                $query1->where('date', '>=', $params['start_time'])
                    ->where('date', '<=', $params['end_time']);
            } else if ($params['type'] != 'all') {
                switch ($params['type']) {
                    case 'day':
                        $date = date('Y-m-d');
                        break;
                    case "week":
                        $date = date('Y-m-d', strtotime('this week'));
                        break;
                    case "month":
                        $date = date('Y-m-d', strtotime('this month'));
                        break;
                }
                $query->where('date', '>=', $date);
                $query1->where('date', '>=', $date);
            }
            $data['recharge'] = $query1->sum('recharge');
            $data['withdraw'] = $query1->sum('withdraw');
            $data['total_price'] = $query1->sum('total_price');
            $count = $query->count();
            $list = $query
                ->forPage($page, $limit)
                ->orderByDesc('date')
                ->get()->toArray();


        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list, 'count' => $data]);
    }
}