# -*- coding: utf-8 -*-

from django.conf import settings
from django_response import response
from pywe_pay import WeChatPay

from account.models import UserInfo


WECHAT = settings.WECHAT


def send_jsapi_hb(brand_id, openid, amount, transfer=True, clerk=False):
    trade_type = 'JSAPI'
    # 根据 trade_type 获取 wechat 配置
    wxcfg = WECHAT.get('{}:{}'.format(brand_id, trade_type), {})
    # WeChatPay 初始化
    wxpay = WeChatPay(wxcfg.get('appID'), wxcfg.get('apiKey'), wxcfg.get('mchID'), mch_cert=wxcfg.get('mch_cert'), mch_key=wxcfg.get('mch_key'))

    if transfer:
        ret_data = wxpay.transfer.transfer(openid, amount, u'企业付款', check_name='NO_CHECK')
    else:
        wxrpk = wxcfg.get('clerkredpack', {}) if clerk else wxcfg.get('redpack', {})
        ret_data = wxpay.redpack.send(
            openid,
            amount,
            send_name=wxrpk.get('SEND_NAME'),
            act_name=wxrpk.get('ACT_NAME'),
            wishing=wxrpk.get('WISHING'),
            remark=wxrpk.get('REMARK'),
            miniprogram=False,
        )
    return ret_data


def jsapi_hb_api(request):
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    user_id = request.POST.get('user_id', '')
    transfer = request.POST.get('transfer', '')

    try:
        user = UserInfo.objects.get(user_id=user_id)
    except UserInfo.DoesNotExist:
        return response()

    openid = user.openid
    amount = 100

    ret_data = send_jsapi_hb(brand_id, openid, amount, transfer=True)

    return response(200, data=ret_data)


def mini_hb_api(request):
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    user_id = request.POST.get('user_id', '')

    try:
        user = UserInfo.objects.get(user_id=user_id)
    except UserInfo.DoesNotExist:
        return response()

    openid = user.openid_miniapp
    amount = 100

    trade_type = 'MINIAPP'
    # 根据 trade_type 获取 wechat 配置
    wxcfg = WECHAT.get('{}:{}'.format(brand_id, trade_type), {})
    # WeChatPay 初始化
    wxpay = WeChatPay(wxcfg.get('appID'), wxcfg.get('apiKey'), wxcfg.get('mchID'), mch_cert=wxcfg.get('mch_cert'), mch_key=wxcfg.get('mch_key'))

    wxrpk = wxcfg.get('redpack', {})
    ret_data = wxpay.redpack.send(
        openid,
        amount,
        send_name=wxrpk.get('SEND_NAME'),
        act_name=wxrpk.get('ACT_NAME'),
        wishing=wxrpk.get('WISHING'),
        remark=wxrpk.get('REMARK'),
        miniprogram=True,
    )

    package = ret_data.get('package', '')

    wxahb_params = wxpay.jsapi.get_jsapi_params(package=package)

    return response(200, data=wxahb_params)
