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

from django.db import models
from django.utils.translation import ugettext_lazy as _
from shortuuidfield import ShortUUIDField
from TimeConvert import TimeConvert as tc

from pai2.basemodels import CreateUpdateMixin, LensmanTypeMixin
from photo.models import PhotosInfo
from utils.qiniucdn import qiniu_file_url
from utils.redis.rgroup import get_group_photo_thumbup_flag
from utils.redis.rorder import get_lensman_order_record
from utils.time_utils import origin_expired_stamps
from utils.url_utils import share_url


class GroupInfo(CreateUpdateMixin):
    APP_GROUP = 0
    SESSION_GROUP = 1
    TOURGUIDE_GROUP = 10

    GROUP_FROM = (
        (APP_GROUP, u'APP 建群'),
        (SESSION_GROUP, u'SESSION 建群'),
        (TOURGUIDE_GROUP, u'导游建群'),
    )

    group_id = models.CharField(_(u'group_id'), max_length=255, blank=True, null=True, help_text=u'群组唯一标识', db_index=True, unique=True)
    admin_id = models.CharField(_(u'admin_id'), max_length=255, blank=True, null=True, help_text=u'用户唯一标识', db_index=True)
    group_name = models.CharField(_(u'group_name'), max_length=255, blank=True, null=True, help_text=u'群组名称')
    group_default_avatar = models.IntegerField(_(u'group_default_avatar'), default=0, help_text=u'群组默认头像，0 - 255，水果头像')
    group_avatar = models.CharField(_(u'group_avatar'), max_length=255, blank=True, null=True, help_text=u'群组头像')
    group_desc = models.TextField(_(u'group_desc'), blank=True, null=True, help_text=u'群组描述')
    group_from = models.IntegerField(_(u'group_from'), choices=GROUP_FROM, default=APP_GROUP, help_text=u'群组来源')
    session_id = models.CharField(_(u'session_id'), max_length=255, blank=True, null=True, help_text=u'照片组唯一标识', db_index=True)
    group_lock = models.BooleanField(_(u'group_lock'), default=False, help_text=u'群组锁定')
    group_initio = models.BooleanField(_(u'group_initio'), default=False, help_text=u'群组查看照片从头开始')
    # 旅行团
    name = models.CharField(_(u'name'), max_length=255, blank=True, null=True, help_text=u'导游姓名')
    phone = models.CharField(_(u'phone'), max_length=255, blank=True, null=True, help_text=u'导游电话')
    started_at = models.DateTimeField(_(u'started_at'), blank=True, null=True, help_text=_(u'旅游团开始时间'))
    ended_at = models.DateTimeField(_(u'ended_at'), blank=True, null=True, help_text=_(u'旅游团结束时间'))
    total_persons = models.IntegerField(_(u'total_persons'), default=1, help_text=u'旅游团总人数')
    group_closed = models.BooleanField(_(u'group_closed'), default=False, help_text=u'旅游团关闭')
    gather_at = models.DateTimeField(_(u'gather_at'), blank=True, null=True, help_text=_(u'旅游团集合时间'))
    gather_lon = models.FloatField(_(u'gather_lon'), blank=True, null=True, help_text=_(u'旅游团集合经度'))
    gather_lat = models.FloatField(_(u'gather_lat'), blank=True, null=True, help_text=_(u'旅游团集合纬度'))
    gather_location = models.CharField(_(u'gather_location'), max_length=255, blank=True, null=True, help_text=u'旅游团集合地点')
    gather_screenshot = models.CharField(_(u'gather_screenshot'), max_length=255, blank=True, null=True, help_text=u'旅游团集合地点截图')

    attentions_path = models.CharField(_(u'attentions_path'), max_length=255, blank=True, null=True, help_text=u'注意事项照片存放路径')
    schedules_path = models.CharField(_(u'schedules_path'), max_length=255, blank=True, null=True, help_text=u'行程安排照片存放路径')

    class Meta:
        verbose_name = _(u'groupinfo')
        verbose_name_plural = _(u'groupinfo')

        unique_together = (('session_id', 'group_from'),)

    def __unicode__(self):
        return unicode(self.group_id)

    @property
    def group_avatar_url(self):
        return qiniu_file_url(self.group_avatar, bucket='photo')

    @property
    def group_attentions_url(self):
        return qiniu_file_url(self.attentions_path, bucket='photo')

    @property
    def group_schedules_url(self):
        return qiniu_file_url(self.schedules_path, bucket='photo')

    @property
    def gather_screenshot_url(self):
        return qiniu_file_url(self.gather_screenshot, bucket='photo')

    @property
    def group_photo_num(self):
        return GroupPhotoInfo.objects.filter(group_id=self.group_id, status=True).count()

    @property
    def data(self):
        return {
            'group_id': self.group_id,
            'admin_id': self.admin_id,
            'group_name': self.group_name,
            'group_default_avatar': self.group_default_avatar,
            'group_avatar': self.group_avatar_url,
            'group_desc': self.group_desc,
            'group_from': self.group_from,
            'group_lock': self.group_lock,
            'group_initio': self.group_initio,
            'group_photo_num': self.group_photo_num,
            'name': self.name,
            'phone': self.phone,
            'started_at': tc.remove_microsecond(self.started_at),
            'ended_at': tc.remove_microsecond(self.ended_at),
            'total_persons': self.total_persons,
            'gather_at': tc.remove_microsecond(self.gather_at),
            'gather_lon': self.gather_lon,
            'gather_lat': self.gather_lat,
            'gather_location': self.gather_location,
            'gather_screenshot': self.gather_screenshot_url,
            'created_at': tc.remove_microsecond(self.created_at),
            'banners': {
                'attentions': self.group_attentions_url,
                'schedules': self.group_schedules_url,
            },
        }

    def users(self, admin=True, user_id=None):
        all_users = GroupUserInfo.objects.filter(group_id=self.group_id, user_status__in=[GroupUserInfo.APPLYING, GroupUserInfo.PASSED], status=True)

        passed_users = all_users.filter(user_status=GroupUserInfo.PASSED)
        passed_count = passed_users.count()
        passed = [passed.user_info for passed in passed_users]

        if admin and self.admin_id != user_id:
            return {
                'passed_count': passed_count,
                'passed': passed,
            }

        applying_users = all_users.filter(user_status=GroupUserInfo.APPLYING)
        applying_count = applying_users.count()
        applying = [applying.user_info for applying in applying_users]

        return {
            'applying_count': applying_count,
            'passed_count': passed_count,
            'applying': applying,
            'passed': passed,
        }


