from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
import time
from smartfarming.models.agriculture import KnowledgeManage, KnowledgeCategory, Information
from smartfarming.serializers.knowledge_serializer import KnowledgeCategorySerializer, KnowledgeManageSerializer, InformationSerializer
from django.db.models import Q 


class KnowledgeCategoryAPIView(APIView):

    def post(self, request):
        # 知识分类列表
        request_data = request.data 
        if (not request_data.get("pagenum")) and (not request_data.get("pagesize")):
            queryset = KnowledgeCategory.objects.filter(is_delete=1).order_by("-uptime","-addtime")
            serializers = KnowledgeCategorySerializer(queryset, many=True)
            return Response({"code": 0, "msg": "success", "data": serializers.data})
        page_num = int(request_data.get("pagenum", 1)) if request_data.get("pagenum") else 1
        page_size = int(request_data.get("pagesize", 10)) if request_data.get("pagesize") else 10
        title = request_data.get("title")
        if title:
            queryset = KnowledgeCategory.objects.filter(is_delete=1, title=title).order_by("-uptime","-addtime")
        else:
            queryset = KnowledgeCategory.objects.filter(is_delete=1).order_by("-uptime","-addtime")
        total_obj = queryset.count()
        paginator = Paginator(queryset, page_size)
        page_obj = paginator.get_page(page_num)
        serializers = KnowledgeCategorySerializer(page_obj, many=True)
        return Response({"code": 0, "msg": "success", "data": serializers.data, "count": total_obj})
    

class KnowledgeCategoryAddAPIView(APIView):

    def post(self, request):
        # 新增知识分类
        try:
            request_data = request.data 
            title = request_data.get("title")
            knowledge_category,  is_created= KnowledgeCategory.objects.get_or_create(
                title = title,
                is_delete=1,
                defaults={
                    "title": title,
                    "uptime": int(time.time()),
                    "is_use": 1, 
                    "addtime": int(time.time())
                }
            )
            if not is_created:
                return Response({"code": 2, "msg": "该知识分类已存在，请检查"})
            else:
                return Response({"code": 0, "msg": "success"})
        except Exception as e:
            print(e)
            return Response({"code": 2, "msg": "fail"})
        

class KnowledgeCategoryUpdateAPIView(APIView):

    def post(self, request):
        # 知识分类修改
        try:
            request_data = request.data 
            category_id = request_data.get("category_id")
            title = request_data.get("title")
            order = request_data.get("order")
            is_use = request_data.get("is_use")
            category = KnowledgeCategory.objects.get(id=category_id)
            if title:
                try:
                    kg = KnowledgeCategory.objects.get(title=title)
                    if kg.id != category_id:
                        return Response({"code": 0, "msg": "该知识分类已存在，请检查"})
                except Exception as e:
                    pass 
                category.title = title
                category.uptime = int(time.time())
            if order:
                category.order = order
            if is_use:
                category.is_use = is_use
            category.save()
            return Response({"code": 0, "msg": "success"})
        except:
            return Response({"code": 2, "msg": "fail"})


class KnowledgeCategoryDeleteAPIView(APIView):

    def post(self, request):
        # 知识分类删除
        request_data = request.data 
        category_id = request_data.get("category_id")
        manage = KnowledgeManage.objects.filter(category=category_id)
        if manage:
            return Response({"code": 2, "msg": "该知识分类已被知识信息引用，请检查"})
        KnowledgeCategory.objects.filter(id=category_id).update(is_delete=0)
        return Response({"code": 0, "msg": "success"})
    

class KnowledgeManageAPIView(APIView):

    def post(self, request):
        # 知识信息列表
        request_data = request.data 
        category_id = request_data.get("category_id")
        related_plan = request_data.get("related_plan")
        page_num = int(request_data.get("pagenum", 1)) if request_data.get("pagenum") else 1
        page_size = int(request_data.get("pagesize", 10)) if request_data.get("pagesize") else 10
        if category_id and related_plan:
            queryset = KnowledgeManage.objects.filter( Q(is_delete=1) & Q(related_plan__icontains=related_plan) & Q(category=category_id)).order_by("-addtime")
        elif category_id and not related_plan:
            queryset = KnowledgeManage.objects.filter(Q(is_delete=1) & Q(category=category_id) ).order_by("-addtime")
        elif related_plan and not category_id:
            queryset = KnowledgeManage.objects.filter( Q(is_delete=1) & Q(related_plan__icontains=related_plan)).order_by("-addtime")
        else:
            queryset = KnowledgeManage.objects.filter(is_delete=1).order_by("-addtime")
        total_obj = queryset.count()
        paginator = Paginator(queryset, page_size)
        page_obj = paginator.get_page(page_num)
        serializers = KnowledgeManageSerializer(page_obj, many=True)
        return Response({"code": 0, "msg": "success", "data": serializers.data, "count": total_obj})


