<?php

namespace app\admin\controller\finance;

use app\admin\service\member\MemberService;
use app\model\Member;
use app\model\Order;
use support\Db;
use support\Request;

class RechargeController
{

    public function list(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);
        $memberId = $request->get('join_order_member_id', '');
        $days = $request->get('order_addtimes', []);
        $premisesId = intval($request->get('premises_id', ''));
        if (!empty($days)) {
            $days[0] = strtotime($days[0]);
            $days[1] = strtotime($days[1]);
        }

        $rows = Order::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
        ])->where('order_classify','RECHARGE')
            ->when(!empty($days), function ($query) use ($days) {
            $query->whereBetween('order_addtimes', $days);
        })->when(!empty($memberId), function ($query) use ($memberId) {
            $query->where('join_order_member_id', $memberId);
        });

        $total = $rows->count();
        $memberIds = $rows->pluck('join_order_member_id')->toArray();
        dump(count(array_unique($memberIds)));
        $statistics['member_count'] = count(array_unique($memberIds));
        $statistics['amount'] = $rows->sum('order_amount_pay');

        $rows = $rows->orderBy('order_addtimes', 'DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();

        foreach ($rows as &$row){
            $mobile = $row['member'] && $row['member']['member_mobile'] ? $row['member']['member_mobile'] : '';
            $certName = $row['cert'] && $row['cert']['member_cert_name'] ? $row['cert']['member_cert_name'] : '';
            $row['member_name'] = MemberService::getMemberCertName($mobile,$certName,'');
        }

        return json_success('', compact('rows', 'page', 'pageSize', 'total', 'statistics'));
    }
}