class GroupUserInfo(CreateUpdateMixin):
    APPLYING = 0
    PASSED = 1
    REFUSED = 2
    DELETED = 3
    QUIT = 4

    USER_STATUS = (
        (APPLYING, u'申请中'),
        (PASSED, u'已通过'),
        (REFUSED, u'已拒绝'),
        (DELETED, u'已删除'),
        (QUIT, u'已退出'),
    )

    group_id = models.CharField(_(u'group_id'), max_length=255, blank=True, null=True, help_text=u'群组唯一标识', db_index=True)
    user_id = models.CharField(_(u'user_id'), max_length=255, blank=True, null=True, help_text=u'用户唯一标识', db_index=True)
    current_id = models.IntegerField(_(u'current_id'), default=-1, help_text=u'当前群组照片ID')
    nickname = models.CharField(_(u'nickname'), max_length=255, blank=True, null=True, help_text=u'用户群组昵称')
    avatar = models.CharField(_(u'avatar'), max_length=255, blank=True, null=True, help_text=u'用户头像')
    admin = models.BooleanField(_(u'admin'), default=False, help_text=u'群组管理员')
    user_status = models.IntegerField(_(u'user_status'), choices=USER_STATUS, default=APPLYING)
    passed_at = models.DateTimeField(_(u'passed_at'), blank=True, null=True, help_text=_(u'通过时间'))
    refused_at = models.DateTimeField(_(u'refused_at'), blank=True, null=True, help_text=_(u'拒绝时间'))
    deleted_at = models.DateTimeField(_(u'deleted_at'), blank=True, null=True, help_text=_(u'删除时间'))
    quit_at = models.DateTimeField(_(u'quit_at'), blank=True, null=True, help_text=_(u'退出时间'))
    # 旅行团相关
    subadmin = models.BooleanField(_(u'subadmin'), default=False, help_text=u'副群组管理员')
    name = models.CharField(_(u'name'), max_length=255, blank=True, null=True, help_text=u'用户姓名')
    phone = models.CharField(_(u'phone'), max_length=255, blank=True, null=True, help_text=u'用户电话')
    relative_persons = models.IntegerField(_(u'relative_persons'), default=1, help_text=u'关联人数')
    authority = models.BooleanField(_(u'authority'), default=True, help_text=u'是否有定位权限')
    remark = models.CharField(_(u'remark'), max_length=255, blank=True, null=True, help_text=u'备注')
    admin_status = models.BooleanField(_(u'admin_status'), default=True, help_text=_(u'群组管理员状态'))

    class Meta:
        verbose_name = _(u'groupuserinfo')
        verbose_name_plural = _(u'groupuserinfo')

        unique_together = (('group_id', 'user_id'),)

    def __unicode__(self):
        return unicode(self.pk)

    @property
    def user_info(self):
        return {
            'user_id': self.user_id,
            'nickname': self.nickname,
            'avatar': self.avatar,
            'admin': self.admin,
            'subadmin': self.subadmin,
            'name': self.name,
            'phone': self.phone,
            'relative_persons': self.relative_persons,
            'authority': self.authority,
            'remark': self.remark,
        }

    @property
    def admin_info(self):
        return {
            'user_id': self.user_id,
            'nickname': self.nickname,
            'avatar': self.avatar,
            'admin': self.admin,
            'subadmin': self.subadmin,
            'name': self.name,
            'phone': self.phone,
            'relative_persons': self.relative_persons,
            'authority': self.authority,
            'remark': self.remark,
            'status': self.admin_status,
        }


