# coding=utf-8
from __future__ import unicode_literals, absolute_import
import requests
import json
import hashlib
from django.db import models
from django.conf import settings

from api.models import Settlement
from pay.manager import AppleSettlementManager
from pay.manager import ApplePayRefundManager
from pay.tool.apple_tool import get_mysign
from api.tool.log_tool import apple_refund_logger
from pay.tool import apple_tool


class ApplePayRefund(models.Model):
    class Meta:
        verbose_name = '苹果支付退款'
        db_table = 'pay_applepayrefund'
        app_label = 'pay'

    order_no = models.CharField(max_length=12, verbose_name='订单号', help_text='gaia order')
    oid_partner = models.CharField(max_length=18, verbose_name='商户号')
    oid_refundno = models.CharField(max_length=16, verbose_name='连连银联通流水号')
    money_refund = models.FloatField(verbose_name='退款金额')
    no_refund = models.CharField(max_length=32, verbose_name='商户唯一标识退款流水号')
    dt_refund = models.DateTimeField(verbose_name='商户退款时间')
    sta_refund = models.CharField(max_length=1, verbose_name='退款状态')
    settle_date = models.DateTimeField(verbose_name='清算日期')

    objects = ApplePayRefundManager()


class ApplePaySettlement(models.Model):
    class Meta:
        verbose_name = '苹果支付结单附加信息'
        db_table = 'pay_applepaysettlement'
        app_label = 'pay'

    settlement = models.ForeignKey(Settlement, verbose_name='关联的结算单')  # no_order
    oid_partner = models.CharField(max_length=18, verbose_name='商户号')
    dt_order = models.DateTimeField(verbose_name='商户订单时间')
    created_time = models.DateTimeField(auto_now_add=True, help_text=u"创建时间")
    oid_paybill = models.CharField(max_length=16, verbose_name='lianlian order_id')
    money_order = models.FloatField(verbose_name='交易金额')

    @property
    def no_order_id(self):
        return self.settlement.id

    objects = AppleSettlementManager()


class ApplePay(object):
    def __init__(self):
        self.sign_type = 'MD5'
        self.busi_partner = '101001'
        self.oid_partner = settings.OID_PARTNER
        self.pay_notify_url = settings.APPLEPAY_PAY_NOTIFY_URL
        self.refund_notify_url = settings.APPLEPAY_REFUND_NOTIFY_URL
        self.query_url = settings.APPLEPAY_QUERY_URL
        self.refund_url = settings.APPLEPAY_REFUND_URL

    def hash_user_id(self, user_id):
        salt = 'zj346OwDO7mD'

        return hashlib.md5(str(user_id) + salt).hexdigest()

    def pay_params(self, user_id, no_order, dt_order, name_goods, info_order, money_order):
        risk_item={
                'frms_ware_category': '1999',
                'user_info_mercht_userno': self.hash_user_id(user_id)
        }
        params = {
            'oid_partner': self.oid_partner,
            'sign_type': self.sign_type,
            'busi_partner': self.busi_partner,
            'no_order': no_order,
            'dt_order': dt_order,
            'name_goods': name_goods,
            'info_order': info_order,
            'money_order': str(money_order),
            'notify_url': self.pay_notify_url,
            'risk_item': json.dumps(risk_item),
        }
        params['sign'] = get_mysign(params)
        params['user_id'] = self.hash_user_id(user_id)
        return params

    def refund(self, no_refund, dt_refund, no_order, dt_order, oid_paybill, money_refund, refund_notify_url):
        params = dict()
        params['no_refund'] = no_refund
        params['dt_refund'] = dt_refund
        params['money_refund'] = money_refund
        params['no_order'] = no_order
        params['dt_order'] = dt_order
        params['oid_paybill'] = oid_paybill
        params['notify_url'] = refund_notify_url
        params['sign_type'] = self.sign_type
        params['oid_partner'] = self.oid_partner
        params['sign'] = get_mysign(params)
        data = json.dumps(params)
        rsp = requests.post(url=self.refund_url, data=data, proxies=settings.APPLE_PROXIES)
        apple_refund_logger.info(rsp.text)
        result = json.loads(rsp.text)
        apple_tool.check_is_from_apple(result)
        return result

    def query(self, no_order, dt_order, oid_paybill):
        params = dict()
        params['no_order'] = no_order
        params['dt_order'] = dt_order
        params['oid_paybill'] = oid_paybill
        params['query_version'] = '1.1'
        params['sign_type'] = self.sign_type
        params['oid_partner'] = self.oid_partner
        params['sign'] = get_mysign(params)
        data = json.dumps(params)
        rsp = requests.post(url=self.query_url, data=data, proxies=settings.APPLE_PROXIES)
        print (rsp.text)
        result = json.loads(rsp.text)
        apple_tool.check_is_from_apple(result)
        return result
