<?php

namespace App\Listeners;

use App\Events\FinishAccount;
use App\Models\Amount;
use App\Models\Order;
use App\Models\Store;
use App\Handlers\SignHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class FinishAccountListeners
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  FinishAccount  $event
     * @return void
     */
    public function handle(FinishAccount $event)
    {
        $order_no=$event->data;
        Log::info('订单:'.$order_no.'开始分账完结');
        $order=Order::where('order_no',$order_no)->first();
        $sub_mchid = Store::withTrashed()->where('is_failure',0)->where('id',$order->store_id)->value('sub_mchid');
        $url='https://api.mch.weixin.qq.com/v3/ecommerce/profitsharing/finish-order';//地址
        $merchant_id=config('wechat.payment.default.mch_id');//商户号
        $serial_no=config('wechat.payment.default.serial_no');//不是平台证书序列号
        $handler=new SignHandler();
        $mch_private_key=$handler->getPublicKey();//读取商户api证书公钥 getPublicKey()获取方法 见下文
        $timestamp=time();//时间戳
        $nonce=$handler->nonce_str();//随机字符串
        $data=[
            'sub_mchid'     => $sub_mchid,
            'transaction_id'=> $order->wechat_pay_no,//微信支付单号
            'out_order_no'  =>'WJ'.substr($order->order_no,2),//订单号
            'description'   =>'分账完结',
        ];
        $sign=$handler->sign($url,'POST',$timestamp,$nonce,json_encode($data),$mch_private_key,$merchant_id,$serial_no);//签名
        $header=[
            'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $sign,
            'Accept:application/json',
            'User-Agent:' . $merchant_id,
            'Content-Type:application/json',
            'Wechatpay-Serial:' . $handler->getzhengshu()//获取平台证书序列号
        ];
        $result=$handler->curl($url,json_encode($data),$header);
        Log::info($result);
        $result=json_decode($result,true);
        if(isset($result['order_id']) && !empty($result['order_id'])){
            Log::info('分账完结成功');
            DB::transaction(function()use($order,$result) {
                Order::where('order_no',$order->order_no)->update(['is_finish'=>1,'finish_no'=>$result['order_id']]);
                $total_fee=round($order->pay_money*(1-0.006),2);
                //店铺信息
                $store = Store::withTrashed()->where('is_failure',0)->where('id', $order->store_id)->lockForUpdate()->first();
                $start_amount = $store->available_amount;
                $store->available_amount += $total_fee;
                $start_money = $store->pending_amount;
                $store->pending_amount -= $order->pay_money;
                $fee = round($order->pay_money - round($order->pay_money*54/10000,2),2);
                $store->account += $fee;
                $store->save();
                Amount::create([
                    'user_id' => $order->user_id,
                    'store_id' => $order->store_id,
                    'order_no' => 'WJ'.substr($order->order_no,2),
                    'transaction_id' => $order->wechat_pay_no,
                    'money' => $order->pay_money,
                    'type' => 2,  //结账
                    'status' => 1,  //成功
                    'service_fee' => $order->pay_money-$total_fee,
                    'start_money' => $start_money,//结账前冻结金额
                    'end_money' => $store->pending_amount,//结账后冻结金额
                    'start_amount' => $start_amount,//结账前可用金额
                    'end_amount' => $store->available_amount,//结账后可用金额
                    'remark' => '到账',
                    'account' => $store->account,
                    'actual_money' => $fee
                ]);
            },5);
            Log::info('订单:'.$order_no.'分账完结成功');
        }else{
            Log::info('分账完结失败');
        }
    }

}
