# -*- coding: utf-8 -*-
"""
DynamicObject 取值/赋值/分录遍历示例
适用插件：Form/Operation
依赖 API：DynamicObject, DynamicObjectCollection, BusinessDataServiceHelper
相关检查：推荐对嵌套访问进行判空，基础资料赋值建议同时设置 ID 和对象
"""

def demonstrate_dynamic_object(this):
    # 表单插件中获取当前单据数据包
    billObj = this.View.Model.DataObject

    # 表头取值
    billNo = billObj["BillNo"]  # PropertyName from meta
    billId = billObj["id"]

    # 基础资料字段取值（返回 DynamicObject）
    supplier = billObj["supplier"]
    if supplier is not None:
        supplierName = supplier["Name"]
        supplierId = supplier["Id"]

    # 分录遍历
    entryRows = billObj["POOrderEntry"]
    if entryRows is not None:
        for row in entryRows:
            entryId = row["id"]
            qty = row["Qty"]  # PropertyName from meta (not Key FQty)
            materialId = row["MaterialId_Id"]  # 基础资料 ID 字段通常以 _Id 结尾

            # 分录基础资料取值
            material = row["MaterialId"]
            if material is not None:
                materialNumber = material["Number"]

    # 基础资料赋值（同时设 ID 和对象）
    field = this.View.BillBusinessInfo.GetField("FMaterialId")
    material = BusinessDataServiceHelper.LoadSingle(this.Context, materialId, field.RefFormDynamicObjectType)
    row["MaterialId_Id"] = materialId
    row["MaterialId"] = material

    # 刷新视图（只刷新必要区域）
    this.View.UpdateView("FMaterialId")
