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

from __future__ import division

import os

import shortuuid
from curtail_uuid import CurtailUUID
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.core.files.storage import default_storage
from django.http import JsonResponse
from TimeConvert import TimeConvert as tc

from account.models import LensmanInfo, UserInfo
from group.models import GroupInfo, GroupPhotoInfo, GroupUserInfo
from photo.models import PhotosInfo
from utils.error.errno_utils import LensmanStatusCode, UserStatusCode
from utils.error.response_utils import response
from utils.redis.rgroup import get_group_info, get_group_users_info, set_group_info, set_group_users_info
from utils.redis.rkeys import GROUP_LAST_PHOTO_PK
from utils.thumbnail_utils import make_thumbnail
from utils.watermark_utils import watermark_wrap


r = settings.REDIS_CACHE


def lensman_submit_api(request):
    """
    摄影师信息提交
    :param request:
    :return:
    """
    unionid = request.POST.get('unionid', '')
    phone = request.POST.get('phone', '')

    if LensmanInfo.objects.filter(phone=phone).exclude(unionid=unionid).exists():
        return response(LensmanStatusCode.LENSMAN_PHONE_ALREADY_EXISTS)

    fields = {
        'name': request.POST.get('name', ''),
        'sex': int(request.POST.get('sex', 1)),
        'phone': phone,
        'location': request.POST.get('location', ''),
        'user_status': LensmanInfo.UNVERIFIED,
    }

    lensman, created = LensmanInfo.objects.get_or_create(unionid=unionid, defaults=fields)
    # 状态为 UNVERIFIED 的允许修改, 其他需要登录摄影师 APP 进行信息的修改
    if lensman.user_status not in [LensmanInfo.UNVERIFIED, LensmanInfo.REFUSED]:
        return response(LensmanStatusCode.LENSMAN_ALREADY_NOT_UNVERIFIED)
    if not created:
        for key, value in fields.iteritems():
            setattr(lensman, key, value)
        lensman.save()

    return response(200, 'Submit Success', u'提交成功', {})


def lensman_login_api(request):
    """
    摄影师登录
    :param request:
    :return:
    """
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

    try:
        lensman = LensmanInfo.objects.get(username=username)
    except LensmanInfo.DoesNotExist:
        return response(LensmanStatusCode.LENSMAN_NOT_FOUND)

    if not check_password(password, lensman.encryption):
        return response(LensmanStatusCode.LENSMAN_PASSWORD_ERROR)

    try:
        user = UserInfo.objects.get(user_id=lensman.lensman_id)
    except UserInfo.DoesNotExist:
        return response(LensmanStatusCode.LENSMAN_NOT_FOUND)

    return JsonResponse({
        'status': 200,
        'message': u'登录成功',
        'data': user.data,
    })


