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

from __future__ import division

from django.conf import settings
from django_logit import logit
from django_response import response
from TimeConvert import TimeConvert as tc

from account.models import UserInfo
from mch.models import DistributorInfo
from sales.models import SalesResponsibilityInfo, SalesResponsibilityInfoModelsSaleStatisticInfo, SuperSalesResponsibilityInfoModelsSaleStatisticInfo
from utils.error.errno_utils import UserStatusCode, SalesResponsibilityStatusCode


@logit
def sr_submit_api(request):
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    user_id = request.POST.get('user_id', '')
    name = request.POST.get('name', '')
    phone = request.POST.get('phone', '')

    if SalesResponsibilityInfo.objects.filter(brand_id=brand_id, phone=phone).exclude(user_id=user_id).exists():
        return response(SalesResponsibilityStatusCode.SR_PHONE_ALREADY_EXISTS)

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

    SalesResponsibilityInfo.objects.update_or_create(unionid=user.unionid, brand_id=brand_id, defaults={
        'user_id': user.user_id,
        'openid': user.openid,
        'name': name,
        'phone': phone,
        'user_status': SalesResponsibilityInfo.UNVERIFIED,
        'status': True,
    })

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


@logit
def sr_distributor_list(request):
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    sr_id = request.POST.get('sr_id', '')

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

    return response(data={
        'distributors': distributors,
    })


@logit
def sr_distributor_tj(request):
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    distributor_id = request.POST.get('distributor_id', '')

    sales = SalesResponsibilityInfoModelsSaleStatisticInfo.objects.filter(brand_id=brand_id, distributor_id=distributor_id, ymd=tc.local_string(format='%Y%m%d'), status=True).order_by('-is_important', '-yesterday_num', '-current_month', '-last_month')
    sales = [sale.data for sale in sales]

    return response(data={
        'sales': sales,
    })


@logit
def supersr_sr_tj(request):
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    sr_id = request.POST.get('sr_id', '')

    sales = SuperSalesResponsibilityInfoModelsSaleStatisticInfo.objects.filter(brand_id=brand_id, ymd=tc.local_string(format='%Y%m%d'), status=True).order_by('-yesterday_num', '-current_month', '-last_month')
    sales = [sale.data for sale in sales]

    return response(data={
        'sales': sales,
    })