class KnowledgeManageAddAPIView(APIView):

    def post(self, request):
        # 知识信息新增
        try:
            request_data = request.data
            category_id = request_data.get("category_id")
            related_plan = request_data.get("related_plan", "")
            title = request_data.get("title")
            is_top = request_data.get("is_top")
            if not is_top:
                is_top = 0
            img = request_data.get("img", "")
            origin = request_data.get("origin", "")
            content = request_data.get("content", "")
            is_created = KnowledgeManage.objects.create(
                category = category_id,
                related_plan = related_plan,
                title = title,
                is_top = is_top,
                img = img,
                origin = origin,
                content = content,
                addtime = int(time.time())
            )
            if is_created:
                return Response({"code": 0, "msg": "success"})
            else:
                return Response({"code": 2, "msg": "创建失败"})
        except:
            return Response({"code": 2, "msg": "fail"})
        
class KnowledgeManageUpdateAPIView(APIView):

    def post(self, request):
        # 知识信息更新 
        try:
            request_data = request.data
            update_top = request_data.get("update_top")
            is_top = request_data.get("is_top")
            manage_id = request_data.get("manage_id")
            if update_top:
                try:
                    KnowledgeManage.objects.filter(id=manage_id).update(is_top=is_top)
                    return Response({"code": 0, "msg": "success"})
                except Exception as e:
                    return Response({"code": 2, "msg": "更新失败"})
            category_id = request_data.get("category_id")
            related_plan = request_data.get("related_plan", "")
            title = request_data.get("title")
            img = request_data.get("img", "")
            origin = request_data.get("origin", "")
            content = request_data.get("content", "")
            is_created = KnowledgeManage.objects.filter(id=manage_id).update(
                category = category_id,
                related_plan = related_plan,
                title = title,
                is_top = 1 if is_top else 0,
                img = img,
                origin = origin,
                content = content
            )
            if is_created:
                return Response({"code": 0, "msg": "success"})
            else:
                return Response({"code": 2, "msg": "更新失败"})
        except:
            return Response({"code": 2, "msg": "fail"})


class KnowledgeManageDeleteAPIView(APIView):

    def post(self, request):
        # 知识信息删除
        request_data = request.data
        manage_id = request_data.get("manage_id")
        is_update = KnowledgeManage.objects.filter(id=manage_id).update(is_delete=0)
        if is_update:
            return Response({"code": 0, "msg": "success"})
        else:
            return Response({"code": 2, "msg": "删除失败"})
        

class KnowledgeManageDetailAPIView(APIView):

    def post(self, request):
        # 知识信息更新 
        try:
            request_data = request.data
            manage_id = request_data.get("manage_id")
            queryset = KnowledgeManage.objects.filter(is_delete=1, id=manage_id).order_by("-addtime").first()
            serializers = KnowledgeManageSerializer(queryset)
            return Response({"code": 0, "msg": "success", "data": serializers.data})
        except:
            return Response({"code": 2, "msg": "fail"})



class InformationAPIView(APIView):

    def post(self, request):
        # 研判信息详情
        request_data = request.data 
        title = request_data.get("title")
        page_num = int(request_data.get("pagenum", 1)) if request_data.get("pagenum") else 1
        page_size = int(request_data.get("pagesize", 10)) if request_data.get("pagesize") else 10
        if title:
            queryset = Information.objects.filter(is_delete=1, title__icontains=title).order_by("-addtime")
        else:
            queryset = Information.objects.filter(is_delete=1).order_by("-addtime")
        total_obj = queryset.count()
        paginator = Paginator(queryset, page_size)
        page_obj = paginator.get_page(page_num)
        serializers = InformationSerializer(page_obj, many=True)
        return Response({"code": 0, "msg": "success", "data": serializers.data, "count": total_obj})
    

class InformationAddAPIView(APIView):

    def post(self, request):
        # 研判信息详情
        request_data = request.data 
        myuser = request.myuser
        title = request_data.get("title")
        content = request_data.get("content")
        user = myuser.uid
        information = Information.objects.create(
            title = title,
            content = content,
            addtime = int(time.time()),
            user = user
        )
        if information:
            return Response({"code": 0, "msg": "success"})
        else:
            return Response({"code": 2, "msg": "失败"})
        

class InformationUpdateAPIView(APIView):

    def post(self, request):
        # 研判信息更新
        try:
            request_data = request.data 
            information_id = request_data.get("information_id")
            title = request_data.get("title")
            content = request_data.get("content")
            information = Information.objects.filter(id=information_id).update(
                title = title,
                content = content
            )
            if information:
                return Response({"code": 0, "msg": "success"})
            else:
                return Response({"code": 2, "msg": "失败"})
        except:
            return Response({"code": 2, "msg": "fail"})
        

class InformationDeleteAPIView(APIView):

    def post(self, request):
        # 研判信息更新
        try:
            request_data = request.data 
            information_id = request_data.get("information_id")
            is_delete = Information.objects.filter(id=information_id).update(is_delete=0)
            if is_delete:
                return Response({"code": 0, "msg": "success"})
            else:
                return Response({"code": 2, "msg": "失败"})
        except:
            return Response({"code": 2, "msg": "fail"})