class GroupPhotoInfo(CreateUpdateMixin, LensmanTypeMixin):
    APP_GROUP = 0
    SESSION_GROUP = 1

    PHOTO_FROM = (
        (APP_GROUP, u'APP 建群'),
        (SESSION_GROUP, u'SESSION 建群'),
    )

    photo_id = ShortUUIDField(_(u'photo_id'), max_length=255, help_text=u'照片唯一标识', db_index=True)

    group_id = models.CharField(_(u'group_id'), max_length=255, blank=True, null=True, help_text=u'群组唯一标识', db_index=True)
    user_id = models.CharField(_(u'user_id'), max_length=255, blank=True, null=True, help_text=u'用户唯一标识', db_index=True)
    nickname = models.CharField(_(u'nickname'), max_length=255, blank=True, null=True, help_text=u'用户群组昵称')
    avatar = models.CharField(_(u'avatar'), max_length=255, blank=True, null=True, help_text=u'用户头像')

    photo_md5 = models.CharField(_(u'photo_md5'), max_length=255, blank=True, null=True, help_text=u'照片 MD5', db_index=True)

    photo_path = models.CharField(_(u'photo_path'), max_length=255, blank=True, null=True, help_text=u'照片存放路径')
    has_watermark = models.BooleanField(_(u'has_watermark'), default=False, help_text=_(u'是否有水印'), db_index=True)
    photo_w = models.IntegerField(_(u'photo_w'), default=0, help_text=u'照片宽度')
    photo_h = models.IntegerField(_(u'photo_h'), default=0, help_text=u'照片高度')

    # 双列: 540, 40-50K
    photo_thumbnail_path = models.CharField(_(u'photo_thumbnail_path'), max_length=255, blank=True, null=True, help_text=u'照片缩略图存放路径')
    photo_thumbnail_w = models.IntegerField(_(u'photo_thumbnail_w'), default=0, help_text=u'照片缩略图宽度')
    photo_thumbnail_h = models.IntegerField(_(u'photo_thumbnail_h'), default=0, help_text=u'照片缩略图高度')

    # 单列: 1080, xx-100K
    photo_thumbnail2_path = models.CharField(_(u'photo_thumbnail2_path'), max_length=255, blank=True, null=True, help_text=u'照片缩略图存放路径')
    photo_thumbnail2_w = models.IntegerField(_(u'photo_thumbnail2_w'), default=0, help_text=u'照片缩略图宽度')
    photo_thumbnail2_h = models.IntegerField(_(u'photo_thumbnail2_h'), default=0, help_text=u'照片缩略图高度')

    comment_num = models.IntegerField(_(u'comment_num'), default=0, help_text=u'照片评论数量')
    thumbup_num = models.IntegerField(_(u'thumbup_num'), default=0, help_text=u'照片点赞数量')

    photo_from = models.IntegerField(_(u'photo_from'), choices=PHOTO_FROM, default=APP_GROUP, help_text=u'照片来源')

    session_id = models.CharField(_(u'session_id'), max_length=255, blank=True, null=True, help_text=u'照片组唯一标识，同 PhotosInfo 表', db_index=True)
    lensman_id = models.CharField(_(u'lensman_id'), max_length=255, blank=True, null=True, help_text=u'摄影师唯一标识，同 PhotosInfo 表', db_index=True)
    lensman_photo_id = models.CharField(_(u'lensman_photo_id'), max_length=255, blank=True, null=True, help_text=u'摄影师照片唯一标识，同 PhotosInfo 表', db_index=True)

    nomark = models.IntegerField(_(u'nomark'), default=299, help_text=u'摄影师照片无水印价格(分)')
    origin = models.IntegerField(_(u'origin'), default=999, help_text=u'摄影师照片高清图价格(分)')

    class Meta:
        verbose_name = _(u'groupphotoinfo')
        verbose_name_plural = _(u'groupphotoinfo')

        unique_together = (('group_id', 'user_id', 'photo_md5'),)

    def __unicode__(self):
        return unicode(self.pk)

    @property
    def photo_url(self):
        return qiniu_file_url(self.photo_path, bucket='watermark' if self.has_watermark else 'photo')

    @property
    def photo_thumbnail_url(self):
        return qiniu_file_url(self.photo_thumbnail_path, bucket='thumbnail')

    @property
    def photo_thumbnail2_url(self):
        return qiniu_file_url(self.photo_thumbnail2_path, bucket='thumbnail2')

    @property
    def photo_share_url(self):
        return share_url(self.photo_id)

    @property
    def photo_data(self):
        return {
            'photo_id': self.photo_id,
            'comment_num': self.comment_num,
            'thumbup_num': self.thumbup_num,
        }

    def photo_info(self, user_id):
        try:
            group = GroupInfo.objects.get(group_id=self.group_id)
        except GroupInfo.DoesNotExist:
            group = None
        porder = get_lensman_order_record(self.photo_id, user_id) if self.photo_from == GroupPhotoInfo.SESSION_GROUP else {}
        created_at = self.created_at.replace(microsecond=0)
        return {
            'group_id': group and group.group_id,
            'group_name': group and group.group_name,
            'group_default_avatar': group and group.group_default_avatar,
            'group_avatar': group and group.group_avatar_url,
            'group_from': group and group.group_from,
            'photo_id': self.photo_id,
            'photo_url': self.photo_url,
            'photo_w': self.photo_w,
            'photo_h': self.photo_h,
            'photo_thumbnail_url': self.photo_thumbnail_url,
            'photo_thumbnail_w': self.photo_thumbnail_w,
            'photo_thumbnail_h': self.photo_thumbnail_h,
            'photo_thumbnail2_url': self.photo_thumbnail2_url,
            'photo_thumbnail2_w': self.photo_thumbnail2_w,
            'photo_thumbnail2_h': self.photo_thumbnail2_h,
            'photo_share_url': self.photo_share_url,
            'user_id': self.user_id,
            'nickname': self.nickname,
            'avatar': self.avatar,
            'comment_num': self.comment_num,
            'thumbup': get_group_photo_thumbup_flag(self.pk, user_id),
            'thumbup_num': self.thumbup_num,
            'photo_from': self.photo_from,
            'session_id': self.session_id,
            'nomark': self.nomark,
            'origin': self.origin,
            'porder': porder,
            'created_at': created_at,
            'origin_expired_stamps': origin_expired_stamps(created_at, self.user_id),
            'display_payment_btn': self.photo_from == self.SESSION_GROUP and self.lensman_type not in [self.OUTTAKE],
        }


