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

from __future__ import division

import itertools

from django.conf import settings
from django.db import connection
from django_query import get_query_value
from paginator import pagination

from group.models import GroupPhotoInfo
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.sql.raw import PAI2_HOME_API, PAI2_HOME_WX_API
from utils.time_utils import origin_expired_stamps
from utils.url_utils import share_url


def get_home_photos(request):
    user_id = get_query_value(request, 'user_id')
    page = get_query_value(request, 'page', default=1, val_cast_func=int)
    num = get_query_value(request, 'num', default=settings.PAI2_HOME_PER_PAGE, val_cast_func=int)

    # 执行原生 SQL 语句，获取首页照片列表
    cursor = connection.cursor()
    cursor.execute((PAI2_HOME_WX_API if request.weixin else PAI2_HOME_API).format(
        user_id=user_id,
        offset=0,
        rows=settings.PAI2_HOME_MAX_ROWS,
    ))
    rows = cursor.fetchall()

    # 首页照片分页
    rows, left = pagination(rows, page, num)

    # 首页照片信息
    rows = [{
        'group_id': row[0],
        'group_name': row[1],
        'group_default_avatar': row[2],
        'group_avatar': row[3],
        'group_from': row[4],
        'photo_id': row[5],
        'photo_url': qiniu_file_url(row[6], bucket='watermark' if row[7] else 'photo'),
        'photo_w': row[8],
        'photo_h': row[9],
        'photo_thumbnail_url': qiniu_file_url(row[10], bucket='thumbnail'),
        'photo_thumbnail_w': row[11],
        'photo_thumbnail_h': row[12],
        'photo_thumbnail2_url': qiniu_file_url(row[13], bucket='thumbnail2'),
        'photo_thumbnail2_w': row[14],
        'photo_thumbnail2_h': row[15],
        'photo_share_url': share_url(row[5]),  # Warning: Index of This Line is 5
        'user_id': row[16],
        'nickname': row[17],
        'avatar': row[18],
        'comment_num': row[19],
        'thumbup_num': row[20],
        'photo_from': row[21],
        'session_id': row[22],
        'nomark': row[23],
        'origin': row[24],
        'created_at': row[25],
        'origin_expired_stamps': origin_expired_stamps(row[25], row[16]),
        'thumbup': get_group_photo_thumbup_flag(row[5], user_id),
        'porder': get_lensman_order_record(row[5], user_id) if row[21] == GroupPhotoInfo.SESSION_GROUP else {},
        'display_payment_btn': row[21] == GroupPhotoInfo.SESSION_GROUP and row[27] not in [GroupPhotoInfo.OUTTAKE],
        'longitude': row[28],
        'latitude': row[29],
        'location': row[30],
    } for row in rows]

    session_photos = map(lambda x: {'session_id': x[0], 'photos': list(x[1])}, itertools.groupby(rows, lambda x: x.get('session_id', '')))

    return rows, session_photos, left
