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

from __future__ import division

from django.conf import settings
from django.contrib.auth.hashers import check_password
from django_logit import logit
from django_response import response
from pywe_miniapp import get_phone_number
from pywe_storage import RedisStorage
from TimeConvert import TimeConvert as tc

from account.models import UserInfo
from mch.models import (AdministratorInfo, BrandInfo, ConsumeInfoSubmitLogInfo, DistributorInfo, LatestAppInfo,
                        ModelInfo, OperatorInfo)
from statistic.models import (ConsumeDistributorSaleStatisticInfo, ConsumeModelSaleStatisticInfo,
                              ConsumeProvinceSaleStatisticInfo, ConsumeSaleStatisticInfo)
from utils.error.errno_utils import (AdministratorStatusCode, OperatorStatusCode, ProductBrandStatusCode,
                                     ProductDistributorStatusCode, ProductModelStatusCode, SaleclerkStatusCode,
                                     UserStatusCode)
from utils.redis.connect import r


WECHAT = settings.WECHAT


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

    if brand_id != settings.KODO_DEFAULT_BRAND_ID:
        return response(ProductBrandStatusCode.BRAND_NOT_MATCH)

    phone = request.POST.get('phone', '')
    password = request.POST.get('password', '')

    try:
        operator = OperatorInfo.objects.get(phone=phone, status=True)
    except OperatorInfo.DoesNotExist:
        return response(OperatorStatusCode.OPERATOR_NOT_FOUND)

    if operator.user_status == OperatorInfo.DISABLED:
        return response(OperatorStatusCode.OPERATOR_NOT_ACTIVATED)
    elif operator.user_status == OperatorInfo.DELETED:
        return response(OperatorStatusCode.OPERATOR_HAS_DELETED)

    if not check_password(password, operator.encryption):
        return response(OperatorStatusCode.OPERATOR_PASSWORD_ERROR)

    return response(200, 'Optor Login Success', u'操作员登录成功', data=operator.kododata)


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

    if brand_id != settings.KODO_DEFAULT_BRAND_ID:
        return response(ProductBrandStatusCode.BRAND_NOT_MATCH)

    phone = request.POST.get('phone', '')
    password = request.POST.get('password', '')

    try:
        administrator = AdministratorInfo.objects.get(phone=phone, status=True)
    except AdministratorInfo.DoesNotExist:
        return response(AdministratorStatusCode.ADMINISTRATOR_NOT_FOUND)

    if administrator.user_status == AdministratorInfo.DISABLED:
        return response(AdministratorStatusCode.ADMINISTRATOR_NOT_ACTIVATED)
    elif administrator.user_status == AdministratorInfo.DELETED:
        return response(AdministratorStatusCode.ADMINISTRATOR_HAS_DELETED)

    if not check_password(password, administrator.encryption):
        return response(AdministratorStatusCode.ADMINISTRATOR_PASSWORD_ERROR)

    request.session['admin_id'] = administrator.admin_id

    return response(200, 'Admin Login Success', u'管理员登录成功', data={
        'qrurl': settings.KODO_CLERK_AUTH_URL.format(administrator.brand_id),
    })


@logit
def bmd_infos(request):
    optor_id = request.POST.get('optor_id', '')

    try:
        operator = OperatorInfo.objects.get(operator_id=optor_id, status=True)
    except OperatorInfo.DoesNotExist:
        return response(OperatorStatusCode.OPERATOR_NOT_FOUND)

    if operator.user_status == OperatorInfo.DISABLED:
        return response(OperatorStatusCode.OPERATOR_NOT_ACTIVATED)

    brands = BrandInfo.objects.filter(brand_id=operator.brand_id, status=True).order_by('position')
    brands = [brand.data for brand in brands]

    models = ModelInfo.objects.filter(brand_id=operator.brand_id, status=True).order_by('position')
    models = [model.data for model in models]

    distributors = DistributorInfo.objects.filter(brand_id=operator.brand_id, status=True).order_by('position')
    distributors = [distributor.data for distributor in distributors]

    return response(200, data={
        'optor_id': operator.operator_id,
        'brands': brands,
        'models': models,
        'distributors': distributors,
    })


