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

from django.conf import settings
from django.db import transaction
from django.shortcuts import render
from django_logit import logit
from django_response import response
from json_render import json_render

from account.models import LensmanInfo, TourGuideInfo
from mch.models import BrandInfo, DistributorInfo, SaleclerkInfo
from utils.error.errno_utils import ProductBrandStatusCode, ProductDistributorStatusCode, SaleclerkStatusCode
from utils.redis.connect import r


def lensman_oauth(request):
    lensman_type = int(request.GET.get('lt') or 0)
    unionid = request.GET.get('unionid', '')

    try:
        lensman = LensmanInfo.objects.get(unionid=unionid)
    except LensmanInfo.DoesNotExist:
        lensman = None

    return render(request, 'page/lensman_oauth.html', {
        'lensman_type': lensman_type,
        'lensman_info': lensman and lensman.data(lensman_type),
        'modified': bool((not lensman) or (lensman and lensman.modified(lensman_type))),  # 是否可以更改信息
    })


def tourguide_oauth(request):
    unionid = request.GET.get('unionid', '')

    try:
        tourguide = TourGuideInfo.objects.get(unionid=unionid)
    except TourGuideInfo.DoesNotExist:
        tourguide = None

    return render(request, 'page/tourguide_oauth.html', {
        'tourguide_info': tourguide and tourguide.data,
        'modified': bool((not tourguide) or (tourguide and tourguide.modified)),  # 是否可以更改信息
    })


def login_qrcode(request):
    lensman_type = int(request.GET.get('lt') or 0)
    unionid = request.GET.get('unionid', '')

    data = {
        'lensman_type': lensman_type,
        'unionid': unionid,
        'token': r.token(unionid)
    }

    return json_render(request, 'page/login_qrcode.html', data)


def clerk_oauth(request):
    brand_id = request.GET.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    unionid = request.GET.get('unionid', '')

    try:
        BrandInfo.objects.get(brand_id=brand_id, status=True)
    except BrandInfo.DoesNotExist:
        return response(ProductBrandStatusCode.BRAND_NOT_FOUND)

    distributors = DistributorInfo.objects.filter(brand_id=brand_id, status=True)
    distributors = [distributor.admindata for distributor in distributors]

    try:
        clerk = SaleclerkInfo.objects.get(brand_id=brand_id, unionid=unionid, status=True)
    except SaleclerkInfo.DoesNotExist:
        clerk = None

    return render(request, 'page/clerk_oauth.html', {
        'domain': settings.DOMAIN,
        'distributors': distributors,
        'clerk_info': clerk and clerk.data,
        'modified': bool((not clerk) or (clerk and clerk.user_status in [SaleclerkInfo.UNVERIFIED, SaleclerkInfo.REFUSED])),  # 是否可以更改信息
    })


@logit
@transaction.atomic
def clerk_submit_api(request):
    """ 店员授权信息提交 """
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    distributor_id = request.POST.get('distributor_id', '')
    unionid = request.POST.get('unionid', '')
    openid = request.POST.get('openid', '')
    phone = request.POST.get('phone', '')

    if SaleclerkInfo.objects.filter(clerk_phone=phone).exclude(unionid=unionid).exists():
        return response(SaleclerkStatusCode.CLERK_PHONE_ALREADY_EXISTS)

    try:
        distributor = DistributorInfo.objects.get(distributor_id=distributor_id)
    except DistributorInfo.DoesNotExist:
        return response(ProductDistributorStatusCode.DISTRIBUTOR_NOT_FOUND)

    fields = {
        'distributor_id': distributor_id,
        'distributor_name': distributor.distributor_name,
        'clerk_name': request.POST.get('name', ''),
        'clerk_sex': int(request.POST.get('sex', 1)),
        'clerk_phone': phone,
        'openid': openid,
        'user_status': SaleclerkInfo.UNVERIFIED,
    }

    clerk, created = SaleclerkInfo.objects.select_for_update().get_or_create(brand_id=brand_id, unionid=unionid, defaults=fields)
    # clerk.user_status = SaleclerkInfo.UNVERIFIED
    clerk.status = True
    # 状态为 UNVERIFIED 的允许修改, 其他需要登录摄影师 APP 进行信息的修改
    if clerk.user_status not in [SaleclerkInfo.UNVERIFIED, SaleclerkInfo.REFUSED]:
        return response(SaleclerkStatusCode.CLERK_ALREADY_NOT_UNVERIFIED)
    if not created:
        for key, value in fields.iteritems():
            setattr(clerk, key, value)
    clerk.save()

    return response(200, 'Submit Success', u'提交成功', {})
