# coding=utf-8

import json
import xmltodict
import traceback

from django.db import transaction
from django.http import HttpResponse
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.log.models import BizLog
from apps.WechatApplet.models import WechatApplet
from apps.order.models import Pay
from apps.rebate.bussiness import CustomerRebate


class WechatNotifyView(APIView):

    def dispatch(self, request, *args, **kwargs):
        appid = kwargs['appid']
        applet = WechatApplet.getByAppid(appid)
        param = request.body
        notify = WechatPayNotify(param, applet.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'])
            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'微信支付成功，pay_no=%s' % no, param)
            # 计算返利
            # 在这现金返利发红包(不要在同一个事务里边 防止出错导致 订单状态不能正确改变)
            try:
                with transaction.atomic():  # 因为在计算 返利的时候使用了select_for_update 这个必须在事务里边
                    instance = CustomerRebate(pay)
                    instance.calcul_rebate()
            except Exception as e:
                traceback.print_exc()
        except Exception as e:
            traceback.print_exc()
            return HttpResponse(WechatPayNotify.response_fail())
        return HttpResponse(WechatPayNotify.response_ok())
