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

import logging

from django.conf import settings


logger = logging.getLogger('logit')


def DJANGO_WE_CFG_FUNC(request, state=None):
    """ WeChat CFG Callback Func """
    if state in ['component_auth', 'component_callback', 'component_preauth_callback']:
        return settings.WECHAT.get('COMPONENT')


def DJANGO_WE_QUOTE_STATE_FUNC(request, state):
    """ WeChat Quote Callback Func """
    from utils.redis.connect import r
    return r.quote(state, short_uuid=True)


def DJANGO_WE_UNQUOTE_STATE_FUNC(request, state):
    """ WeChat UnQuote Callback Func """
    from utils.redis.connect import r
    return r.unquote(state, buf=True)


def DJANGO_WE_BASE_FUNC(code, state, access_info=None):
    """ WeChat Base Redirect Callback Func """


def DJANGO_WE_USERINFO_FUNC(code, state, access_info=None, userinfo=None):
    """ WeChat Userinfo Redirect Callback Func """


def DJANGO_WE_SHARE_FUNC(request, state=None):
    """ WeChat Share Callback Func """


def DJANGO_WE_MESSAGE_CALLBACK_FUNC(request, data, decrypted=None):
    """ WeChat Message Callback Func """


def DJANGO_WE_COMPONENT_CALLBACK_FUNC(request, appid, data, decrypted=None):
    """ WeChat Component Message Callback Func """
    from account.models import UserInfo
    from mch.models import BrandInfo

    logger.info(appid)
    logger.info(data)
    logger.info(decrypted)

    event = decrypted.get('Event', '')
    tousername = decrypted.get('ToUserName', '')
    openid = fromusername = decrypted.get('FromUserName', '')
    unionid = decrypted.get('UnionId', '')
    membercardid = decrypted.get('CardId', '')
    memberusercardcode = decrypted.get('UserCardCode', '')

    try:
        brand = BrandInfo.objects.get(tousername=tousername)
    except BrandInfo.DoesNotExist:
        return

    if event == 'user_get_card':
        UserInfo.objects.filter(brand_id=brand.brand_id, unionid=unionid).update(openid=openid, has_membercard=True, membercardid=membercardid, memberusercardcode=memberusercardcode)
    elif event == 'user_del_card':
        UserInfo.objects.filter(brand_id=brand.brand_id, memberusercardcode=memberusercardcode).update(has_membercard=False)


def DJANGO_WE_REDIS_OBJ_FUNC(request):
    """ WeChat Redis Object Callback Func """
    from utils.redis.connect import r
    return r


def DJANGO_FILE_UPLOAD_CALLBACK_FUNC(request, file_path=None, file_url=None):
    """ DJANGO FILE UPLOAD Callback Func """
    from logs.models import MchLogInfo
    file_type = request.POST.get('file_type', '')

    if file_type == 'logfile':
        optor_id = request.POST.get('optor_id', '')
        version = request.POST.get('version', 0)

        MchLogInfo.objects.create(
            log_file=file_path,
            operator_id=optor_id,
            app_version=version,
        )
