# coding=utf-8

import traceback

from django.db import transaction
from django.http import HttpResponse
from django.conf import settings

from rest_framework.views import APIView

from util.exceptions import CustomError
from util.wechatpay import WechatPayNotify
from util.wx.wechat import WeChat

from apps.activity.models import Pay
from apps.WechatApplet.models import WechatApplet
from apps.foundation.models import BizLog


class WechatNotifyView(APIView):

    def dispatch(self, request, *args, **kwargs):
        param = request.body
        appid = kwargs['appid']
        app = WechatApplet.getByAppid(appid)
        # param = request.body.decode('utf-8')
        notify = WechatPayNotify(param, app.agent_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 = float(data['total_fee']) / 100.0
            transaction_id = data['transaction_id']

            with transaction.atomic():
                pay = Pay.getByNo(no)
                pay.payConfirm(amount, transaction_id)
                BizLog.objects.addnew(pay.customer.user, BizLog.INSERT, u'微信支付成功，no=%s' % no)
            # 微信支付成功之后分账  分账不要影响支付结果
            try:
                pay.split_account(app)
            except:
                traceback.print_exc()
        except Exception as e:
            traceback.print_exc()
            return HttpResponse(WechatPayNotify.response_fail())
        return HttpResponse(WechatPayNotify.response_ok())
