# coding=utf-8

import json
import xmltodict

from django.db import transaction
from django.http import HttpResponse
from apps.account import tenant_log
from rest_framework.views import APIView

from utils.wx.WXBizMsgCrypt import WXBizMsgCrypt
from utils.exceptions import CustomError
from utils import response_ok, response_error
from utils.wechatpay import WechatPayNotify
from apps.foundation.models import Config,BizLog

from apps.pay.models import Pay


class WechatNotifyView(APIView):

    def dispatch(self, request, *args, **kwargs):
        param = request.body.decode('utf-8')
        tenant_key = Config.getConfigValue(Config.KEY_WECHAT_TENANT_KEY)
        notify = WechatPayNotify(param, tenant_key)

        try:
            data = notify.handle()
            if not data:
                raise CustomError(u'错误的请求！')

            result_code = data['result_code']
            if result_code != 'SUCCESS':
                raise CustomError(u'错误的请求！')

            no = data['out_trade_no']
            amount = int(data['total_fee']) * 100

            with transaction.atomic():
                pay = Pay.getByNo(no)
                pay.payConfirm(amount)
                tenant_log(pay.customer.user, BizLog.INSERT, u'支付成功，no=%s' % no, param)
        except:
            return HttpResponse(WechatPayNotify.response_fail())
        return HttpResponse(WechatPayNotify.response_ok())

