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

from django.conf import settings
from django.db import transaction
from django_logit import logit
from django_models_ext.provincemodels import ProvinceShortModelMixin
from django_response import response
from TimeConvert import TimeConvert as tc

from mch.models import BrandInfo, DistributorInfo, ModelInfo
from statistic.models import (ConsumeDistributorSaleStatisticInfo, ConsumeModelSaleStatisticInfo,
                              ConsumeProvinceSaleStatisticInfo, ConsumeSaleStatisticInfo, DistributorSaleStatisticInfo,
                              ModelSaleStatisticInfo, ProvinceSaleStatisticInfo, RegisterStatisticInfo,
                              SaleStatisticInfo)
from utils.rdm_utils import randnum


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

    ymd = int(tc.local_string(format='%Y%m%d'))

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

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

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

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

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

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

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

    # TOADD: ROI
    rois = ModelSaleStatisticInfo.objects.filter(brand_id=brand_id, ymd=ymd, status=True)
    rois = [m.roi for m in rois]

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


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

    ymd = int(tc.local_string(format='%Y%m%d'))

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

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

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

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

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

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

    # 各地区实时销量
    province_sales = ConsumeProvinceSaleStatisticInfo.objects.filter(brand_id=brand_id, ymd=ymd, 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_STATISTIC_DATA_FLAG else register_num,  # 注册用户统计 & 今日注册用户
        'register_trends': register_trends,  # 注册用户数趋势
        'sale_num': randnum() if settings.DEBUG_STATISTIC_DATA_FLAG else sale_num,  # 销量统计 & 今日销量
        'sale_trends': sale_trends,  # 商品销量趋势
        'model_sales': model_sales,  # 型号销量统计 & 热销商品榜
        'distributor_sales': distributor_sales,  # 经销商销量统计 & 经销商榜
        'province_sales': province_sales,  # 各地区实时销量
    })


@logit
@transaction.atomic
def tj_generate(request):
    # 1 0 * * * curl http://kodo.xfoto.com.cn/api/tj/generate

    __tj_generate(ymd=None)

    return response()


@transaction.atomic
def __tj_generate(ymd=None):
    ymd = ymd or int(tc.local_string(format='%Y%m%d'))

    brands = BrandInfo.objects.filter(status=True)

    for brand in brands:
        for pcode, pname in ProvinceShortModelMixin.PROVINCE_CODE_NAME_DICT.items():
            pssi, created = ProvinceSaleStatisticInfo.objects.get_or_create(
                brand_id=brand.brand_id,
                province_code=pcode,
                ymd=ymd,
            )
            pssi.province_name = pname
            pssi.save()

            cpssi, created = ConsumeProvinceSaleStatisticInfo.objects.get_or_create(
                brand_id=brand.brand_id,
                province_code=pcode,
                ymd=ymd,
            )
            cpssi.province_name = pname
            cpssi.save()

        models = ModelInfo.objects.filter(brand_id=brand.brand_id, status=True)
        for mdl in models:
            mssi, created = ModelSaleStatisticInfo.objects.get_or_create(
                brand_id=brand.brand_id,
                model_id=mdl.model_id,
                ymd=ymd,
            )
            mssi.model_name = mdl.model_name
            mssi.save()

            cmssi, created = ConsumeModelSaleStatisticInfo.objects.get_or_create(
                brand_id=brand.brand_id,
                model_id=mdl.model_id,
                ymd=ymd,
            )
            cmssi.model_name = mdl.model_name
            cmssi.save()

        distributors = DistributorInfo.objects.filter(brand_id=brand.brand_id, status=True)
        for dtbt in distributors:
            dssi, created = DistributorSaleStatisticInfo.objects.get_or_create(
                brand_id=brand.brand_id,
                distributor_id=dtbt.distributor_id,
                ymd=ymd,
            )
            dssi.distributor_name = dtbt.distributor_name
            dssi.save()

            cdssi, created = ConsumeDistributorSaleStatisticInfo.objects.get_or_create(
                brand_id=brand.brand_id,
                distributor_id=dtbt.distributor_id,
                ymd=ymd,
            )
            cdssi.distributor_name = dtbt.distributor_name
            cdssi.save()

        RegisterStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd,
        )

        SaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd,
        )

        ConsumeSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd,
        )
