<?php
namespace liuniu\repositories;
use app\common\model\OrderLevel as LaveModel;
use app\common\model\UserRelation;
use liuniu\MiniProgramService;
use liuniu\WechatService;

class LevelRepository
{
    /**
     * 微信公众号JS支付
     * @param $orderId
     * @param string $field
     * @return array|string
     * @throws Exception
     */
    public static function wxpay($cid,$orderId,$field="order_id")
    {
        if (is_string($orderId))
            $orderInfo = LaveModel::where($field, $orderId)->find();
        else
            $orderInfo = $orderId;
        if (!$orderInfo || !isset($orderInfo['paid'])) exception('支付订单不存在!');
        if ($orderInfo['paid']) exception('支付已支付!');
        if ($orderInfo['pay_price'] <= 0) exception('该支付无需支付!');
        $openid = UserRelation::userIdToOpenId($orderInfo['user_id']);
        $rs = WechatService::paymentOrder($openid, $orderInfo['order_id'], $orderInfo['pay_price'],"level", $orderInfo['body'],'', 'JSAPI', [],$cid);
        return WechatService::jspay($cid,$rs['prepay_id']);
    }

    /**
     * 小程序JS支付
     * @param $orderId
     * @param string $field
     * @return array|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public static function jsPay($cid,$orderId, $field = 'order_id')
    {
        if (is_string($orderId))
            $orderInfo = LaveModel::where($field, $orderId)->find();
        else
            $orderInfo = $orderId;
        if (!$orderInfo || !isset($orderInfo['paid'])) exception('支付订单不存在!');
        if ($orderInfo['paid']) exception('支付已支付!');
        if ($orderInfo['pay_price'] <= 0) exception('该支付无需支付!');
        $openid = UserRelation::userIdToOpenId($orderInfo['user_id'],'routine_openid');
        return MiniProgramService::paymentOrder($openid, $orderInfo['order_id'], $orderInfo['pay_price'], 'level', $orderInfo['body'],'','',[],$cid);

    }
    /**
     * 微信h5支付
     * @param $orderId
     * @param string $field
     * @return array|string
     * @throws Exception
     */
    public static function h5Pay($cid,$orderId, $field = 'order_id')
    {
        if (is_string($orderId))
            $orderInfo = Donate::where($field, $orderId)->find();
        else
            $orderInfo = $orderId;
        if (!$orderInfo || !isset($orderInfo['paid'])) exception('支付订单不存在!');
        if ($orderInfo['paid']) exception('支付已支付!');
        if ($orderInfo['pay_price'] <= 0) exception('该支付无需支付!');
        return WechatService::payment(false,$cid)->paymentOrder(null, $orderInfo['order_id'], $orderInfo['pay_price'],"level", $orderInfo['body'],'', 'MWEB', [],$cid);
    }
}