from django.http.response import JsonResponse
from django.utils import timezone
from django.utils.timezone import localtime

from BookStore import error
from BookStore.function import check_method
from order.models import Order, OrderBook
from store.models import Book, Store


# Create your views here.


def get_orders():
    # 获取当前时间一周前的时间
    now_time = timezone.now()
    timedelta = timezone.timedelta(days=7)
    old_time = now_time - timedelta

    # 获取当前时间前一周内所有订单
    orders = Order.objects.filter(generateDate__gte=old_time, paid=True)

    return orders


def sort_books(orders, store=None):
    books = []
    books_isbn = {}

    for order in orders:
        order_books = OrderBook.objects.filter(order=order)
        for order_book in order_books:
            isbn = order_book.book.isbn
            count = order_book.count

            if books_isbn.get(isbn):
                books_isbn[isbn] += count
            else:
                books_isbn[isbn] = count

    books_isbn = sorted(books_isbn.items(), key=lambda x: x[1], reverse=True)

    for books_isbn in books_isbn[:6]:
        try:
            get_book = Book.objects.get(isbn=books_isbn[0])

            if store:
                book = {'title': get_book.title, 'author': get_book.author, 'sold': books_isbn[1],
                        'pub_year': get_book.pubYear, 'off': get_book.off}
            else:
                book = {'title': get_book.title, 'author': get_book.author, 'sold': books_isbn[1],
                        'pub_year': get_book.pubYear, }

            books.append(book)

        except Exception as e:
            print('sort_books error:', e)
            code, message = error.database_error()
            return JsonResponse({
                'message': message,
            }, status=code)

    return books


@check_method('GET')
def home(request):
    orders = get_orders()

    # 每周优质书籍
    weekly_books = sort_books(orders)

    # 每周优质书店
    get_stores = {}
    stores = []

    for order in orders:
        store_name = order.store.storeName
        sum_price = order.sumPrice

        if get_stores.get(store_name):
            get_stores[store_name] += sum_price
        else:
            get_stores[store_name] = sum_price

    get_stores = sorted(get_stores.items(), key=lambda x: x[1], reverse=True)

    for store_name in get_stores[:6]:
        try:
            store = Store.objects.get(storeName=store_name[0])
            new_store = {'store_id': store.storeName, 'address': store.address,
                         'info': store.info, 'sold': store.sold}
            stores.append(new_store)

        except Exception as e:
            print(e)
            code, message = error.database_error()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 每周新书
    get_books = Book.objects.all()

    times = {}
    new_books = []

    for book in get_books:
        isbn = book.isbn
        create_date = book.createDate

        if times.get(isbn):
            if times[isbn] > create_date:
                times[isbn] = create_date
        else:
            times[isbn] = create_date

    books_isbn = sorted(times.items(), key=lambda x: x[1], reverse=True)

    for isbn in books_isbn[0:6]:
        try:
            time = times.get(isbn[0])
            get_book = Book.objects.get(isbn=isbn[0], createDate=time)
            book = {'create_date': localtime(time).strftime("%Y-%m-%d %H:%M:%S") if time else '',
                    'title': get_book.title, 'author': get_book.author, 'pub_year': get_book.pubYear}
            new_books.append(book)

        except Exception as e:
            print(e)
            code, message = error.database_error()
            return JsonResponse({
                'message': message,
            }, status=code)

    return JsonResponse({
        'message': 'ok',
        'weekly_books': weekly_books,
        'weekly_stores': stores,
        'new_books': new_books,
    })


@check_method('GET')
def store_good_books(request):
    store_id = request.GET.get('store_id')

    try:
        store = Store.objects.get(storeName=store_id)
        orders = Order.objects.filter(store=store)

        books = sort_books(orders, store)

    except Store.DoesNotExist:
        code, message = error.store_id_doesnt_exist(store_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)

    return JsonResponse({
        'message': 'ok',
        'books': books,
    })


@check_method('GET')
def store_new_books(request):
    store_id = request.GET.get('store_id')

    get_books = {}
    try:
        store = Store.objects.get(storeName=store_id)
        books = Book.objects.filter(store=store)

        for book in books:
            get_books[book.bookID] = book.createDate

        get_books = sorted(get_books.items(), key=lambda x: x[1], reverse=True)

        books = []
        for bookID in get_books[0:6]:
            try:
                get_book = Book.objects.get(bookID=bookID[0])
                book = {'create_date': localtime(get_book.createDate).strftime("%Y-%m-%d %H:%M:%S")
                        if get_book.createDate else '',
                        'title': get_book.title,
                        'author': get_book.author, 'price': get_book.price,
                        'pub_year': get_book.pubYear}
                books.append(book)
            except Book.DoesNotExist:
                code, message = error.book_id_doesnt_exist(bookID)
                return JsonResponse({
                    'message': message,
                }, status=code)
    except Store.DoesNotExist:
        code, message = error.store_id_doesnt_exist(store_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)

    return JsonResponse({
        'message': 'ok',
        'books': books,
    })
