<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-10-2
 * Time: 下午8:27
 */

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Docter;
use App\Models\Order;
use App\Models\Payment;
use App\Models\User;
use DB;
use EasyWeChat\Factory;

class PayCallbackController extends Controller
{
    public function wechatPayNotify()
    {
        $app = Factory::payment(config('config.wechat_pay'));
        $response = $app->handlePaidNotify(function($message, $fail){
            // 使用通知里的 "交易单号" 去自己的数据库找到订单
            $payment = Payment::where('trade_sn', $message['out_trade_no'])->first();
            // 如果订单不存在 或者 订单已经支付过了
            if (empty($payment) || $payment['status'] != 1) {
                return true; // 告诉微信，我已经处理完了或者订单没找到，别再通知我了
            }
            //使用通知里的 "微信支付订单号" 去自己的数据库找是否已经存在
            if(Payment::where('online_sn', $message['transaction_id'])->exists()){
                return true; // 告诉微信，我已经处理过这单了，别再通知我了
            }

            //建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付

            // return_code 表示通信状态，不代表支付状态
            if ($message['return_code'] === 'SUCCESS') {
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    // 启动事务
                    DB::beginTransaction();
                    try {
                        //更新payment
                        Payment::where('id', $payment['id'])->update(['online_sn' => $message['transaction_id'], 'status' => 2, 'payment_time' => time()]);
                        $order = Order::select(['id', 'user_id', 'docter_id', 'product_type', 'payment_amount', 'total_amount'])->where('id', $payment['order_id'])->first();
                        $order_status = 2;
                        if (in_array($order['product_type'], [3,4,5,6])) {
                            $order_status = 3;
                        }
                        elseif ($order['product_type'] == 7) {
                            $order_status = 4;
                            //改变用户余额
                            User::changeBalance($order['user_id'], $order['total_amount'], 2, $order['id'], '充值');
                        }
                        //更新订单
                        Order::where('id', $payment['order_id'])->update([
                            'order_status' => $order_status,
                            'payment_status' => 2,
                            'payment_time' => time(),
                        ]);

                        Order::payCompletedHandle($order['id']);

                        // 提交事务
                        DB::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        DB::rollback();
                        trace(['微信支付回调错误' => $e->getMessage(), '错误数据' => $payment], 'error');
                        return $fail('内部服务失败，请稍后再通知我');
                    }
                }
                elseif ($message['result_code'] === 'FAIL') {
                    $err_code = $message['err_code'] ?? '';
                    $err_code_des = $message['err_code_des'] ?? '';
                    $remark = $err_code.':'.$err_code_des;
                    Payment::where('id', $payment['id'])->update(['remark' => $remark, 'status' => 3, 'payment_time' => time()]);
                }
            }
            else {
                trace(['微信支付回调通知数据错误，返回码return_code:' => $message['return_code'], '错误数据' => $payment], 'error');
                return $fail('通信失败，请稍后再通知我');
            }

            return true; // 返回处理完成
        });

        return $response;
    }
}
