import math
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.core.paginator import Paginator
from goods_app.models import Category, Goods


class IndexView(View):
    def get(self, request, category_id=8, num=1):
        category_id = int(category_id)
        num = int(num)
        # 获取所有的商品类别信息
        category_list = Category.objects.all().order_by("id")

        # 获取某个类别下的所有的商品信息
        goods_list = Goods.objects.filter(category_id=category_id).order_by("id")

        # 添加分页功能
        paginator_obj = Paginator(object_list=goods_list, per_page=8)

        page_goods_obj = paginator_obj.page(num)

        # 添加页码数
        start = num - math.ceil(10/2)
        if start < 1:
            start = 1
        end = start + 9
        if end > paginator_obj.num_pages:
            end = paginator_obj.num_pages
        if end < 10:
            start = 1
        else:
            start = end - 9
        page_list = range(start, end+1)

        return render(request, "goods_app/index.html",
                      {"category_list": category_list,
                       "goods_list": page_goods_obj,
                       "currentCid": category_id,
                       "page_list": page_list,
                       })


def recommend(func):
    def _wrapper(detailView, request, goods_id, *args, **kwargs):
        # 获取cookie中的goodsid字符串
        c_goodsid = request.COOKIES.get("c_goodsid", "")
        # 存放用户访问过的商品ID列表
        goodsIdList = [id for id in c_goodsid.split() if id.strip()]
        # 用户访问过的商品对象列表
        goodsObjList = [Goods.objects.get(pk=gid) for gid in goodsIdList if gid != goods_id and Goods.objects.get(pk=gid).category_id == Goods.objects.get(pk=goods_id).category_id][:4]

        if goods_id in goodsIdList:
            goodsIdList.remove(goods_id)
            goodsIdList.insert(0, goods_id)
        else:
            goodsIdList.insert(0, goods_id)
        # 调用视图方法
        response = func(detailView, request, goods_id, recommend_list=goodsObjList, *args, **kwargs)
        # 将用户访问过的商品ID列表存放在cookie中
        response.set_cookie("c_goodsid", " ".join(goodsIdList), max_age=3*24*60*60)
        return response
    return _wrapper


class DetailView(View):
    @recommend
    def get(self, request, goods_id, recommend_list=[]):
        goods_id = int(goods_id)
        try:
            goods = Goods.objects.get(pk=goods_id)
            return render(request, "goods_app/detail.html", {"goods": goods, "recommend_list": recommend_list})
        except Goods.DoesNotExist:
            return HttpResponse(status=404)
