<?php

namespace Modules\User\Models\Traits;

use Modules\Coupon\Models\Coupon;
use Modules\Payment\Models\Payment;
use Modules\User\Events\UserOrderPaid;
use Exception;
use Modules\User\Models\Order;

trait OrderActions
{
    /**
     * Notes: 设置订单支付
     *
     * @Author: 玄尘
     * @Date  : 2020/11/12 11:19
     */
    public function pay()
    {
        try {
            $this->state = self::STATE_SUCCESS;
            $this->save();
            event(new UserOrderPaid($this));
            return true;

        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

    }

    /**
     * Notes: 退款
     *
     * @Author: 玄尘
     * @Date: 2022/8/22 13:09
     */
    public function refund(): bool
    {
        try {
            $payment = $this->payment;
            if (! $payment) {
                throw new Exception("退款失败，未找到支付信息");
            }

            $refund = $payment->refunds()->create([
                'total' => $this->price,
            ]);
            //微信支付
            if ($payment->driver == Payment::DRIVER_WECHAT) {

                $order = [
                    'out_trade_no'  => $payment->trade_id,
                    'out_refund_no' => $refund->refund_no,
                    'amount'        => [
                        'refund'   => $payment->total * 100,
                        'total'    => $payment->total * 100,
                        'currency' => 'CNY',
                    ],
                ];

                $result = app('pay.wechat')->refund($order);

                if (isset($result->code) && $result->code == 'PARAM_ERROR') {
                    throw new Exception("退款失败，".$result->message);
                }

                $this->update([
                    'state' => Order::STATE_REFUND
                ]);

                $refund->update([
                    'refund_at' => now()
                ]);

                return true;
            } elseif ($payment->driver == Payment::DRIVER_ALIPAY) {//支付宝支付

                $order = [
                    'out_trade_no'  => $this->order->order_no,
                    'refund_amount' => $this->actual_total,
                ];

                $result = app('pay.alipay')->refund($order);

                if ($result->code != '10000') {
                    throw new Exception("退款失败，".$result->msg);
                }

                $this->update([
                    'state' => Order::STATE_REFUND
                ]);

                $refund->update([
                    'refund_at' => now()
                ]);

                return true;
            } else {
                throw new Exception("退款失败，未找到支付路径");
            }
        } catch (Exception $exception) {
            throw new Exception($exception->getMessage());
        }
    }
}
