<?php


namespace App\Console\Commands\Activity;


use App\Cache\Activity\ActivityCache;
use App\Modules\Activity\Services\ActivityService;
use App\Modules\Trade\Services\OrderService;
use App\Modules\Activity\Models\ActivityStats as ActivityStatsModel;
use Illuminate\Console\Command;

class ActivityStats extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'activity:stats';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计快应用活动相关数据';

    /**
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        // 获取所有有效快应用
        $activities = ActivityService::getValidActivities();
        if (empty($activities)) {
            return false;
        }

        // 获取活动统计
        $activityIds   = array_column($activities, 'id');
        $activityStats = ActivityStatsModel::getActivityStatsByActivityIds($activityIds);

        $yesterday = date('Y-m-d');
        foreach ($activities as $activity) {
            [$activityId, $channelId] = [getProp($activity, 'id'), getProp($activity, 'distribution_channel_id')];
            [$startAt, $endAt] = [getProp($activity, 'start_time'), getProp($activity, 'end_time')];

            // 获取订单相关数据
            $orders = OrderService::getOrdersByActivityId($channelId, $startAt, $activityId);
            if (empty($orders)) {
                continue;
            }

            // 订单总数、订单成功数、订单总金额
            $orderNum        = 0;
            $successOrderNum = 0;
            $rechargeAmount  = 0;
            $paidUids        = [];
            foreach ($orders as $order) {
                $uid = (int)getProp($order, 'uid');
                $orderNum++;
                if (getProp($order, 'status') === 'PAID') {
                    $successOrderNum++;
                    $rechargeAmount += getProp($order, 'price');
                    if (!in_array($uid, $paidUids, true)) {
                        $paidUids[] = $uid;
                    }
                }
            }

            // 获取昨日uv、pv
            $uv = ActivityCache::getActivityUv($activityId, $yesterday);
            $pv = ActivityCache::getActivityPv($activityId, $yesterday);

            // 更新统计数据
            $activityStat = collect($activityStats)->firstWhere('activity_id', $activityId);
            if ($activityStat) {
                ActivityStatsModel::updateData(['activity_id' => $activityId], [
                    'success_order_num' => $successOrderNum,
                    'recharge_amount'   => $rechargeAmount,
                    'order_num'         => $orderNum,
                    'paid_user_num'     => count($paidUids),
                    'uv'                => $uv + (int)getProp($activityStat, 'uv'),
                    'pv'                => $pv + (int)getProp($activityStat, 'pv'),
                    'updated_at'        => date('Y-m-d H:i:s'),
                ]);
            } else {
                ActivityStatsModel::insertData([
                    'activity_id'       => $activityId,
                    'channel_id'        => $channelId,
                    'success_order_num' => $successOrderNum,
                    'recharge_amount'   => $rechargeAmount,
                    'order_num'         => $orderNum,
                    'paid_user_num'     => count($paidUids),
                    'uv'                => $uv,
                    'pv'                => $pv,
                    'created_at'        => date('Y-m-d H:i:s'),
                    'updated_at'        => date('Y-m-d H:i:s'),
                ]);
            }
        }
    }

}