#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: vv
# Date: 2019/11/5
import json
import yop_security_utils
from django.conf import settings
import yop_request_sdk as yp2util_rsa
from api.tool.log_tool import yibao_pay_logger


class YIBAO_PAY(object):
    def __init__(self, sercet_key=settings.YIBAO_PRIVATE_KEY):
        self.__sercet_key = sercet_key
        self.__merchantNo = settings.YIBAO_MERCHANTNO
        self.__parentMerchantNo = settings.YIBAO_MERCHANTNO
        self.__notify_url = settings.YIBAO_NOTIFY_URL
        self.__redirectUrl = settings.YIBAO_REDIRECT_RUL
        self.__gen_token_uri = settings.YIBAO_API['token_uri']
        self.__cashier_url_prefix = settings.YIBAO_API['cashier']

    def sign_data(self, data):
        """
        https://open.yeepay.com/docs/e-commerceprotocols/5afd43472181f8275762d7da.html
        1. sorted_rules 参数都必须传递, 默认为空串
        2. sorted_rules 顺序不能改变
        :param data:
        :return:
        """
        unsigned_string = ""
        sorted_rules = (
            (1, "merchantNo"),
            (2, "token"),
            (3, "timestamp"),
            (4, "directPayType"),
            (5, "cardType"),
            (6, "userNo"),
            (7, "userType"),
            (8, "ext"),
        )
        for _, param in sorted_rules:
            value = data.get(param, "")
            if param == "ext" and not value:
                value = {
                    "appId": "",
                    "openId": "",
                    "clientId": ""
                }
            unsigned_string += "%s=%s&" % (param, value)

        yibao_pay_logger.info("INFO: 【%s】----1" % unsigned_string)
        unsigned_string = unsigned_string.strip("&")
        yibao_pay_logger.info("INFO: 【%s】----【%s】2" % (unsigned_string, type(unsigned_string)))
        unsigned_string = unsigned_string.encode('utf8')
        sign = yop_security_utils.sign_rsa(unsigned_string, private_key=self.__sercet_key)
        yibao_pay_logger.info("INFO: 【%s】----3" % sign)
        signed_string = "?sign=" + sign + '$SHA256' + '&' + unsigned_string
        return signed_string

    def get_token(self, params):
        """
        生成网银支付token
        :return:
        """
        if isinstance(params, dict):
            params.update({
                "merchantNo": self.__merchantNo,
                "parentMerchantNo": self.__parentMerchantNo,
                "notifyUrl": self.__notify_url,
                "redirectUrl": self.__redirectUrl,
            })

        result, code = yp2util_rsa.restful_param(api=self.__gen_token_uri, params=params)
        if code != 'OPR00000':
            token = None
        else:
            token = result['token']
        return token, result

    def gen_direct_url(self, casher):
        """
        生成支付链接
        :return:
        """
        if isinstance(casher, dict):
            casher.update({
                "merchantNo": self.__merchantNo,
            })
        return self.__cashier_url_prefix + self.sign_data(casher)


yibao = YIBAO_PAY(settings.YIBAO_PRIVATE_KEY)
