# -*- encoding: utf-8 -*-
"""
@File    : PayUtil.py
@Time    : 2022/6/29 11:41
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""
from urllib.parse import quote

from Ansjer.config import SERVER_DOMAIN_SSL
from Object.AliPayObject import AliPayObject
from Object.WechatPayObject import WechatPayObject

"""
支付服务
"""


class PayService:

    @staticmethod
    def create_alipay_payment(passback_params, order_id, price, title, notify_url, content, response):
        """
        创建支付宝支付
        @param passback_params: 携带参数支付宝回调原样返回
        @param order_id: 订单编号
        @param price: 价格
        @param title: 标题
        @param notify_url: 异步回调通知URL
        @param content: 内容
        @param response: 响应结果
        @return: 网站支付链接
        """
        aliPayObj = AliPayObject()
        alipay = aliPayObj.conf()
        subject = title + content
        order_string = alipay.api_alipay_trade_wap_pay(
            out_trade_no=order_id,
            total_amount=price,
            subject=subject,
            return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
            notify_url="{}{}".format(SERVER_DOMAIN_SSL, notify_url),
            quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
            passback_params=quote(passback_params)
        )
        if not order_string:
            return response.json(10, '生成订单错误.')
        return aliPayObj.alipay_prefix + order_string

    @staticmethod
    def create_wechat_payment(attach, order_id, price, ip, notify_url, content, response):
        """
        创建微信支付
        @param attach: 参数微信回调通知原样返回
        @param order_id: 订单编号
        @param price: 价格
        @param ip: 用户支付ip地址
        @param notify_url: 异步通知回调URL
        @param content: 内容
        @param response: 响应结果
        @return: 网站支付链接
        """
        notify_url = "{}{}".format(SERVER_DOMAIN_SSL, notify_url)
        pay = WechatPayObject()
        # 统一调用接口
        pay.get_parameter(order_id, content, float(price) * 100, ip, notify_url, quote(attach))
        sign_params = pay.re_finall(orderid=order_id)
        if not sign_params:
            return response.json(10, '生成订单错误.')
        return sign_params

    @staticmethod
    def get_two_float(f_str, n):
        # f_str = '{}'.format(f_str) 也可以转换为字符串
        f_str = str(f_str)
        a, b, c = f_str.partition('.')
        # 如论传入的函数有几位小数，在字符串后面都添加n为小数0
        c = (c + "0" * n)[:n]
        return ".".join([a, c])
