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

from __future__ import division

import random

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 api.encrypt_views import decrypt
from api.hb_views import exec_clerk_send_jsapi_hb
from account.models import UserInfo
from logs.models import MchInfoDecryptLogInfo, MchInfoEncryptLogInfo
from integral.models import SaleclerkIntegralIncomeExpensesInfo, SaleclerkSubmitLogInfo
from mch.models import ActivityInfo, BrandInfo, ConsumeImpressionInfo, DistributorInfo, ModelInfo, SaleclerkInfo
from statistic.models import (DistributorSaleStatisticInfo, ModelSaleStatisticInfo, ProvinceSaleStatisticInfo,
                              SaleclerkSaleStatisticInfo, SaleStatisticInfo)
from utils.algorithm.b64 import b64_decrypt
from utils.algorithm.caesar import caesar_decrypt
from utils.algorithm.rsalg import rsa_decrypt
from utils.error.errno_utils import (ProductBrandStatusCode, ProductDistributorStatusCode, ProductModelStatusCode,
                                     SaleclerkStatusCode)
from utils.redis.connect import r
from utils.redis.rkeys import REDPACK_WAITING_SEND_LIST


# CIPHER_ALGORITHM = ('CAESAR', 'B64', 'RSA')
CIPHER_ALGORITHM = ('CAESAR', )

CIPHER_PREFIX = {
    'CAESAR': '0',
    'B64': '1',
    'RSA': '2',
}


