from apps.wf.mixins import TicketMixin
from apps.utils.viewsets import  CustomModelViewSet
from apps.asm.models import Asset, AssetLog, AssetCate
from rest_framework.exceptions import ParseError
from apps.asm.serializers import AssetSerializer, AssetLogSerializer, AssetCateSerializer, AssetLogCreateSerializer
from apps.wf.models import Ticket
from apps.pum.models import Supplier

class AssetCateViewSet(CustomModelViewSet):
    """
    list: 固定资产分类

    固定资产分类
    """ 
    queryset = AssetCate.objects.all()
    serializer_class = AssetCateSerializer
    search_fields = ['name', 'code']


class AssetViewSet(CustomModelViewSet):
    """
    list: 固定资产台账

    固定资产台账
    """ 
    queryset = Asset.objects.all()
    serializer_class = AssetSerializer
    search_fields = ['name', 'card_number', 'specification']
    filterset_fields = ['keep_dept', 'state']


class AssetLogViewSet(TicketMixin, CustomModelViewSet):
    """
    list: 固定资产操作

    固定资产操作
    """ 
    queryset = AssetLog.objects.all()
    serializer_class = AssetLogSerializer
    create_serializer_class = AssetLogCreateSerializer

    def add_info_for_list(self, data):
        supplierIds = []
        cateIds = []
        for dataitem in data:
            supplierIds.extend([item["supplier"] for item in dataitem["items"]])
            cateIds.extend([item["cate"] for item in dataitem["items"]])
        supplier_dict = dict(Supplier.objects.filter(id__in=supplierIds).values_list("id", "name"))
        assetcate_dict = dict(AssetCate.objects.filter(id__in=cateIds).values_list("id", "name"))
        for dataitem in data:
            for item in dataitem["items"]:
                item["supplier_name"] = supplier_dict.get(item["supplier"], None)
                item["cate_name"] = assetcate_dict.get(item["cate"], None)
        return data
   
    def get_workflow_key(self, instance:AssetLog):
        if instance.type == "入库":
            return "wf_assetlogin"
        raise ParseError("不支持的流程类型")
    
    def gen_other_ticket_data(self, instance:AssetLog):
        return {"keep_dept_name": instance.keep_dept.name}
    
    @staticmethod
    def apply(ticket: Ticket, transition, new_ticket_data: dict):
        assetlog:AssetLog = ticket.assetlog_ticket
        items = assetlog.items
        sr = AssetSerializer(data=items, many=True)
        sr.is_valid(raise_exception=True)
        sr.save(create_by=ticket.create_by)

