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

from __future__ import division

import xlrd
from django.conf import settings
from pysnippets.strsnippets import strip
from TimeConvert import TimeConvert as tc

from mch.models import BrandInfo, ConsumeInfoSubmitLogInfo, DistributorInfo, ModelInfo
from statistic.models import (ConsumeDistributorSaleStatisticInfo, ConsumeModelSaleStatisticInfo,
                              ConsumeProvinceSaleStatisticInfo, ConsumeSaleStatisticInfo, ConsumeUserStatisticInfo,
                              DistributorSaleStatisticInfo, ModelSaleStatisticInfo, ProvinceSaleStatisticInfo,
                              SaleStatisticInfo)
from utils.redis.connect import r
from utils.redis.rkeys import MINI_PROGRAM_GIS_LIST


PROVINCE_LIST = {
    "110000": "北京市",
    "120000": "天津市",
    "130000": "河北省",
    "140000": "山西省",
    "150000": "内蒙古自治区",
    "210000": "辽宁省",
    "220000": "吉林省",
    "230000": "黑龙江省",
    "310000": "上海市",
    "320000": "江苏省",
    "330000": "浙江省",
    "340000": "安徽省",
    "350000": "福建省",
    "360000": "江西省",
    "370000": "山东省",
    "410000": "河南省",
    "420000": "湖北省",
    "430000": "湖南省",
    "440000": "广东省",
    "450000": "广西壮族自治区",
    "460000": "海南省",
    "500000": "重庆市",
    "510000": "四川省",
    "520000": "贵州省",
    "530000": "云南省",
    "540000": "西藏自治区",
    "610000": "陕西省",
    "620000": "甘肃省",
    "630000": "青海省",
    "640000": "宁夏回族自治区",
    "650000": "新疆维吾尔自治区",
    "710000": "台湾省",
    "810000": "香港特别行政区",
    "820000": "澳门特别行政区"
}


def pre_provinces():
    brands = BrandInfo.objects.filter(status=True)
    for brand in brands:
        for pcode, pname in PROVINCE_LIST.items():
            pssi, created = ProvinceSaleStatisticInfo.objects.get_or_create(brand_id=brand.brand_id, province_code=pcode, ymd=0)
            pssi.province_name = pname
            pssi.save()

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


def pre_models():
    brands = BrandInfo.objects.filter(status=True)
    for brand in brands:
        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=0)
            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=0)
            cmssi.model_name = mdl.model_name
            cmssi.save()


def pre_distributors():
    brands = BrandInfo.objects.filter(status=True)
    for brand in brands:
        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=0)
            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=0)
            cdssi.distributor_name = dtbt.distributor_name
            cdssi.save()


def pre_all():
    pre_provinces()
    pre_models()
    pre_distributors()


# In [55]: cv
# Out[55]: 991000295147.0
#
# In [56]: str(cv)
# Out[56]: '9.91000295147e+11'
#
# In [57]: repr(cv)
# Out[57]: '991000295147.0'
def convert_to_str(cv):
    if isinstance(cv, (int, float)):
        cv = repr(cv)[:-2] if repr(cv).endswith('.0') else repr(cv)
    if isinstance(cv, str):
        cv = cv.strip()
    return cv


def pre_new_models(fpath='./pre/static/models_20180816.xls'):
    workbook = xlrd.open_workbook(fpath)
    # sheet = workbook.sheet_by_name('SMR')
    sheets = workbook.sheets()
    sheet = sheets[0]
    nrows = sheet.nrows
    for idx in range(1, nrows):
        rvals = sheet.row_values(idx)
        print rvals

        jancode = strip(rvals[0])
        if not jancode:
            continue

        mdl, _ = ModelInfo.objects.get_or_create(jancode=jancode)
        mdl.brand_id = settings.KODO_DEFAULT_BRAND_ID
        mdl.brand_name = settings.KODO_DEFAULT_BRAND_NAME
        mdl.model_name = strip(rvals[1])
        mdl.model_uni_name = strip(rvals[2])
        mdl.category = strip(rvals[3])
        mdl.model_full_name = strip(rvals[4])
        mdl.warehouse = strip(rvals[5])
        mdl.save()


