<?php

namespace App\Jobs;

use App\Events\CommissionUnfreezeComplete;
use App\Models\OrderCommission;
use App\Models\PartnerCommission;
use App\Models\PartnerWallet;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UnfreezeCommission implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected OrderCommission $commission;
    protected PartnerCommission $partner_commission;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(OrderCommission $commission)
    {
        $this->commission = $commission;
        $this->partner_commission = $commission->partner_commission;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $partner_commission = $this->partner_commission;

        // 判断佣金是否已经解冻或未到时间
        if ($partner_commission->status != 0 || $partner_commission->unfreeze_time > now()) {
            Log::info('order_commission'.$this->commission->id."的状态为".$partner_commission->status.",解冻时间为".$partner_commission->unfreeze_time.",当前时间为".date('Y-m-d H:i:s'));
            return;
        }

        try {
            DB::beginTransaction();
            Log::info('order_commission'.$this->commission->id.'佣金解冻start');
            // 更新佣金状态为已解冻
            $partner_commission->status = 1;
            $partner_commission->save();
            Log::info('order_commission'.$this->commission->id.'更新佣金状态为已解冻');

            // 更新合伙人钱包余额
            $wallet = PartnerWallet::where('user_id', $partner_commission->user_id)->first();
            $wallet->balance = bcadd($wallet->balance,$partner_commission->amount,2);
            $wallet->frozen_amount = bcsub($wallet->frozen_amount,$partner_commission->amount,2);
            $wallet->save();
            Log::info('order_commission'.$this->commission->id.'更新合伙人钱包余额');

            DB::commit();
            Log::info('order_commission'.$this->commission->id.'佣金解冻完成');
            CommissionUnfreezeComplete::dispatch($this->commission);
        }catch (\Exception){
            DB::rollBack();
            Log::info('order_commission'.$this->commission->id.'佣金解冻失败');
        }
    }
}
