<?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 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:
                self::$error = '订单异常';
                $result = false;
        }
        } catch (Exception $e) {
            \support\Log::info($e->extra['message']?? $e->getMessage());
            throw new \Exception($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)) {
            self::$error = '请使用正确的微信收付款条码';
            return false;
        }
        $order = [
            '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
                ]
            ],
        ];
        $wechat = new PayService(1);
        try {
            $result = $wechat->wechat->pos($order)->toArray();
        } catch (Exception $e) {
            if (getenv('APP_DEBUG') == true) {
                self::$error = $e->extra['message'] ?? $e->getMessage();
            } else {
                self::$error = $e->getMessage();
            }
            return false;
        }
        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)) {
            self::$error = '请使用正确的支付宝收付款条码';
            return false;
        }
        $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 (Exception $e) {
            if (getenv('APP_DEBUG') == true) {
                self::$error = $e->extra['message'] ?? $e->getMessage();
            } else {
                self::$error = $e->getMessage();
            }
            return false;
        }
        return $result;
    }
}