def fill_ym():
    for o in ConsumeSaleStatisticInfo.objects.all():
        ymd = str(o.ymd)
        if len(ymd) == 8:
            # 月销量统计
            ssi, _ = ConsumeSaleStatisticInfo.objects.get_or_create(
                brand_id=o.brand_id,
                ymd=ymd[:6],
            )
            ssi.num += o.num
            ssi.save()
            # 年销量统计
            ssi, _ = ConsumeSaleStatisticInfo.objects.get_or_create(
                brand_id=o.brand_id,
                ymd=ymd[:4],
            )
            ssi.num += o.num
            ssi.save()

    for o in ConsumeModelSaleStatisticInfo.objects.all():
        ymd = str(o.ymd)
        if len(ymd) == 8:
            # 月型号销量统计
            mssi, _ = ConsumeModelSaleStatisticInfo.objects.get_or_create(
                brand_id=o.brand_id,
                model_id=o.model_id,
                ymd=ymd[:6],
            )
            mssi.model_name = o.model_name
            mssi.num += o.num
            mssi.save()
            # 年型号销量统计
            mssi, _ = ConsumeModelSaleStatisticInfo.objects.get_or_create(
                brand_id=o.brand_id,
                model_id=o.model_id,
                ymd=ymd[:4],
            )
            mssi.model_name = o.model_name
            mssi.num += o.num
            mssi.save()

    for o in SaleStatisticInfo.objects.all():
        ymd = str(o.ymd)
        if len(ymd) == 8:
            # 月销量统计
            ssi, _ = SaleStatisticInfo.objects.get_or_create(
                brand_id=o.brand_id,
                ymd=ymd[:6],
            )
            ssi.num += o.num
            ssi.save()
            # 年销量统计
            ssi, _ = SaleStatisticInfo.objects.get_or_create(
                brand_id=o.brand_id,
                ymd=ymd[:4],
            )
            ssi.num += o.num
            ssi.save()


def refreshs():
    ConsumeUserStatisticInfo.objects.all().delete()
    ConsumeSaleStatisticInfo.objects.all().delete()
    ConsumeProvinceSaleStatisticInfo.objects.all().delete()
    ConsumeModelSaleStatisticInfo.objects.all().delete()

    logs = ConsumeInfoSubmitLogInfo.objects.filter(verifyResult=1, dupload=False, test_user=False)

    for log in logs:
        ymd = tc.local_string(tc.to_local_datetime(log.created_at), format='%Y%m%d')

        try:
            mdl = ModelInfo.objects.get(model_id=log.model_id)
        except ModelInfo.DoesNotExist:
            continue

        cusi, _ = ConsumeUserStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            ymd=ymd,
        )
        cusi.users = list(set(cusi.users + [log.user_id]))
        cusi.num = len(cusi.users)
        cusi.save()
        cusi, _ = ConsumeUserStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            ymd=ymd[:6],
        )
        cusi.users = list(set(cusi.users + [log.user_id]))
        cusi.num = len(cusi.users)
        cusi.save()
        cusi, _ = ConsumeUserStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            ymd=ymd[:4],
        )
        cusi.users = list(set(cusi.users + [log.user_id]))
        cusi.num = len(cusi.users)
        cusi.save()

        cssi, _ = ConsumeSaleStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            ymd=ymd,
        )
        cssi.num += 1
        cssi.save()
        cssi, _ = ConsumeSaleStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            ymd=ymd[:6],
        )
        cssi.num += 1
        cssi.save()
        cssi, _ = ConsumeSaleStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            ymd=ymd[:4],
        )
        cssi.num += 1
        cssi.save()

        # 日型号销量统计
        cmssi, _ = ConsumeModelSaleStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            model_name=mdl.model_uni_name,
            ymd=ymd,
        )
        cmssi.num += 1
        cmssi.save()
        # 月型号销量统计
        cmssi, _ = ConsumeModelSaleStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            model_name=mdl.model_uni_name,
            ymd=ymd[:6],
        )
        cmssi.num += 1
        cmssi.save()
        # 年型号销量统计
        cmssi, _ = ConsumeModelSaleStatisticInfo.objects.get_or_create(
            brand_id=mdl.brand_id,
            model_name=mdl.model_uni_name,
            ymd=ymd[:4],
        )
        cmssi.num += 1
        cmssi.save()

        r.rpushjson(MINI_PROGRAM_GIS_LIST, {
            'brand_id': log.brand_id,
            'user_id': log.user_id,
            'lat': log.lat,
            'lon': log.lon,
            'phone': log.phone,
            'ymd': tc.local_string(tc.to_local_datetime(log.created_at), format='%Y%m%d'),
        })