@logit
@transaction.atomic
def clerk_sale_decrypt_api(request):
    brand_id = request.POST.get('brand_id', '')
    ciphertext = request.POST.get('ciphertext', '')

    prefix, cipherlen, ciphertext = ciphertext.split('+', 2)

    ciphertext = ciphertext[:int(cipherlen)]

    if prefix == CIPHER_PREFIX['CAESAR']:
        plaintext = caesar_decrypt(ciphertext)
    elif prefix == CIPHER_PREFIX['B64']:
        plaintext = b64_decrypt(ciphertext)
    elif prefix == CIPHER_PREFIX['RSA']:
        plaintext = rsa_decrypt(ciphertext)
    else:
        plaintext = ciphertext

    # brand_id#model_id#distributor_id#sn#time
    # AAAA#AAAAAA#AAAAA#AAAAAAAAAAAAAA#180224
    brand_pk, model_pk, distributor_pk, sn, time = plaintext.split('#')

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

    if brand and brand.brand_id != brand_id:
        return response(ProductBrandStatusCode.BRAND_NOT_MATCH)

    if not brand.clerk_direct_submit:
        return decrypt(request)

    try:
        model = ModelInfo.objects.get(pk=model_pk)
    except ModelInfo.DoesNotExist:
        model = None

    mdli, created_at = MchInfoDecryptLogInfo.objects.get_or_create(ciphertext=ciphertext, defaults={
        'brand_pk': brand_pk,
        'model_pk': model_pk,
        'distributor_pk': distributor_pk,
        'sn': sn,
        'decrypt_count': 1,
    })

    if not created_at:
        mdli.decrypt_count += 1
        mdli.save()

    act = ActivityInfo.objects.filter(status=True).order_by('-pk').first()
    has_unexpired_activity = True if act and act.has_unexpired_activity(model.model_uni_name) else False

    coupon_info = {
        'coupon_expire_at': act.final_coupon_expire_at(created_at=None),
        'coupon_value': act.coupon_value,
    } if has_unexpired_activity else {
        'coupon_expire_at': '',
        'coupon_value': 0,
    }

    # 红包
    try:
        elog = MchInfoEncryptLogInfo.objects.get(sn=sn)
    except MchInfoEncryptLogInfo.DoesNotExist:
        elog = None
    except MchInfoEncryptLogInfo.MultipleObjectsReturned:
        elog = None

    user_id = request.POST.get('user_id', '')
    lat = request.POST.get('lat', .0)
    lon = request.POST.get('lon', .0)
    brandID = brand_pk
    modelID = model_pk
    distributorID = distributor_pk
    serialNo = sn

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

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

    test_sn = serialNo in settings.TESTING_SNS

    if lat == 'undefined':
        lat = .0
    if lon == 'undefined':
        lon = .0

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

    if not clerk.is_auth:
        return response(SaleclerkStatusCode.CLERK_NOT_AUTH)

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

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

    # 店员提交记录
    ssli = SaleclerkSubmitLogInfo.objects.create(
        brand_pk=brand.pk,
        brand_name=brand.brand_name,
        model_pk=modelID,
        model_name=model.model_name,
        distributor_pk=distributorID,
        distributor_name=distributor.distributor_name,
        clerk_id=clerk.clerk_id,
        clerk_name=clerk.clerk_name,
        code=serialNo,
        consumer_name=consumer_name,
        consumer_phone=consumer_phone,
        lat=lat,
        lon=lon,
        image=file_path,
        test_user=clerk.test_user,
        test_sn=test_sn,
        ym=ymd[:6],
        ymd=ymd,
    )

    if settings.CHECK_TESTSN_ENABLED and test_sn:
        return response(200, data={
            'integral': 0,
            'total_integral': clerk.integral,
        })

    if settings.CHECK_DUPLOAD_ENABLED:
        try:
            sci = SaleclerkIntegralIncomeExpensesInfo.objects.get(
                brand_id=brand.brand_id,
                model_id=model.model_id,
                code=serialNo,
                status=True
            )
        except SaleclerkIntegralIncomeExpensesInfo.DoesNotExist:
            sci = None
    else:
        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.num += 1
    clerk.integral += integral
    clerk.total_integral += integral
    clerk.save()

    # 店员积分记录
    if integral > 0:
        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 settings.CHECK_DUPLOAD_ENABLED) or (not clerk.test_user and not sci):
        # 日销量统计
        ssi, _ = SaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd,
        )
        ssi.num += 1
        ssi.save()
        # 月销量统计
        ssi, _ = SaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd[:6],
        )
        ssi.num += 1
        ssi.save()
        # 年销量统计
        ssi, _ = SaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd[:4],
        )
        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()
        # 月省份销量统计
        pssi, _ = ProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            province_code=distributor.distributor_province_code,
            ymd=ymd[:6],
        )
        pssi.province_name = distributor.distributor_province_name
        pssi.num += 1
        pssi.save()
        # 年省份销量统计
        pssi, _ = ProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            province_code=distributor.distributor_province_code,
            ymd=ymd[:4],
        )
        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()

        # 日销售员销量统计
        sssi, _ = SaleclerkSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            clerk_id=clerk.clerk_id,
            ymd=ymd,
        )
        sssi.distributor_id = distributor.distributor_id
        sssi.distributor_name = distributor.distributor_name
        sssi.distributor_short_name = distributor.distributor_short_name
        sssi.clerk_name = clerk.clerk_name
        sssi.num += 1
        sssi.save()
        # 月销售员销量统计
        sssi, _ = SaleclerkSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            clerk_id=clerk.clerk_id,
            ymd=ymd[:6],
        )
        sssi.distributor_id = distributor.distributor_id
        sssi.distributor_name = distributor.distributor_name
        sssi.distributor_short_name = distributor.distributor_short_name
        sssi.clerk_name = clerk.clerk_name
        sssi.num += 1
        sssi.save()
        # 年销售员销量统计
        sssi, _ = SaleclerkSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            clerk_id=clerk.clerk_id,
            ymd=ymd[:4],
        )
        sssi.distributor_id = distributor.distributor_id
        sssi.distributor_name = distributor.distributor_name
        sssi.distributor_short_name = distributor.distributor_short_name
        sssi.clerk_name = clerk.clerk_name
        sssi.num += 1
        sssi.save()

    return response(200, data={
        'plaintext': plaintext,
        'logo_url': brand.brand_logo_url if brand else '',
        'model_imgs': model.images if model else [],
        'model_imgs2': model.images2 if model else [],
        'goodsInfo': {
            'BrandID': brand_pk,
            'Brand': brand.brand_name if brand else '',
            'ModelID': model_pk,
            'Model': (model.model_full_name or model.model_name) if model else '',
            'DistributorID': distributor_pk,
            'SerialNo': sn,
        },
        'has_unexpired_activity': has_unexpired_activity,
        'coupon_info': coupon_info,
        'redpack_info': elog.redpack_info if elog else {},
        'integral': integral,
        'total_integral': clerk.integral,
    })


