import json

from django.core.paginator import Paginator
from django.http import JsonResponse

from DCbackend.utils import common
from DCbackend.utils.common import success, fail, pageData
from backend.Form.SourceDataForm import SourceDataForm
from backend.models import SourceData, SourceCategory


class SourceDataService:

    @staticmethod
    def Create(request):
        form = SourceDataForm(request.POST)
        if form.is_valid():
            form.save()
            return success("成功")
        else:
            return fail(form.errors)

    @staticmethod
    def Update(request):
        data = SourceData.objects.filter(id=request.POST.get("id")).first()
        if data is not None:
            data.code = request.POST.get("code")
            data.name = request.POST.get("name")
            data.source_data = request.POST.get("source_data")
            data.status = request.POST.get("status")
            data.category_id = request.POST.get("category_id")
            data.save()
            return success("成功")
        else:
            return fail("更新源数据成功")

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

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

    @staticmethod
    def getDetail(item: SourceData):
        return {
            "id": item.id,
            'code': item.code,
            'name': item.name,
            'source_data': item.source_data,
            'createTime': item.create_time,
            'status': item.status,
            'category_id': item.category_id
        }

    @staticmethod
    def getDetailList(item):
        return {
            "id": item['id'],
            'code': item['code'],
            'name': item['name'],
            'createTime': item['create_time'].strftime('%Y-%m-%d %H:%M:%S') if item['create_time'] else None,
            'status': item['status'],
            'category_id': item['category_id']
        }

    @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 = {}

        code = request.POST.get("code", '')
        if code:
            where["code__icontains"] = code

        name = request.POST.get("name", '')
        if name:
            where["name__icontains"] = name

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

        paginator = Paginator(SourceData.objects.filter(**where).exclude(status=4).order_by("-id").values('id','code','name','status','category_id','create_time'),
                              pageSize)  # 每页显示10条数据
        page_obj = paginator.get_page(page)
        dataList = []
        for item in page_obj:
            dataInfo = SourceDataService.getDetailList(item)
            dataList.append(dataInfo)

        return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))

    @staticmethod
    def findData(request):
        row = request.POST.get("row")
        col = request.POST.get("col")
        tbCode = request.POST.get("code")

        tbData = SourceData.objects.filter(code=tbCode).first()
        if not tbData:
            return fail("数据表标签不正确")

        jsonData = json.loads(tbData.source_data)
        sheetData=jsonData['exportJson']['sheets'][0]['data']
        rowData=sheetData[int(row)] 
        result=''
        if 'v' in rowData[int(col)]:
            result = rowData[int(col)]['v']
        elif 'ct' in rowData[int(col)]:
             if 's' in rowData[int(col)]['ct']:
                 for sub in rowData[int(col)]['ct']['s']:
                     result+=str(sub['v'])

        return success({"result": result})

    @staticmethod
    def Categories(request):
        query = request.POST.get('query', '')
        status = request.POST.get('status', '')
        page = request.POST.get('page', 1)

        sourcecategories = SourceCategory.objects.all()

        if query:
            sourcecategories = sourcecategories.filter(name__icontains=query)
        if status:
            sourcecategories = sourcecategories.filter(status=status)

        paginator = Paginator(sourcecategories, 10)  # 每页显示10条
        page_obj = paginator.get_page(page)
        sourcecategories = paginator.get_page(page)

        data = {
            'status': '200',
            'message': 'success',
            'data': {
                'sourcecategories': [
                    {
                        'id': category.id,
                        'name': category.name,
                        'status': category.status,
                        'created_at': category.created_at.strftime('%Y-%m-%d %H:%M:%S')
                    } for category in page_obj
                ],
                'total': paginator.count,
                'page': page,
                'total_pages': paginator.num_pages
            }
        }

        return JsonResponse(data)

    @staticmethod
    def Catcreat(request):
        name = request.POST.get('name')
        status = request.POST.get('status', 'active')

        sourcecategory = SourceCategory.objects.create(name=name, status=status)

        data = {
            'id': sourcecategory.id,
            'name': sourcecategory.name,
            'status': sourcecategory.status,
            'created_at': sourcecategory.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        return success(data)

    @staticmethod
    def info(request):
        info = SourceCategory.objects.filter(id=request.POST.get("id")).first()

        return success(SourceDataService.getcategory(info))

    @staticmethod
    def updatetype(request):
        data = SourceCategory.objects.filter(id=request.POST.get("id")).first()
        if data is not None:
            data.name = request.POST.get("name")
            data.status = request.POST.get("status")
            data.created_at = request.POST.get("created_at")
            data.save()
            return success("成功")
        else:
            return fail("更新源数据成功")

    @staticmethod
    def getcategory(item: SourceCategory):
        return {
            "id": item.id,
            'name': item.name,
            'status': item.status,
            'created_at': item.created_at
        }