import json


from django.core.paginator import Paginator


from DCbackend.utils.common import success, fail, pageData, saveDocFile
from backend.Form.DocumentForm import DocumentForm
from backend.Service.AdminService import AdminService
from backend.Service.DocumentCategoryService import DocumentCategoryService
from backend.models import Supplier, Document, DocumentCategory, ProductDocument, ProjectDocument, Admin, AdminRole


#
# from docx import Document
# from bs4 import BeautifulSoup

class DocumentService:

    @staticmethod
    def Create(request):
        try:

            form = DocumentForm(request.POST)
            if form.is_valid():
                is_template = request.POST.get("is_template")
                category_id = request.POST.get("category_id")

                if int(is_template) == 0 and category_id == None:
                    return fail("保存文档时,分类不能为空")

                form.save()


                document_id = form.instance.id
                links = json.loads(request.POST.get("links"))
                for link in links:
                    pd = ProductDocument()
                    pd.document_id = document_id
                    pd.product_id = link
                    pd.status = 5
                    pd.save()
                projects = json.loads(request.POST.get("projects"))
                for p in projects:
                    pr = ProjectDocument()
                    pr.project_id = p
                    pr.doc_id = document_id
                    pr.status = 5
                    pr.save()
                return success(document_id)
            else:
                return fail(form.errors)
        except Exception as ex:
            return fail(str(ex))
    @staticmethod
    def Update(request):
        data = Document.objects.filter(id=request.POST.get("id")).first()
        if data is not None:
            data.title = request.POST.get("title")
            data.data = request.POST.get("data")
            data.status = request.POST.get("status")
            data.save()
            links = json.loads(request.POST.get("links"))
            ProductDocument.objects.filter(document_id=data.id).update(status=4)
            for link in links:
                pd = ProductDocument()
                pd.document_id = data.id
                pd.product_id = link
                pd.status = 5
                pd.save()
            projects = json.loads(request.POST.get("projects"))
            ProjectDocument.objects.filter(doc_id=data.id).update(status=4)
            for p in projects:
                pr = ProjectDocument()
                pr.project_id = p
                pr.doc_id = data.id
                pr.status = 5
                pr.save()

            return success(data.id)
        else:
            return fail("更新文档信息失败")

    @staticmethod
    def Info(request):
        info = Document.objects.filter(id=request.POST.get("id")).first()
        return success(DocumentService.getDetail(info))

    @staticmethod
    def Delete(request):
        Document.objects.filter(id=request.POST.get("id")).update(status=4)
        return success("成功")

    @staticmethod
    def getDetail(item: Document):
        where = {}
        where["document_id"] = item.id
        dpList = ProductDocument.objects.filter(**where).exclude(status=4).all()
        linkProduct = []
        for it in dpList:
            # temp = {
            #     'id': it.id,
            #     'product_id': it.product_id,
            #     'document_id': it.document_id,
            # }
            linkProduct.append(it.product_id)

        prList = ProjectDocument.objects.filter(doc_id=item.id).exclude(status=4).all()
        linkProject = []
        for it in prList:
            # temp = {
            #     'id': it.id,
            #     'project_id': it.project_id,
            #     'doc_id': it.doc_id,
            # }
            linkProject.append(it.project_id)

        isTemplate = item.is_template
        username = ''
        if item.is_template is False:
            adminInfo = Admin.objects.filter(id=item.user_id).first()
            username = adminInfo.username
        return {
            "id": item.id,
            'title': item.title,
            'data': item.data,
            'user_id': item.user_id,
            'linkProduct': linkProduct,
            'links': '',
            'linkProject': linkProject,
            'projects': '',
            'category_id': item.category_id,
            'createTime': item.create_time,
            'status': item.status,
            'is_template': item.is_template,
            'user_name': username
        }

    @staticmethod
    def Search(request):



        page = request.POST.get("page")
        pageSize = request.POST.get("pageSize")
        if page is None:
            page = 1
        if pageSize is None:
            pageSize = 1
        where = {}

        admin = AdminService.verify_token(request.POST.get("token"))
        if admin:
            role_id = admin.role_id
            role = AdminRole.objects.filter(id=role_id).first()
            if role.is_admin != 1:
                where["user_id"] = admin.id
        else:
            return fail("token信息异常")

        categoryId = request.POST.get("category_id")
        if categoryId:
            where["category_id"] = categoryId

        title = request.POST.get("title", '')
        if title:
            where["title__icontains"] = title

        status = request.POST.get("status")
        if status:
            where['status'] = status

        paginator = Paginator(Document.objects.filter(**where).exclude(status=4).order_by("-id"),
                              pageSize)  # 每页显示10条数据
        page_obj = paginator.get_page(page)
        dataList = []
        for item in page_obj:
            info = DocumentService.getDetail(item)
            category = DocumentCategory.objects.filter(id=item.category_id).first()
            info['category'] = DocumentCategoryService.getDetail(category)
            dataList.append(info)
        return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))


    @staticmethod
    def pageDocument(request):
        where = {}
        admin = AdminService.verify_token(request.POST.get("token"))
        if admin:
            role_id = admin.role_id
            role = AdminRole.objects.filter(id=role_id).first()
            if role.is_admin != 1:
                where["user_id"] = admin.id
        else:
            return fail("token过期请重新登录")

        page = request.POST.get("page")
        pageSize = request.POST.get("pageSize")
        if page is None:
            page = 1
        if pageSize is None:
            pageSize = 10


        categoryId = request.POST.get("category_id")
        if categoryId:
            where["category_id"] = categoryId

        title = request.POST.get("title", '')
        if title:
            where["title__icontains"] = title

        status = request.POST.get("status")
        if status:
            where['status'] = status

        paginator = Paginator(Document.objects.filter(**where).exclude(status=4).order_by("-id").values('id', 'title', 'category_id','create_time', 'status','is_template','user_id'),pageSize)

        page_obj = paginator.get_page(page)

        # 获取所有需要的 category_id
        category_ids = set(info['category_id'] for info in page_obj if info['category_id'] is not None)

        # 一次性查询所有需要的 DocumentCategory
        categories = {
            cat['id']: cat['name']
            for cat in DocumentCategory.objects.filter(id__in=category_ids).exclude(status=4).values('id', 'name')
        }

        # 获取所有需要的 user_id
        user_ids = set(info['user_id'] for info in page_obj if info['user_id'] is not None)

        # 一次性查询所有需要的 Admin
        admin_info = {
            admin['id']: admin['username']
            for admin in Admin.objects.filter(id__in=user_ids).values('id', 'username')
        }

        dataList = []
        for info in page_obj:
            info_dict = dict(info)  # 转换为可变的字典
            category_id = info_dict['category_id']
            user_id = info_dict['user_id']
            info_dict['type_name'] = categories.get(category_id, '')
            info_dict['user_name'] = admin_info.get(user_id, '')
            dataList.append(info_dict)
        return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))

