<?php

namespace App\Listeners;

use App\Events\CommissionGotEvent;
use App\Events\OrderServeFinishedEvent;
use App\Events\OrderServeStartedEvent;
use App\Models\PartnerCommission;
use DB;
use Illuminate\Support\Facades\Log;

/*发佣金给服务人员*/
class SendCommissionToServeUserListener
{
    public function __construct()
    {
    }

    public function handle(OrderServeStartedEvent|OrderServeFinishedEvent $event): void
    {
        // 获取订单佣金信息
        $order_commissions = $event->offlineOrder->order_commission()
            ->with(['partner_commission', 'main_order'])
            ->where('status', 0)
            ->where('send_event', $event->send_event)
            ->get();
        DB::transaction(function () use ($order_commissions) {
            $order_commissions->reject(function ($order_commission) {
                return $order_commission->partner_commission;
            })->each(function ($order_commission) {
                //变更订单佣金状态
                $order_commission->update(['status' => 1]);
                Log::info('order_commission'.$order_commission->id.'佣金状态更改完成');
                //不存在钱包则创建
                if (!$order_commission->partner_wallet){
                    $wallet = [
                        'user_id'=>$order_commission->user_id,
                        'balance' => 0,
                        'frozen_amount' => 0,
                        'withdrawn_amount' => 0,
                    ];
                    $order_commission->partner_wallet()->create($wallet);
                    Log::info('order_commission'.$order_commission->id.'钱包创建完成');
                }

                //钱包入账冻结金额
                $order_commission->partner_wallet()->increment('frozen_amount', $order_commission->commission_amount);
                Log::info('order_commission'.$order_commission->id.'钱包入账冻结金额'.$order_commission->commission_amount);

                //生成合伙人佣金记录
                $partner_commission = new PartnerCommission([
                    'order_id' => $order_commission->order_id,
                    'order_no' => $order_commission->main_order->trade_no,
                    'order_commission_id' => $order_commission->id,
                    'user_id' => $order_commission->user_id,
                    'role' => $order_commission->role,
                    'amount' => $order_commission->commission_amount,
                    'status' => 0,
                    'unfreeze_time' => now()->addDays($order_commission->delay),
                ]);

                $order_commission->partner_commission = $partner_commission;
                $order_commission->partner_commission->save();
                Log::info('order_commission'.$order_commission->id.'生成合伙人佣金记录完成');
                //触发佣金发放事件
                CommissionGotEvent::dispatch($order_commission);
                Log::info('order_commission'.$order_commission->id.'触发佣金发放事件end');
            });
        });
    }
}
