<?php


namespace app\common\logic;


use app\common\enum\PayEnum;
use app\common\model\user\UserAuth;
use app\common\service\pay\PayService;
use Exception;
use support\exception\BusinessException;
use support\Log;
use Throwable;

use function DI\string;

/**
 * 支付逻辑
 * Class PaymentLogic
 * @package app\common\logic
 */
class PaymentLogic extends BaseLogic
{

    /**
     * @notes 支付
     * @param $payWay
     * @param $from
     * @param $order
     * @param $terminal
     * @param $redirectUrl
     * @return array|false|mixed|string
     * @author 段誉
     * @date 2023/2/28 12:15
     */
    public static function pay($payWay, $from, $order, $terminal, $redirectUrl)
    {
        // 支付编号-仅为微信支付预置(同一商户号下不同客户端支付需使用唯一订单号)
        $paySn = $order['order_id'];
        if ($order['pay_price'] === 0) {
            PayNotifyLogic::handle($from, $order['order_id']);
            return ['pay_way' => PayEnum::BALANCE_PAY];
        }
        try {
            if (isset($order['price'])) {
                $order['pay_price'] = $order['price'];
            }
            switch ($payWay) {
                case PayEnum::WECHAT_PAY_MINI:
                    $auth = UserAuth::where(['user_id' => $order['uid'], 'terminal' => $terminal])->findOrEmpty();
                    $order = [
                        'out_trade_no' => $paySn,
                        'description' => '商品',
                        'amount' => [
                            'total' => intval($order['pay_price'] * 100),
                            'currency' => 'CNY',
                        ],
                        "payer" => [
                            "openid" => $auth['openid']
                        ],
                        'attach' => $from
                    ];
                    $wechat = new PayService(1);
                    $result = $wechat->wechat->mini($order)->toArray();
                    break;
                default:
                    throw new BusinessException('支付方式异常');
            }
        } catch (Throwable $e) {
            Log::info($e->extra['message'] ?? $e->getMessage());
            throw new BusinessException($e->extra['message'] ?? $e->getMessage());
        }
        return $result;
    }

    /**
     * 微信条码支付
     */
    public static function codepay($auth_code, $order, $description = '条码商品')
    {
        $pattern = '/^(10|11|12|13|14|15)\d{16}$/';

        if (!preg_match($pattern, (string)$auth_code)) {
            throw new BusinessException('请使用正确的微信收付款条码');
        }
        $data = [
            'description' => $description,
            'out_trade_no' =>  (string)$order['order_id'],
            'payer' => [
                'auth_code' => (string)$auth_code
            ],
            'amount' => [
                'total' => intval($order['pay_price'] * 100),
            ],
            'scene_info' => [
                "store_info" => [
                    'id' => (string)$order['store_id'] ?? 1
                ]
            ],
            'attach' => 'wechat_common'
        ];
        if (isset($order['attach']) && $order['attach'] != '') {
            $data['attach'] = $order['attach'];
        }
        $wechat = new PayService(1);
        try {
            $result = $wechat->wechat->pos($data)->toArray();
        } catch (Throwable $e) {
            Log::error('条码支付报错', ['message' => $e->extra['message'] ?? $e->getMessage(), 'code' => $e->getCode()]);

            if (getenv('APP_DEBUG') == true) {
                throw new BusinessException($e->extra['message'] ?? $e->getMessage());
            } else {
                throw new BusinessException($e->getMessage());
            }
        }
        return $result;
    }

    /**
     * 支付宝条码支付
     */
    public static function ali_auth_code($auth_code, $order)
    {
        $pattern = '/^(25|26|27|28|29|30)[0-9A-Za-z]{14,23}$/';

        if (!preg_match($pattern, (string)$auth_code)) {
            throw new BusinessException('请使用正确的支付宝收付款条码');
        }
        $order = [
            'subject' => '条码商品',
            'out_trade_no' =>  (string)$order['order_id'],
            'auth_code' => (string)$auth_code,
            'total_amount' => $order['pay_price'],
            'extend_params' => ['attach' => 'alipay_cashier']
        ];
        $wechat = new PayService();
        try {
            $result = $wechat->alipay->pos($order)->toArray();
        } catch (Throwable $e) {
            if (getenv('APP_DEBUG') == true) {
                throw new BusinessException($e->extra['message'] ?? $e->getMessage());
            } else {
                throw new BusinessException($e->getMessage());
            }
        }
        return $result;
    }
}