@logit
@transaction.atomic
def clerk_sale_submit_api(request):
    user_id = request.POST.get('user_id', '')
    lat = request.POST.get('lat', .0)
    lon = 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', '')

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

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

    test_sn = serialNo in settings.TESTING_SNS

    if lat == 'undefined':
        lat = .0
    if lon == 'undefined':
        lon = .0

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

    if not clerk.is_auth:
        return response(SaleclerkStatusCode.CLERK_NOT_AUTH)

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

    # 店员提交记录
    ssli = SaleclerkSubmitLogInfo.objects.create(
        brand_pk=brand.pk,
        brand_name=brand.brand_name,
        model_pk=modelID,
        model_name=model.model_name,
        distributor_pk=distributor.pk,
        distributor_name=distributor.distributor_name,
        clerk_id=clerk.clerk_id,
        clerk_name=clerk.clerk_name,
        code=serialNo,
        consumer_name=consumer_name,
        consumer_phone=consumer_phone,
        lat=lat,
        lon=lon,
        image=file_path,
        test_user=clerk.test_user,
        test_sn=test_sn,
        ym=tc.local_string(format='%Y%m'),
        ymd=tc.local_string(format='%Y%m%d'),
    )

    if settings.CHECK_TESTSN_ENABLED and test_sn:
        return response(200, data={
            'integral': 0,
            'total_integral': clerk.integral,
        })

    if settings.CHECK_DUPLOAD_ENABLED:
        try:
            sci = SaleclerkIntegralIncomeExpensesInfo.objects.get(
                brand_id=brand.brand_id,
                model_id=model.model_id,
                code=serialNo,
                status=True
            )
        except SaleclerkIntegralIncomeExpensesInfo.DoesNotExist:
            sci = None
    else:
        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.num += 1
    clerk.integral += integral
    clerk.total_integral += integral
    clerk.save()

    # 店员积分记录
    if integral > 0:
        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 settings.CHECK_DUPLOAD_ENABLED) or (not clerk.test_user and not sci):
        ymd = 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()
        # 月销量统计
        ssi, _ = SaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd[:6],
        )
        ssi.num += 1
        ssi.save()
        # 年销量统计
        ssi, _ = SaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            ymd=ymd[:4],
        )
        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()
        # 月省份销量统计
        pssi, _ = ProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            province_code=distributor.distributor_province_code,
            ymd=ymd[:6],
        )
        pssi.province_name = distributor.distributor_province_name
        pssi.num += 1
        pssi.save()
        # 年省份销量统计
        pssi, _ = ProvinceSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            province_code=distributor.distributor_province_code,
            ymd=ymd[:4],
        )
        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()

        # 日销售员销量统计
        sssi, _ = SaleclerkSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            clerk_id=clerk.clerk_id,
            ymd=ymd,
        )
        sssi.distributor_id = distributor.distributor_id
        sssi.distributor_name = distributor.distributor_name
        sssi.distributor_short_name = distributor.distributor_short_name
        sssi.clerk_name = clerk.clerk_name
        sssi.num += 1
        sssi.save()
        # 月销售员销量统计
        sssi, _ = SaleclerkSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            clerk_id=clerk.clerk_id,
            ymd=ymd[:6],
        )
        sssi.distributor_id = distributor.distributor_id
        sssi.distributor_name = distributor.distributor_name
        sssi.distributor_short_name = distributor.distributor_short_name
        sssi.clerk_name = clerk.clerk_name
        sssi.num += 1
        sssi.save()
        # 年销售员销量统计
        sssi, _ = SaleclerkSaleStatisticInfo.objects.select_for_update().get_or_create(
            brand_id=brand.brand_id,
            clerk_id=clerk.clerk_id,
            ymd=ymd[:4],
        )
        sssi.distributor_id = distributor.distributor_id
        sssi.distributor_name = distributor.distributor_name
        sssi.distributor_short_name = distributor.distributor_short_name
        sssi.clerk_name = clerk.clerk_name
        sssi.num += 1
        sssi.save()

    # 重复上传执行不到此处，为了下面的统一，这里直接赋值
    dupload = False

    try:
        elog = MchInfoEncryptLogInfo.objects.select_for_update().get(sn=serialNo)
    except MchInfoEncryptLogInfo.DoesNotExist:
        elog = None
    except MchInfoEncryptLogInfo.MultipleObjectsReturned:
        elog = None

    if elog and (not dupload) and elog.is_clerk_send_redpack and (not elog.has_clerk_send_redpack) and (elog.clerk_redpack_amount or elog.clerk_redpack_max_amount):
        amount = elog.clerk_redpack_amount
        if elog.clerk_redpack_max_amount:
            amount = random.randint(100, elog.clerk_redpack_max_amount)
        if user.openid:
            exec_clerk_send_jsapi_hb(user, elog, amount)
        else:
            r.rpushjson(REDPACK_WAITING_SEND_LIST, {
                'sn': serialNo,
                'user_id': user.user_id,
                'amount': amount,
                'is_clerk': 1,
            })

    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', '')
    ftime = request.POST.get('ftime', '')
    ttime = request.POST.get('ttime', '')
    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(clerk_id=user.clerk_id, status=True)
    except SaleclerkInfo.DoesNotExist:
        return response(SaleclerkStatusCode.CLERK_NOT_FOUND)

    integrals = SaleclerkIntegralIncomeExpensesInfo.objects.filter(clerk_id=clerk.clerk_id).order_by('-pk')
    if ftime:
        integrals = integrals.filter(created_at__gte=tc.string_to_utc_datetime(ftime))
    if ttime:
        integrals = integrals.filter(created_at__lte=tc.string_to_utc_datetime(ttime))
    integrals, left = pagination(integrals, page, num)
    integrals = [integral.data for integral in integrals]

    return response(200, data={
        'integrals': integrals,
        'total_integral': sum([i.get('integral', 0) for i in integrals]),
        'left_integral': clerk.integral,
    })


