<?php


namespace App\Http\Controllers\admin;


use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Models\BalanceLog;
use App\Services\BalanceLogService;
use Carbon\Carbon;
use Illuminate\Validation\ValidationException;
use Exception;

class Balance extends Controller
{
    public function log()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'type' => ['nullable', 'integer'],
                'member_id' => ['nullable', 'string', 'min:1'],
                'related_id' => ['nullable', 'string', 'min:1'],
                'change_type' => ['nullable', 'string', 'in:' . implode(',', BalanceLogService::$RW)],
                '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'],
                'first_name' => ['nullable'],
                'is_fancai' => ['nullable', 'integer','in:0,1'],
                // 用户类型/注册来源：-1 tg用户，0 后台客服账号，1 真实用户，2 虚拟用户
                'from' => ['nullable'],
            ]);
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 10);
            $query = BalanceLog::join('users', 'users.member_id', '=', 'balance_logs.member_id')
                        ->where(BalanceLogService::getWhere($params));
            if (!empty($params['is_fancai'])) {
                $data['change_types'] = ['即充即送','老用户回归','余额宝利息'];
                $query = $query->whereIn('balance_logs.change_type', $data['change_types'])
                    ->where('balance_logs.type', 2);
            } else {
                $data['change_types'] = BalanceLogService::$RW;
            }
            // 统计与列表共用筛选条件；clone 避免 count/sum 影响后续分页查询
            $data['total'] = (clone $query)->count();
            $data['total_amount'] = bcadd((clone $query)->sum('balance_logs.amount'), 0, 2);
            $data['data'] = $query->select("balance_logs.*", "users.first_name", "users.admin_note as user_admin_note", "users.from as user_from")
                ->orderByDesc('balance_logs.id')
                ->forPage($page, $limit)
                ->with(['member'])
                ->get()
                ->toArray();
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode(),$e->getMessage());
        }
        return $this->success($data);
    }
}