#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   zhangxiaolin
#   E-mail  :   petelin1120@gmail.com
#   Date    :   17/9/28 18:07
#   Desc    :   payment order 管理
import datetime
import json

from django.db import models
from django.db import transaction
from gm_types.pay import CHANNEL


class PaymentManager(models.Manager):
    @transaction.atomic
    def save_from_apple(self, order_ids, pay_time, trade_data):
        payment, create = self.get_or_create(
            transaction_id=trade_data["oid_paybill"],
            defaults=dict(
                total_fee=float(trade_data["money_order"]) * 100,
                channel=CHANNEL.LIANLIAN,
                out_trade_no=trade_data["no_order"],
                pay_start_time=datetime.datetime.strptime(trade_data["dt_order"], '%Y%m%d%H%M%S'),
                paid_time=pay_time,
                notify_data=json.dumps(trade_data),
                account_seller_id=trade_data["oid_partner"],
                third_user_account=None,
            )
        )

        from pay.models import PaymentOrderItem
        to_insert_pois = []
        for order_id in order_ids:
            to_insert_pois.append(PaymentOrderItem(
                order_id=order_id, payment_order=payment
            ))
        PaymentOrderItem.objects.bulk_create(to_insert_pois)

        return payment

    @transaction.atomic
    def save_from_wx(self, order_ids, pay_start_time, pay_time, trade_data):
        payment, create = self.get_or_create(
            transaction_id=trade_data["transaction_id"],
            defaults=dict(
                total_fee=trade_data["total_fee"],
                channel=CHANNEL.WECHAT,
                out_trade_no=trade_data["out_trade_no"],
                pay_start_time=pay_start_time,
                paid_time=pay_time,
                notify_data=json.dumps(trade_data),
                account_seller_id=trade_data["mch_id"],
                third_user_account=trade_data["openid"],
            )
        )

        from pay.models import PaymentOrderItem
        to_insert_pois = []
        for order_id in order_ids:
            to_insert_pois.append(PaymentOrderItem(
                order_id=order_id, payment_order=payment
            ))
        PaymentOrderItem.objects.bulk_create(to_insert_pois)

        return payment

    @transaction.atomic
    def save_from_ali(self, order, data):
        raise Exception("废弃，仅供代码参考")

        payment, create = self.get_or_create(
            transaction_id=data.trade_no,
            defaults=dict(
                total_fee=float(data.total_fee) * 100,
                channel=CHANNEL.ALIPAY,
                out_trade_no=data.out_trade_no,
                pay_start_time=datetime.datetime.strptime(data.gmt_create,
                                                          '%Y-%m-%d %H:%M:%S'),
                paid_time=datetime.datetime.strptime(data.gmt_payment,
                                                     '%Y-%m-%d %H:%M:%S'),
                notify_data=data.to_string(),
                account_seller_id=data.seller_id,
                third_user_account=data.buyer_email,
            )
        )
        from pay.models import PaymentOrderItem
        PaymentOrderItem.objects.get_or_create(order=order, payment_order=payment)
        return payment

    @transaction.atomic
    def save_from_alipay(self, order_ids, pay_start_time, pay_time, trade_data, notify_data_str):
        third_user_account = trade_data["buyer_id"]

        try:
            if "buyer_email" in trade_data and trade_data["buyer_email"]:
                buyer_email = trade_data["buyer_email"]
                if "*" not in buyer_email:
                    third_user_account = buyer_email
        except:
            pass

        payment, create = self.get_or_create(
            transaction_id=trade_data["trade_no"],
            defaults=dict(
                total_fee=float(trade_data["total_fee"]) * 100,
                channel=CHANNEL.ALIPAY,
                out_trade_no=trade_data["out_trade_no"],
                pay_start_time=pay_start_time,
                paid_time=pay_time,
                notify_data=notify_data_str,
                account_seller_id=trade_data["seller_id"],
                third_user_account=third_user_account,
            )
        )

        from pay.models import PaymentOrderItem
        to_insert_pois = []
        for order_id in order_ids:
            to_insert_pois.append(PaymentOrderItem(
                order_id=order_id, payment_order=payment
            ))
        PaymentOrderItem.objects.bulk_create(to_insert_pois)

        return payment
