from apps.wf.models import Ticket
# TicketFlow, Transition, Workflow, CustomField, State, 
from apps.srm.models import PatentInfo, Papersecret, Platform
from rest_framework.exceptions import ParseError


def bind_patent(ticket: Ticket, transition, new_ticket_data: dict):
    ins = PatentInfo.objects.get(id=new_ticket_data['t_id'])
    ticket_data = ticket.ticket_data
    ticket_data.update({
        't_model': 'patent',
        't_id': ins.id,
    })
    ticket.ticket_data = ticket_data
    ticket.create_by = ins.create_by
    ticket.save()
    if ins.ticket is None:
        ins.ticket = ticket
        ins.save()

def patent_save_ticket_data(ticket: Ticket, new_ticket_data: dict, **kwargs):
    try:
        obj = PatentInfo.objects.get(id=new_ticket_data['t_id'])
    except PatentInfo.DoesNotExist:
        raise ParseError("Publicity t_id 不存在")
    data_save = {k: v for k, v in new_ticket_data.items() if k not in ['t_model', 't_id']}

    for k, v in data_save.items():
        setattr(obj, k, v)
    obj.save()
    

def paperse_patent(ticket: Ticket, transition, new_ticket_data: dict):
    ins = Papersecret.objects.get(id=new_ticket_data['t_id'])
    ticket_data = ticket.ticket_data
    ticket_data.update({
        't_model': 'paperse',
        't_id': ins.id,
    })
    ticket.ticket_data = ticket_data
    ticket.create_by = ins.create_by
    ticket.save()
    if ins.ticket is None:
        ins.ticket = ticket
        ins.save()

def paperse_save_ticket_data(ticket: Ticket, new_ticket_data: dict, **kwargs):
    try:
        obj = Papersecret.objects.get(id=new_ticket_data['t_id'])
    except Papersecret.DoesNotExist:
        raise ParseError("Publicity t_id 不存在")
    data_save = {k: v for k, v in new_ticket_data.items() if k not in ['t_model', 't_id']}

    for k, v in data_save.items():
        setattr(obj, k, v)
    obj.save()


def platform(ticket: Ticket, transition, new_ticket_data: dict):
    ins = Platform.objects.get(id=new_ticket_data['t_id'])
    ticket_data = ticket.ticket_data
    ticket_data.update({
        't_model': 'platform',
        't_id': ins.id,
    })
    ticket.ticket_data = ticket_data
    ticket.create_by = ins.create_by
    ticket.save()
    if ins.ticket is None:
        ins.ticket = ticket
        ins.save()

def save_platform_data(ticket: Ticket, new_ticket_data: dict, **kwargs):
    try:
        obj = Platform.objects.get(id=new_ticket_data['t_id'])
    except Platform.DoesNotExist:
        raise ParseError("Platform t_id 不存在")
    data_save = {k: v for k, v in new_ticket_data.items() if k not in ['t_model', 't_id']}

    for k, v in data_save.items():
        setattr(obj, k, v)
    obj.save()