# coding=utf-8
from __future__ import unicode_literals, absolute_import

import json
import datetime
from xml.etree import ElementTree

from rpc.tool.error_code import gen
from rpc.tool.error_code import CODES
from api.models import Order
from api.models import ORDER_STATUS

from django.db import models

__all__ = ['AlipaySettlementManager', 'WechatSettlementManager', 'AppleSettlementManager']


class ConvertNotifyData(object):
    def __init__(self, data):
        self.data = data

    def __getattr__(self, item):
        '''
        item can be a dictionary or a ElementTree
        then you can get the value like 'x.y'
        '''
        if isinstance(self.data, dict):
            return self.data[item]
        else:
            return self.data.findtext(item)

    def to_string(self):
        if isinstance(self.data, dict):
            return json.dumps(self.data)
        else:
            return ElementTree.tostring(self.data)


class AlipaySettlementManager(models.Manager):
    def create_record(self, settlement, trade_data, origin_data_string):
        #buyer_email = trade_data.get("buyer_email", "") #新版接口没有这个字段，用原有写法会报错
        #payment = trade_data.get("total_fee") if trade_data.get("total_fee") else trade_data.get("total_amount")

        #由于trade_data可能是XML，所以之前这个写法在没有ConvertNotifyData的时候获取payment会为空
        #但是现有的ConvertNotifyData在调用dict不存在key的时候会直接报错，如果支付宝的数据去掉了对应key，会导致出错
        #要重新对接支付宝APP支付这里需要重新处理（因为APP支付不再返回"buyer_email"直接访问trade_data.buyer_email会报错）

        self.create(
                settlement=settlement,
                trade_no=trade_data["trade_no"],
                trade_status=trade_data["trade_status"],
                buyer_id=trade_data["buyer_id"],
                buyer_email=trade_data["buyer_email"],
                total_fee=trade_data["total_fee"],
                gmt_create=trade_data["gmt_create"],
                gmt_payment=trade_data["gmt_payment"],
                origin_data=origin_data_string,
        )


class WechatSettlementManager(models.Manager):
    def create_record(self, settlement, trade_data):
        total_fee = float(trade_data["total_fee"]) * 0.01

        self.create(
            settlement=settlement,
            appid=trade_data["appid"],
            bank_type=trade_data["bank_type"],
            cash_fee=trade_data["cash_fee"],
            fee_type=trade_data["fee_type"],
            is_subscribe=trade_data["is_subscribe"],
            mch_id=trade_data["mch_id"],
            nonce_str=trade_data["nonce_str"],
            openid=trade_data["openid"],
            out_trade_no=trade_data["out_trade_no"],
            result_code=trade_data["result_code"],
            sign=trade_data["sign"],
            total_fee=total_fee,
            time_end=trade_data["time_end"],
            trade_type=trade_data["trade_type"],
            transaction_id=trade_data["transaction_id"]
        )


class AppleSettlementManager(models.Manager):
    def create_record(self, settlement, trade_data):
        self.create(
            settlement=settlement,
            oid_partner=trade_data["oid_partner"],
            dt_order=datetime.datetime.strptime(trade_data["dt_order"], "%Y%m%d%H%M%S"),
            oid_paybill=trade_data["oid_paybill"],
            money_order=trade_data["money_order"],
        )
