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

from __future__ import division

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

from account.models import SaleclerkInfo, UserInfo
from integral.models import SaleclerkIntegralIncomeExpensesInfo, SaleclerkSubmitLogInfo
from mch.models import DistributorInfo, ModelInfo
from product.models import ProductModelInfo
from statistic.models import DistributorSaleStatisticInfo, ModelSaleStatisticInfo, SaleStatisticInfo
from utils.error.errno_utils import ProductDistributorStatusCode, ProductModelStatusCode, SaleclerkStatusCode


def clerk_sale_oauth(request):
    unionid = request.GET.get('unionid', '')

    models = ProductModelInfo.objects.filter(status=True)
    models = [model.data for model in models]

    try:
        clerk = SaleclerkInfo.objects.get(unionid=unionid)
    except SaleclerkInfo.DoesNotExist:
        clerk = None

    return render(request, 'page/clerk_sale.html', {
        'domain': settings.DOMAIN,
        'models': models,
        'clerk_info': clerk and clerk.data,
    })


@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))
    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:
        clerk = SaleclerkInfo.objects.get(unionid=user.unionid, status=True)
    except SaleclerkInfo.DoesNotExist:
        return response(SaleclerkStatusCode.CLERK_NOT_FOUND)

    # 店员提交记录
    ssli = SaleclerkSubmitLogInfo.objects.create(
        franchiser_id=clerk.franchiser_id,
        clerk_id=clerk.clerk_id,
        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.franchiser_name,
            'clerk_name': clerk.clerk_name,
        } if clerk else {})

    # 店员积分
    try:
        model = ModelInfo.objects.get(pk=modelID)
    except ModelInfo.DoesNotExist:
        return response(ProductModelStatusCode.MODEL_NOT_FOUND)

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

    integral = model.integral

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

    # 店员积分记录
    SaleclerkIntegralIncomeExpensesInfo.objects.create(
        franchiser_id=clerk.franchiser_id,
        clerk_id=clerk.clerk_id,
        type=SaleclerkIntegralIncomeExpensesInfo.INCOME,
        model_id=model.model_id,
        model_name=model.model_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,
    )

    if not sci:
        ymd = int(tc.local_string(format='%Y%m%d'))

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

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

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

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

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

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


@logit
def clerk_integral_list_api(request):
    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:
        clerk = SaleclerkInfo.objects.get(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,
    })
