# -*- coding: utf-8 -*-
"""
分录增删改 + 字段联动计算示例
适用插件：Form/Bill
依赖 API：this.Model, this.View
相关检查：循环内推荐避免调用 updateView，循环结束后统一刷新
"""

def add_entry_row(this, entryKey):
    # 新增分录行
    rowIndex = this.Model.CreateNewEntryRow(entryKey)
    # 设置默认值
    this.Model.SetValue("FQty", 0, rowIndex)
    this.Model.SetValue("FPrice", 0, rowIndex)
    return rowIndex

def delete_entry_row(this, entryKey, rowIndex):
    # 删除分录行
    this.Model.DeleteEntryRow(entryKey, rowIndex)

def calculate_entry_amount(this, e):
    # 分录字段联动：数量 * 单价 = 金额
    entryKey = "FPOOrderEntry"

    if e.Property.Name == "FQty" or e.Property.Name == "FPrice":
        qty = to_decimal(this.Model.GetValue("FQty", e.Row))
        price = to_decimal(this.Model.GetValue("FPrice", e.Row))
        this.Model.SetValue("FAmount", qty * price, e.Row)

def calculate_header_total(this, entryKey):
    # 汇总分录金额到表头
    entryRows = this.View.Model.DataObject[entryKey]
    totalAmount = 0
    if entryRows is not None:
        for row in entryRows:
            totalAmount += to_decimal(row["FAmount"])

    this.Model.SetValue("FTotalAmount", totalAmount)
    # 循环结束后统一刷新
    this.View.UpdateView("FTotalAmount")

def to_decimal(value):
    """安全转换为 decimal"""
    if value is None:
        return 0
    return Convert.ToDecimal(value)