@logit
def brands_list(request):
    brands = BrandInfo.objects.filter(status=True).order_by('position')
    brands = [brand.data for brand in brands]

    return response(200, data={
        'brands': brands,
    })


@logit
def models_list(request):
    models = ModelInfo.objects.filter(status=True).order_by('position')
    models = [model.data for model in models]

    return response(200, data={
        'models': models,
    })


@logit
def distributors_list(request):
    distributors = DistributorInfo.objects.filter(status=True).order_by('position')
    distributors = [distributor.data for distributor in distributors]

    return response(200, data={
        'distributors': distributors,
    })


@logit
def upgrade_api(request):
    """ APP 升级 """
    try:
        appinfo = LatestAppInfo.objects.filter(status=True)[0].adr
    except IndexError:
        appinfo = {
            'latest_version_code': '',
            'latest_version_name': '',
            'latest_url': '',
        }

    return response(200, 'Get Latest App Success', u'获取最新版信息成功', {
        'appinfo': appinfo,
    })


def getPhoneNumber(request):
    wxcfg = WECHAT.get('MINIAPP', {})

    appid = wxcfg.get('appID')
    secret = wxcfg.get('appsecret')

    iv = request.POST.get('iv', '')
    encryptedData = request.POST.get('encryptedData', '')

    # {
    #     "phoneNumber": "13580006666",
    #     "purePhoneNumber": "13580006666",
    #     "countryCode": "86",
    #     "watermark":
    #         {
    #             "appid": "APPID",
    #             "timestamp": TIMESTAMP
    #         }
    # }
    phone_number = get_phone_number(appid=appid, secret=secret, encryptedData=encryptedData, iv=iv, storage=RedisStorage(r))

    return phone_number.get('purePhoneNumber', '')


@logit(res=True)
def consumer_phone_api(request):
    return response(200, 'Get Consumer Phone Success', u'获取消费者手机号成功', {
        'purePhoneNumber': getPhoneNumber(request),
    })


@logit(res=True)
def consumer_info_api(request):
    user_id = request.POST.get('user_id', '')
    iv = request.POST.get('iv', '')
    encryptedData = request.POST.get('encryptedData', '')
    lat = request.POST.get('lat', '')
    lon = request.POST.get('lon', '')
    brandID = request.POST.get('BrandID', '')
    modelID = request.POST.get('ModelID', '')
    distributorID = request.POST.get('DistributorID', '')
    serialNo = request.POST.get('SerialNo', '')
    verifyResult = request.POST.get('verifyResult', '')
    purePhoneNumber = request.POST.get('purePhoneNumber', '')

    purePhoneNumber = purePhoneNumber or getPhoneNumber(request)

    # 校验用户是否存在
    try:
        user = UserInfo.objects.get(user_id=user_id)
    except UserInfo.DoesNotExist:
        return response(UserStatusCode.USER_NOT_FOUND)

    # 更新用户手机号
    user.phone = purePhoneNumber
    user.save()

    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)

    # 记录用户信息提交记录
    ConsumeInfoSubmitLogInfo.objects.create(
        user_id=user_id,
        phone=purePhoneNumber,
        iv=iv,
        encryptedData=encryptedData,
        lat=lat,
        lon=lon,
        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,
        serialNo=serialNo,
        verifyResult=verifyResult,
        test_user=user.test_user,
    )

    if not user.test_user:
        # TODO: Make statistic async
        if ConsumeInfoSubmitLogInfo.objects.filter(
            brand_id=brand.brand_id,
            model_id=model.model_id,
            distributor_id=distributor.distributor_id,
            serialNo=serialNo,
            verifyResult=1,
            test_user=False,
        ).count() == 1:
            ymd = int(tc.local_string(format='%Y%m%d'))

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

            # 型号销量统计
            mssi, _ = ConsumeModelSaleStatisticInfo.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, _ = ConsumeModelSaleStatisticInfo.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, _ = ConsumeDistributorSaleStatisticInfo.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, _ = ConsumeDistributorSaleStatisticInfo.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, _ = ConsumeProvinceSaleStatisticInfo.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, _ = ConsumeProvinceSaleStatisticInfo.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, 'Submit Consumer Info Success', u'提交消费者信息成功')