def lensman_upload_photo_api(request):
    """
    摄影师上传照片
    :param request:
    :return:
    """
    user_id = lensman_id = request.POST.get('user_id', '')
    nickname = request.POST.get('nickname', '')
    session_id = request.POST.get('session', '')

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

    photo = request.FILES.get('photo', '')

    current_id = int(request.POST.get('current_id', -1))

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

    # 判断通过 session_id 创建的群组是否存在，如果不存在，则直接创建
    group, group_created = GroupInfo.objects.get_or_create(session_id=session_id, group_from=GroupInfo.SESSION_GROUP, defaults={
        'group_id': CurtailUUID.uuid(GroupInfo, 'group_id'),
        'admin_id': user_id,
        'group_name': user.final_nickname,
        'group_default_avatar': 0,
    })
    group_id = group.group_id

    # Redis 群组数据缓存
    group_info = set_group_info(group) if group_created else get_group_info(group_id)

    # 判断 group_id/user_id 的群组用户是否存在，如果不存在，则直接创建
    group_user_current_id = -1
    group_user, group_user_created = GroupUserInfo.objects.get_or_create(group_id=group_id, user_id=user_id, defaults={
        # 'current_id': int(r.get(GROUP_LAST_PHOTO_PK % group_id) or -1),
        'current_id': group_user_current_id,  # 通过扫描 session_id 二维码进群的用户，默认可以查看该群组所有照片
        'nickname': nickname or user.final_nickname,
        'avatar': user.avatar,
        'admin': group_created,
        'user_status': GroupUserInfo.PASSED,
        'passed_at': tc.utc_datetime(),
    })
    if not group_user_created:
        group_user.current_id = group_user_current_id
        group_user.user_status = GroupUserInfo.PASSED
        group_user.save()

    # Redis 群组用户数据缓存
    group_users = set_group_users_info(group) if group_user_created else get_group_users_info(group_id, user_id)

    if photo:
        # 写 PhotosInfo 表
        _, extension = os.path.splitext(photo.name)
        extension = extension or 'jpeg'

        m_photo_path = 'photo/{uuid}{extension}'.format(uuid=shortuuid.uuid(), extension=extension)

        if default_storage.exists(m_photo_path):
            default_storage.delete(m_photo_path)
        default_storage.save(m_photo_path, photo)

        p_photo_path = 'photo/{uuid}{extension}'.format(uuid=shortuuid.uuid(), extension=extension)
        watermark_wrap(
            os.path.join(settings.MEDIA_ROOT, m_photo_path).replace('\\', '/'),
            settings.WATERMARK_LOGO,
            os.path.join(settings.MEDIA_ROOT, p_photo_path).replace('\\', '/')
        )

        photo, created = PhotosInfo.objects.get_or_create(
            lensman_id=lensman_id,
            session_id=session_id,
            photo_id=photo_id,
            p_photo_path=p_photo_path,
            m_photo_path=m_photo_path,
        )

        # 写 GroupPhotoInfo 表
        photo_path = photo.p_photo_path
        photo_thumbnail_path = photo_path.replace('.', '_thumbnail.')
        photo_thumbnail2_path = photo_path.replace('.', '_thumbnail2.')

        # 群组照片缩略图生成
        # 双列: 540, 40-50K
        photo_w, photo_h, photo_thumbnail_w, photo_thumbnail_h = make_thumbnail(
            os.path.join(settings.MEDIA_ROOT, photo_path).replace('\\', '/'),
            os.path.join(settings.MEDIA_ROOT, photo_thumbnail_path).replace('\\', '/'),
            settings.THUMBNAIL_MAX_WIDTH
        )

        # 单列: 1080, xx-100K
        photo_w, photo_h, photo_thumbnail2_w, photo_thumbnail2_h = make_thumbnail(
            os.path.join(settings.MEDIA_ROOT, photo_path).replace('\\', '/'),
            os.path.join(settings.MEDIA_ROOT, photo_thumbnail2_path).replace('\\', '/'),
            settings.THUMBNAIL_MAX_WIDTH2
        )

        # 群组照片记录创建
        group_photo = GroupPhotoInfo.objects.create(
            group_id=group_id,
            user_id=user_id,
            nickname=user.final_nickname,
            avatar=user.avatar,
            photo_path=photo_path,
            photo_w=photo_w,
            photo_h=photo_h,
            photo_thumbnail_path=photo_thumbnail_path,
            photo_thumbnail_w=photo_thumbnail_w,
            photo_thumbnail_h=photo_thumbnail_h,
            photo_thumbnail2_path=photo_thumbnail2_path,
            photo_thumbnail2_w=photo_thumbnail2_w,
            photo_thumbnail2_h=photo_thumbnail2_h,
            photo_from=GroupPhotoInfo.SESSION_GROUP,
            session_id=photo.session_id,
            lensman_id=photo.lensman_id,
            lensman_photo_id=photo.photo_id,
        )

        # 设置群组最后一张照片PK
        r.set(GROUP_LAST_PHOTO_PK % group_id, group_photo.pk)

    # 获取从 current_id 到 now 的群组照片列表
    group_photos = GroupPhotoInfo.objects.filter(
        group_id=group_id,
        status=True,
        pk__gt=max(current_id, group_user.current_id),
    ).order_by(
        '-pk'
    )
    latest_photo = group_photos.first()

    return JsonResponse({
        'status': 200,
        'message': u'摄影师照片上传成功',
        'data': {
            'group_id': group_id,
            'current_id': latest_photo and latest_photo.pk or current_id,
            'photos': [photo.photo_info(user_id) for photo in group_photos],
        }
    })
