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

from __future__ import division

from django.conf import settings
from django.db import transaction
from django_logit import logit
from django_response import response
from paginator import pagination
from TimeConvert import TimeConvert as tc

from account.models import UserInfo
from integral.models import SaleclerkIntegralIncomeExpensesInfo, SaleclerkSubmitLogInfo
from mch.models import BrandInfo, DistributorInfo, ModelInfo, SaleclerkInfo
from statistic.models import (DistributorSaleStatisticInfo, ModelSaleStatisticInfo, ProvinceSaleStatisticInfo,
                              SaleStatisticInfo)
from utils.error.errno_utils import (ProductBrandStatusCode, ProductDistributorStatusCode, ProductModelStatusCode,
                                     SaleclerkStatusCode)


@logit
@transaction.atomic
def clerk_sale_submit_api(request):
    user_id = request.POST.get('user_id', '')
    iv = request.POST.get('iv', '')
    encryptedData = request.POST.get('encryptedData', '')
    lat = float(request.POST.get('lat', 0))
    lon = float(request.POST.get('lon', 0))
    brandID = request.POST.get('BrandID', settings.KODO_DEFAULT_BRAND_PK)
    modelID = request.POST.get('ModelID', '')
    distributorID = request.POST.get('DistributorID', '')
    serialNo = request.POST.get('SerialNo', '')
    verifyResult = request.POST.get('verifyResult', '')

    consumer_name = request.POST.get('consumer_name', '')
    consumer_phone = request.POST.get('consumer_phone', '')

    file_path = request.POST.get('file_path', '')

    try:
        user = UserInfo.objects.get(user_id=user_id, status=True)
    except UserInfo.DoesNotExist:
        return response(SaleclerkStatusCode.CLERK_NOT_FOUND)

    try:
        brand = BrandInfo.objects.get(pk=brandID)
    except BrandInfo.DoesNotExist:
        brand = None
    except ValueError:
        brand = None

    if not brand:
        try:
            brand = BrandInfo.objects.get(brand_id=brandID)
        except BrandInfo.DoesNotExist:
            return response(ProductBrandStatusCode.BRAND_NOT_FOUND)

    try:
        model = ModelInfo.objects.get(pk=modelID)
    except ModelInfo.DoesNotExist:
        return response(ProductModelStatusCode.MODEL_NOT_FOUND)
    except ValueError:
        return response(ProductModelStatusCode.MODEL_NOT_FOUND)

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

    try:
        clerk = SaleclerkInfo.objects.get(brand_id=brand.brand_id, unionid=user.unionid, status=True)
    except SaleclerkInfo.DoesNotExist:
        return response(SaleclerkStatusCode.CLERK_NOT_FOUND)

    # 店员提交记录
    ssli = SaleclerkSubmitLogInfo.objects.create(
        clerk_id=clerk.clerk_id,
        brand_pk=brand.pk,
        model_pk=modelID,
        distributor_pk=distributorID,
        code=serialNo,
        consumer_name=consumer_name,
        consumer_phone=consumer_phone,
        lat=lat,
        lon=lon,
        image=file_path,
        test_user=clerk.test_user,
    )

    try:
        sci = SaleclerkIntegralIncomeExpensesInfo.objects.get(code=serialNo, status=True)
    except SaleclerkIntegralIncomeExpensesInfo.DoesNotExist:
        sci = None

    if sci:
        ssli.dupload = True
        ssli.save()

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

        return response(SaleclerkStatusCode.DUPLICATE_SUBMIT, data={
            'franchiser_name': clerk.distributor_name,
            'clerk_name': clerk.clerk_name,
        } if clerk else {})

    # 店员积分
    integral = model.integral

    clerk.integral += integral
    clerk.total_integral += integral
    clerk.save()

    # 店员积分记录
    SaleclerkIntegralIncomeExpensesInfo.objects.create(
        clerk_id=clerk.clerk_id,
        type=SaleclerkIntegralIncomeExpensesInfo.INCOME,
        brand_id=brand.brand_id,
        brand_name=brand.brand_name,
        model_id=model.model_id,
        model_name=model.model_name,
        distributor_id=distributor.distributor_id,
        distributor_name=distributor.distributor_name,
        code=serialNo,
        consumer_name=consumer_name,
        consumer_phone=consumer_phone,
        lat=lat,
        lon=lon,
        image=file_path,
        integral=integral,
        left_integral=clerk.total_integral,
        test_user=clerk.test_user,
    )

    # TODO: Make statistic async
    if not sci:
        ymd = int(tc.local_string(format='%Y%m%d'))

        # 销量统计
        ssi, _ = SaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd,
        )
        ssi.num += 1
        ssi.save()

        # 型号销量统计
        mssi, _ = ModelSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            model_id=model.model_id,
            ymd=ymd,
        )
        mssi.model_name = model.model_name
        mssi.num += 1
        mssi.save()

        mssi2, _ = ModelSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            model_id=model.model_id,
            ymd=0,
        )
        mssi2.model_name = model.model_name
        mssi2.num += 1
        mssi2.save()

        # 经销商销量统计
        dssi, _ = DistributorSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            distributor_id=distributor.distributor_id,
            ymd=ymd,
        )
        dssi.distributor_name = distributor.distributor_name
        dssi.num += 1
        dssi.save()

        dssi2, _ = DistributorSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            distributor_id=distributor.distributor_id,
            ymd=0,
        )
        dssi2.distributor_name = distributor.distributor_name
        dssi2.num += 1
        dssi2.save()

        # 省份销量统计
        pssi, _ = ProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            province_code=distributor.distributor_province_code,
            ymd=ymd,
        )
        pssi.province_name = distributor.distributor_province_name
        pssi.num += 1
        pssi.save()

        pssi2, _ = ProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            province_code=distributor.distributor_province_code,
            ymd=0,
        )
        pssi2.province_name = distributor.distributor_province_name
        pssi2.num += 1
        pssi2.save()

    return response(200, data={
        'integral': integral,
        'total_integral': clerk.integral,
    })


@logit
def clerk_integral_list_api(request):
    brandID = request.POST.get('BrandID', settings.KODO_DEFAULT_BRAND_PK)
    user_id = request.POST.get('user_id', '')
    page = int(request.POST.get('page', 1))
    num = int(request.POST.get('num', settings.GROUP_NUM_PER_PAGE))

    try:
        user = UserInfo.objects.get(user_id=user_id, status=True)
    except UserInfo.DoesNotExist:
        return response(SaleclerkStatusCode.CLERK_NOT_FOUND)

    try:
        brand = BrandInfo.objects.get(pk=brandID)
    except BrandInfo.DoesNotExist:
        brand = None
    except ValueError:
        brand = None

    if not brand:
        try:
            brand = BrandInfo.objects.get(brand_id=brandID)
        except BrandInfo.DoesNotExist:
            return response(ProductBrandStatusCode.BRAND_NOT_FOUND)

    try:
        clerk = SaleclerkInfo.objects.get(brand_id=brand.brand_id, unionid=user.unionid, status=True)
    except SaleclerkInfo.DoesNotExist:
        return response(SaleclerkStatusCode.CLERK_NOT_FOUND)

    integrals = SaleclerkIntegralIncomeExpensesInfo.objects.filter(clerk_id=clerk.clerk_id).order_by('-pk')
    integrals, left = pagination(integrals, page, num)
    integrals = [integral.data for integral in integrals]

    return response(200, data={
        'integrals': integrals,
        'total_integral': clerk.integral,
    })