class GroupPhotoOrderInfo(CreateUpdateMixin):
    group_id = models.CharField(_(u'group_id'), max_length=32, blank=True, null=True, help_text=u'群组唯一标识', db_index=True)
    session_id = models.CharField(_(u'session_id'), max_length=32, blank=True, null=True, help_text=u'照片组唯一标识，同 PhotosInfo 表', db_index=True)
    user_id = models.CharField(_(u'user_id'), max_length=32, blank=True, null=True, help_text=u'用户唯一标识', db_index=True)
    photo_id = models.CharField(_(u'photo_id'), max_length=32, blank=True, null=True, help_text=u'照片唯一标识', db_index=True)
    lensman_photo_id = models.CharField(_(u'lensman_photo_id'), max_length=127, blank=True, null=True, help_text=u'摄影师照片唯一标识，同 PhotosInfo 表', db_index=True)

    m_photo_path = models.CharField(_(u'm_photo_path'), max_length=255, blank=True, null=True, help_text=u'照片存放路径，Box上传，无水印')
    l_photo_path = models.CharField(_(u'l_photo_path'), max_length=255, blank=True, null=True, help_text=u'照片存放路径，美化大图')
    r_photo_path = models.CharField(_(u'r_photo_path'), max_length=255, blank=True, null=True, help_text=u'照片存放路径，高清大图')

    class Meta:
        verbose_name = _(u'groupphotoorderinfo')
        verbose_name_plural = _(u'groupphotoorderinfo')

        unique_together = (('group_id', 'session_id', 'user_id', 'photo_id', 'lensman_photo_id'),)

    def __unicode__(self):
        return unicode(self.pk)

    @property
    def m_photo_url(self):
        return qiniu_file_url(self.m_photo_path, bucket='photo')

    @property
    def l_photo_url(self):
        return qiniu_file_url(self.l_photo_path, bucket='prettify')

    @property
    def r_photo_url(self):
        return qiniu_file_url(self.r_photo_path, bucket='original')

    @property
    def porder_info(self):
        return {
            'm_photo_url': self.m_photo_url,
            'l_photo_url': self.l_photo_url,
            'r_photo_url': self.r_photo_url,
        }


