# coding: utf-8

"""
    Zuora API Reference

    REST API reference for the Zuora Billing, Payments, and Central Platform! Check out the [REST API Overview](https://www.zuora.com/developer/api-references/api/overview/).

    The version of the OpenAPI document: 2024-05-20
    Contact: docs@zuora.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from datetime import date
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from zuora_sdk.models.create_order_order_line_item import CreateOrderOrderLineItem
from zuora_sdk.models.create_order_subscription import CreateOrderSubscription
from zuora_sdk.models.order_category import OrderCategory
from zuora_sdk.models.order_create_account import OrderCreateAccount
from zuora_sdk.models.order_scheduling_options import OrderSchedulingOptions
from zuora_sdk.models.processing_options_with_delayed_capture_payment import ProcessingOptionsWithDelayedCapturePayment
from typing import Optional, Set
from typing_extensions import Self

class CreateOrderRequest(BaseModel):
    """
    CreateOrderRequest
    """ # noqa: E501
    # avoid validation
    def __init__(self, **kwargs):
        # Directly assign values without validation using `construct()`
        model = self.construct(**kwargs)
        self.__dict__.update(model.__dict__)

        _dict_all = convert_snake_dict_to_camel(kwargs, self.model_fields, self.__properties)

        _dict = self.to_alias_dict(_dict_all)
        for field_name, field_info in self.model_fields.items():
            alias = field_info.alias or field_name
            if alias in _dict:
                self.__dict__[field_name] = _dict.get(alias)
        self.update_additional_properties(self, _dict_all)
        pass

    def __setattr__(self, name, value):
        # Override setattr to bypass validation when setting attributes
        object.__setattr__(self, name, value)

    category: Optional[OrderCategory] = OrderCategory.NEWSALES
    custom_fields: Optional[Dict[str, Any]] = Field(default=None, description="Container for custom fields of an Order object. ", alias="customFields")
    description: Optional[Annotated[str, Field(strict=True, max_length=500)]] = Field(default=None, description="A description of the order.")
    existing_account_number: Optional[Annotated[str, Field(strict=True, max_length=70)]] = Field(default=None, description="The account number that this order will be created under. It can be either the accountNumber or the account info provided. It will return an error if both are specified. Note that this actually specifies the invoice owner account of the subscriptions included in this order. ", alias="existingAccountNumber")
    externally_managed_by: Optional[StrictStr] = Field(default=None, alias="externallyManagedBy")
    new_account: Optional[OrderCreateAccount] = Field(default=None, alias="newAccount")
    order_date: date = Field(description="The date when the order is signed. All the order actions under this order will use this order date as the contract effective date if the contract effective date field is skipped or its value is left as null.", alias="orderDate")
    order_line_items: Optional[List[CreateOrderOrderLineItem]] = Field(default=None, description="[Order Line Items](https://knowledgecenter.zuora.com/Billing/Subscriptions/Orders/Order_Line_Items/AA_Overview_of_Order_Line_Items) are non subscription based items created by an Order, representing transactional charges such as one-time fees, physical goods, or professional service charges that are not sold as subscription services.   With the Order Line Items feature enabled, you can now launch non-subscription and unified monetization business models in Zuora, in addition to subscription business models.  **Note:** The [Order Line Items](https://knowledgecenter.zuora.com/Billing/Subscriptions/Orders/Order_Line_Items/AA_Overview_of_Order_Line_Items) feature is now generally available to all Zuora customers. You need to enable the [Orders](https://knowledgecenter.zuora.com/BC_Subscription_Management/Orders/AA_Overview_of_Orders#Orders) feature to access the [Order Line Items](https://knowledgecenter.zuora.com/Billing/Subscriptions/Orders/Order_Line_Items/AA_Overview_of_Order_Line_Items) feature. As of Zuora Billing Release 313 (November 2021), new customers who onboard on [Orders](https://knowledgecenter.zuora.com/Billing/Subscriptions/Orders/AA_Overview_of_Orders) will have the [Order Line Items](https://knowledgecenter.zuora.com/Billing/Subscriptions/Orders/Order_Line_Items) feature enabled by default.         ", alias="orderLineItems")
    order_number: Optional[Annotated[str, Field(strict=True, max_length=100)]] = Field(default=None, description="The order number of the new order. If not provided, system will auto-generate a number for this order.    **Note:** Make sure the order number does not contain a slash.  ", alias="orderNumber")
    processing_options: Optional[ProcessingOptionsWithDelayedCapturePayment] = Field(default=None, alias="processingOptions")
    reason_code: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="Values of reason code configured in **Billing Settings** > **Configure Reason Codes** through Zuora UI. Indicates the reason when a return order line item occurs. ", alias="reasonCode")
    scheduling_options: Optional[OrderSchedulingOptions] = Field(default=None, alias="schedulingOptions")
    status: Optional[StrictStr] = None
    subscriptions: Optional[List[CreateOrderSubscription]] = Field(default=None, description="Each item includes a set of order actions, which will be applied to the same base subscription.")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["category", "customFields", "description", "existingAccountNumber", "externallyManagedBy", "newAccount", "orderDate", "orderLineItems", "orderNumber", "processingOptions", "reasonCode", "schedulingOptions", "status", "subscriptions"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of CreateOrderRequest from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of new_account
        if self.new_account:
            _dict['newAccount'] = self.new_account.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in order_line_items (list)
        _items = []
        if self.order_line_items:
            for _item_order_line_items in self.order_line_items:
                if _item_order_line_items:
                    _items.append(_item_order_line_items.to_dict())
            _dict['orderLineItems'] = _items
        # override the default output from pydantic by calling `to_dict()` of processing_options
        if self.processing_options:
            _dict['processingOptions'] = self.processing_options.to_dict()
        # override the default output from pydantic by calling `to_dict()` of scheduling_options
        if self.scheduling_options:
            _dict['schedulingOptions'] = self.scheduling_options.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in subscriptions (list)
        _items = []
        if self.subscriptions:
            for _item_subscriptions in self.subscriptions:
                if _item_subscriptions:
                    _items.append(_item_subscriptions.to_dict())
            _dict['subscriptions'] = _items
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of CreateOrderRequest from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        obj = convert_snake_dict_to_camel(obj, cls.model_fields, cls.__properties)

        _obj = cls.model_validate(cls.to_alias_dict(obj))
        return cls.update_additional_properties(_obj, obj)

    @classmethod
    def update_additional_properties(cls, obj, _dict: Optional[Dict[str, Any]]):
        # store additional fields in additional_properties

        # store additional fields in additional_properties
        for _key in _dict.keys():
            if _key not in cls.__properties:
                obj.additional_properties[_key] = _dict.get(_key)


        return obj
        pass

    @classmethod
    def to_alias_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        return {
            "category": obj.get("category") if obj.get("category") is not None else OrderCategory.NEWSALES,
            "customFields": obj.get("customFields"),
            "description": obj.get("description"),
            "existingAccountNumber": obj.get("existingAccountNumber"),
            "externallyManagedBy": obj.get("externallyManagedBy"),
            "newAccount": OrderCreateAccount.from_dict(obj["newAccount"]) if obj.get("newAccount") is not None else None,
            "orderDate": obj.get("orderDate"),
            "orderLineItems": [CreateOrderOrderLineItem.from_dict(_item) for _item in obj["orderLineItems"]] if obj.get("orderLineItems") is not None else None,
            "orderNumber": obj.get("orderNumber"),
            "processingOptions": ProcessingOptionsWithDelayedCapturePayment.from_dict(obj["processingOptions"]) if obj.get("processingOptions") is not None else None,
            "reasonCode": obj.get("reasonCode"),
            "schedulingOptions": OrderSchedulingOptions.from_dict(obj["schedulingOptions"]) if obj.get("schedulingOptions") is not None else None,
            "status": obj.get("status"),
            "subscriptions": [CreateOrderSubscription.from_dict(_item) for _item in obj["subscriptions"]] if obj.get("subscriptions") is not None else None
        }
        return _obj


def convert_snake_dict_to_camel(_dict: dict, model_fields, properties):
    if not isinstance(_dict, dict):
        return _dict
    new_dict = {}
    for k, v in _dict.items():
        if k in model_fields:
            # model_fields: key is attribute name like bill_to_contact,
            alias = model_fields.get(k).alias or k
            new_dict[alias] = v
            pass
        else:
            new_key = snake_to_camel(k)
            if properties is not None and isinstance(properties, list) and new_key in properties:
                new_dict[new_key] = v
            else:
                new_dict[k] = v
    return new_dict
    pass


def snake_to_camel(name):
    if name is None or '_' not in name:
        return name
    components = name.split('_')
    return components[0] + ''.join(x.title() for x in components[1:])
