<?php


namespace App\Modules\SendOrder\Services;


use App\Modules\Order\Services\OrderService;
use App\Modules\SendOrder\Models\SendOrder;
use App\Modules\SendOrder\Models\SendOrderRechargeDayStat;

class SendOrderChargeStatService
{
    /**
     * 根据日期获取订单信息
     * @param string $date
     * @return bool
     */
    public static function getOrdersByDate(string $date): bool
    {
        myLog('getOrdersByDate')->info('[start] ' . date('Y-m-d H:i:s'));

        // 计算时间
        $timestamp = strtotime($date);
        [$startTime, $endTime] = [date('Y-m-d', $timestamp), date('Y-m-d 23:59:59', $timestamp)];
        myLog('getOrdersByDate')->info('1', compact('startTime', 'endTime'));

        // 获取订单信息
        $instance = new OrderService();
        $orders   = $instance->getSendOrdersByDate($startTime, $endTime);
        myLog('getOrdersByDate')->info('2', ['orders_num' => count($orders)]);
        if (empty($orders)) {
            return false;
        }

        // 获取所有派单
        $sendOrderIds = array_unique(array_values(array_column($orders, 'send_order_id')));
        $sendOrders   = SendOrder::getSendOrdersByIds($sendOrderIds);
        myLog('getOrdersByDate')->info('2', ['sendOrderIds' => count($sendOrderIds)]);

        // 组装数据
        $insertDataList = self::buildRechargeStats($date, $sendOrderIds, $sendOrders, $orders);
        $insertDataArr  = array_chunk($insertDataList, 500);
        foreach ($insertDataArr as $insertData) {
            SendOrderRechargeDayStat::insertData($insertData);
        }

        myLog('getOrdersByDate')->info('[end] ' . date('Y-m-d H:i:s'));
        return true;
    }

    /**
     * @param $date
     * @param $sendOrderIds
     * @param $sendOrders
     * @param $orders
     * @return array
     */
    private static function buildRechargeStats($date, $sendOrderIds, $sendOrders, $orders): array
    {
        // 重组派单信息
        $sendOrdersArr = array_column($sendOrders, NULL, 'id');

        // 初始化
        $sendOrderStats   = [];
        $paidOrderUidList = [];
        foreach ($sendOrderIds as $sendOrderId) {
            $sendOrder = getProp($sendOrdersArr, $sendOrderId);
            if (!$sendOrder) {
                continue;
            }

            $paidOrderUidList[$sendOrderId] = [];
            $sendOrderStats[$sendOrderId]   = [
                'send_order_id'           => $sendOrderId,
                'distribution_channel_id' => getProp($sendOrder, 'distribution_channel_id'),
                'book_name'               => getProp($sendOrder, 'book_name'),
                'bid'                     => getProp($sendOrder, 'book_id'),
                'recharge_amount'         => 0.00,
                'order_num'               => 0,
                'paid_order_num'          => 0,
                'unpaid_order_num'        => 0,
                'paid_user_num'           => 0,
                'date'                    => $date,
                'created_at'              => date('Y-m-d H:i:s'),
                'updated_at'              => date('Y-m-d H:i:s'),
            ];
        }

        // 循环订单信息
        foreach ($orders as $order) {
            $sendOrderId = getProp($order, 'send_order_id');
            $orderStatus = getProp($order, 'status');
            if (getProp($sendOrderStats, $sendOrderId)) {
                // 订单总数
                $sendOrderStats[$sendOrderId]['order_num'] += 1;

                // 区分支付订单和未支付订单
                if ($orderStatus === 'PAID') {
                    // 支付总额、支付订单数、支付用户集合
                    $sendOrderStats[$sendOrderId]['recharge_amount'] += (float)getProp($order, 'price');
                    $sendOrderStats[$sendOrderId]['paid_order_num']  += 1;
                    $paidOrderUidList[$sendOrderId][]                = getProp($order, 'uid');
                } else {
                    // 未支付数
                    $sendOrderStats[$sendOrderId]['unpaid_order_num'] += 1;
                }
            }
        }

        // 重新循环stats
        $result = [];
        foreach ($sendOrderStats as $sendOrderId => $sendOrderStat) {
            // 过滤掉没有支付的派单
            if ((int)getProp($sendOrderStat, 'paid_order_num') < 1) {
                continue;
            }

            $item        = $sendOrderStat;
            $paidUidList = getProp($paidOrderUidList, $sendOrderId);
            if ($paidUidList) {
                $paidUserNum           = count(array_unique($paidUidList));
                $item['paid_user_num'] = $paidUserNum;
            }

            $result[] = $item;
        }

        return $result;
    }

    /**
     * @param $date
     * @return bool
     */
    public static function deleteSendOrderStatsByDate($date)
    {
        myLog('getOrdersByDate')->info('[delete] 删除已存在数据');
        return SendOrderRechargeDayStat::deleteData(['date' => $date]);
    }
}