class PhotoCommentInfo(CreateUpdateMixin):
    photo_id = models.CharField(_(u'photo_id'), max_length=255, blank=True, null=True, help_text=u'飞图唯一标识', db_index=True)
    user_id = models.CharField(_(u'user_id'), max_length=255, blank=True, null=True, help_text=u'用户唯一标识', db_index=True)
    nickname = models.CharField(_(u'nickname'), max_length=255, blank=True, null=True, help_text=u'用户群组昵称')
    avatar = models.CharField(_(u'avatar'), max_length=255, blank=True, null=True, help_text=u'用户头像')
    to_uid = models.CharField(_(u'to_uid'), max_length=255, blank=True, null=True, help_text=u'被评论用户唯一标识', db_index=True)
    comment = models.TextField(_(u'comment'), blank=True, null=True, help_text=u'用户评论')

    class Meta:
        verbose_name = _(u'photocommentinfo')
        verbose_name_plural = _(u'photocommentinfo')

    def __unicode__(self):
        return unicode(self.pk)

    @property
    def comment_info(self):
        return {
            'user_id': self.user_id,
            'nickname': self.nickname,
            'avatar': self.avatar,
            'to_uid': self.to_uid,
            'comment': self.comment,
            'created_at': tc.remove_microsecond(self.created_at),
        }


class PhotoThumbUpInfo(CreateUpdateMixin):
    photo_id = models.CharField(_(u'photo_id'), max_length=255, blank=True, null=True, help_text=u'飞图唯一标识', db_index=True)
    user_id = models.CharField(_(u'user_id'), max_length=255, blank=True, null=True, help_text=u'用户唯一标识', db_index=True)
    nickname = models.CharField(_(u'nickname'), max_length=255, blank=True, null=True, help_text=u'用户群组昵称')
    avatar = models.CharField(_(u'avatar'), max_length=255, blank=True, null=True, help_text=u'用户头像')
    thumbup = models.BooleanField(_(u'thumbup'), default=True, help_text=u'用户点赞', db_index=True)

    class Meta:
        verbose_name = _(u'photothumbupinfo')
        verbose_name_plural = _(u'photothumbupinfo')

        unique_together = (('photo_id', 'user_id'),)

    def __unicode__(self):
        return unicode(self.pk)

    @property
    def thumbup_info(self):
        return {
            'user_id': self.user_id,
            'nickname': self.nickname,
            'avatar': self.avatar,
        }
