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

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

from statistic.models import (DistributorSaleStatisticInfo, ModelSaleStatisticInfo, ProvinceSaleStatisticInfo,
                              RegisterStatisticInfo, SaleStatisticInfo)
from utils.rdm_utils import randnum


@logit
def tj_data(request):
    ymd = int(tc.local_string(format='%Y%m%d'))

    # 注册用户统计 & 今日注册用户
    try:
        register_num = RegisterStatisticInfo.objects.get(ymd=ymd).num
    except RegisterStatisticInfo.DoesNotExist:
        register_num = 0

    # 注册用户数趋势
    register_trends = RegisterStatisticInfo.objects.filter(status=True).order_by('-ymd')[:30]
    register_trends = [r.data for r in register_trends]

    # 销量统计 & 今日销量
    try:
        sale_num = SaleStatisticInfo.objects.get(ymd=ymd).num
    except SaleStatisticInfo.DoesNotExist:
        sale_num = 0

    # 商品销量趋势
    sale_trends = SaleStatisticInfo.objects.filter(status=True).order_by('-ymd')[:30]
    sale_trends = [s.data for s in sale_trends]

    # 型号销量统计 & 热销商品榜
    model_sales = ModelSaleStatisticInfo.objects.filter(ymd=0, status=True).order_by('-num')[:3]
    model_sales = [m.data for m in model_sales]

    # 经销商销量统计 & 经销商榜
    distributor_sales = DistributorSaleStatisticInfo.objects.filter(ymd=0, status=True).order_by('-num')[:3]
    distributor_sales = [d.data for d in distributor_sales]

    # 各地区实时销量
    province_sales = ProvinceSaleStatisticInfo.objects.filter(ymd=0, status=True).order_by('position')
    province_sales = [p.data for p in province_sales]

    return response(200, 'Get TJ Data Success', u'获取统计数据成功', {
        'register_num': randnum() if settings.DEBUG_DATA_FLAG else register_num,  # 注册用户统计 & 今日注册用户
        'register_trends': register_trends,  # 注册用户数趋势
        'sale_num': randnum() if settings.DEBUG_DATA_FLAG else sale_num,  # 销量统计 & 今日销量
        'sale_trends': sale_trends,  # 商品销量趋势
        'model_sales': model_sales,  # 型号销量统计 & 热销商品榜
        'distributor_sales': distributor_sales,  # 经销商销量统计 & 经销商榜
        'province_sales': province_sales,  # 各地区实时销量
    })