@logit
def clerk_consumer_impression_api(request):
    user_id = request.POST.get('user_id', '')
    brand_id = request.POST.get('brand_id', settings.KODO_DEFAULT_BRAND_ID)
    ModelID = request.POST.get('ModelID', '')
    model_id = request.POST.get('model_id', '')
    serialNo = request.POST.get('SerialNo', '')
    sex = request.POST.get('sex', 0)
    rage = request.POST.get('rage', 0)
    identity = request.POST.get('identity', '')
    purpose = request.POST.get('purpose', '')

    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(brand_id=brand_id)
    except BrandInfo.DoesNotExist:
        return response(ProductBrandStatusCode.BRAND_NOT_FOUND)

    try:
        clerk = SaleclerkInfo.get(clerk_id=user.clerk_id, status=True)
    except SaleclerkInfo.DoesNotExist:
        return response(SaleclerkStatusCode.CLERK_NOT_FOUND)

    if ModelID and not model_id:
        try:
            model = ModelInfo.objects.get(pk=ModelID)
        except ModelInfo.DoesNotExist:
            model = None
    else:
        try:
            model = ModelInfo.objects.get(model_id=model_id)
        except ModelInfo.DoesNotExist:
            model = None
        if not model:
            try:
                model = ModelInfo.objects.get(pk=model_id)
            except ModelInfo.DoesNotExist:
                model = None

    ConsumeImpressionInfo.objects.update_or_create(
        clerk_id=clerk.clerk_id,
        brand_id=brand_id,
        model_id=model.model_id if model else model_id,
        serialNo=serialNo,
        defaults={
            'sex': sex,
            'rage': rage,
            'identity': identity,
            'purpose': purpose,
        }
    )

    return response()
