<?php
/**
 * Created by ${PRODUCT_NAME}
 * User: JianJia.Zhou
 * DateTime: 2021/8/16 23:14
 * @description
 */

namespace App\Http\Controllers\Api;

use App\Models\ShareConfig;
use App\Models\User;
use App\Models\UserShare;
use App\Models\UserVip;
use Carbon\Carbon;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;

class PaymentController extends Controller
{
    public function notice()
    {
        $app = Factory::payment(config('wechat.payment.default'));
        $response = $app->handlePaidNotify(function ($message, $fail) {
            trace(json_encode($message,JSON_UNESCAPED_UNICODE),'debug');
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = UserVip::where('order_id', $message['out_trade_no'])->first();

            if (!$order) { // 如果订单不存在
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $order->pay_at = Carbon::now()->toDateTimeString(); // 更新支付时间为当前时间
                    $order->status = 1;
                    $order->serial_number = $message['transaction_id'];
                }elseif ($message['result_code'] === 'FAIL') {
                    $order->status = 2;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            if($order->status == 1){
                $user = User::find($order->user_id);
                $user->is_vip = 1;
                $user->become_vip_at = Carbon::now()->toDateTimeString();
                $user->save();
                // 一级分销
                $this->shareIncome($user);
            }

            $order->save();
            return true;
        });
        return $response;

    }


    /**
     * @create       JianJia.Zhou<z656123456@gmail.com>
     * @param User $user
     * @return bool
     */
    private function shareIncome($user)
    {
        if($user->parent_id){
            $shareConfig = ShareConfig::orderBy('id','asc')->first()->toArray();
            if(empty($shareConfig['is_open'])){
                return true;
            }

            UserShare::create([
                'user_id' => $user->parent_id,
                'child_id' => $user->id,
                'income' => $shareConfig['price'],
            ]);

            $parent = User::find($user->parent_id);
            $parent->overage = $parent->overage + $shareConfig['price'];
            $parent->income = $parent->income + $shareConfig['price'];
            $parent->save();
        }
    }
}
