$ErrorActionPreference = "Stop"

$Root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$CaseWorkbook = Join-Path $Root "测试用例\SaaS_E2E测试用例_单Sheet用例测试列表.xlsx"
$FlowWorkbook = Join-Path $Root "测试用例\订单状态流转_链路流程线整理.xlsx"
$BackupDir = Join-Path $Root "runtime\excel_backups"
$Stamp = Get-Date -Format "yyyyMMdd-HHmmss"
New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
Copy-Item -LiteralPath $CaseWorkbook -Destination (Join-Path $BackupDir "SaaS_E2E测试用例_单Sheet用例测试列表.before_flow21_22_assigned_com_$Stamp.xlsx") -Force
Copy-Item -LiteralPath $FlowWorkbook -Destination (Join-Path $BackupDir "订单状态流转_链路流程线整理.before_flow21_22_assigned_com_$Stamp.xlsx") -Force

function Get-HeaderMap($ws) {
    $map = @{}
    $lastCol = $ws.UsedRange.Columns.Count
    for ($col = 1; $col -le $lastCol; $col++) {
        $name = [string]$ws.Cells.Item(1, $col).Text
        if (-not [string]::IsNullOrWhiteSpace($name)) {
            $map[$name.Trim()] = $col
        }
    }
    return $map
}

function Find-Row($ws, $headerName, $value) {
    $headers = Get-HeaderMap $ws
    $col = $headers[$headerName]
    if (-not $col) { throw "Header not found: $headerName" }
    $lastRow = $ws.UsedRange.Rows.Count
    for ($row = 2; $row -le $lastRow; $row++) {
        if (([string]$ws.Cells.Item($row, $col).Text).Trim() -eq $value) {
            return $row
        }
    }
    return $null
}

function Set-Values($ws, $row, $values) {
    $headers = Get-HeaderMap $ws
    foreach ($key in $values.Keys) {
        if ($headers.ContainsKey($key)) {
            $ws.Cells.Item($row, $headers[$key]).Value2 = $values[$key]
        }
    }
}

function Append-Or-Update-Case($ws, $caseId, $values, $templateCaseId) {
    $row = Find-Row $ws "用例编号" $caseId
    if (-not $row) {
        $templateRow = Find-Row $ws "用例编号" $templateCaseId
        $row = $ws.UsedRange.Rows.Count + 1
        if ($templateRow) {
            $ws.Rows.Item($templateRow).Copy()
            $ws.Rows.Item($row).PasteSpecial(-4122) | Out-Null
            $ws.Application.CutCopyMode = $false
        }
    }
    Set-Values $ws $row $values
    return $row
}

function Delete-Flow-Detail-Rows($ws, $flowId) {
    $headers = Get-HeaderMap $ws
    $flowCol = $headers["链路编号"]
    $lastRow = $ws.UsedRange.Rows.Count
    for ($row = $lastRow; $row -ge 2; $row--) {
        if (([string]$ws.Cells.Item($row, $flowCol).Text).Trim() -eq $flowId) {
            $ws.Rows.Item($row).Delete() | Out-Null
        }
    }
}

function Append-Flow-Detail($ws, $flowId, $step, $caseId, $module, $title, $precondition, $expected) {
    $row = $ws.UsedRange.Rows.Count + 1
    Set-Values $ws $row @{
        "链路编号" = $flowId
        "步骤序号" = [string]$step
        "用例编号" = $caseId
        "所属模块" = $module
        "用例标题" = $title
        "前置条件" = $precondition
        "预期结果" = $expected
    }
}

$S079 = @{
    "用例编号" = "S-FLOW-079"
    "用例层级" = "订单状态流转用例"
    "来源/组合依据" = "whiteboard_exported_image.png + 状态机对应关系梳理.html：【指派单 下游取消订单】"
    "所属模块" = "指派单 下游取消订单"
    "用例标题" = "【丸友集视角】丸友集已接单未发打手 / 丸掌柜主单服务中 / 子单代练中 - 指派打手发单"
    "登录平台/角色账号" = "丸友集：工作室主账号或客服账号；打手：被指派打手子账号；丸掌柜：企业主账号或客服账号。"
    "前置条件" = "丸友集已确认接收上游订单，订单在丸友集工作室履约应用-订单列表中，尚未发给打手；如工作室下没有已启用打手，需先邀请并确认打手成员。"
    "测试数据" = "来源单号、订单标题、丸掌柜主单号、目标打手姓名/手机号、价格模式=百分比发单价、收单价百分比=90、服务时限、联系电话。"
    "执行步骤" = "1. 登录丸友集工作室主账号。`n2. 检查当前工作室下是否存在已启用打手成员。`n3. 如不存在可用打手，进入企业管理-成员管理，邀请成员并选择丸友集产品、打手角色，完成注册/确认后返回丸友集。`n4. 进入工作室履约应用-订单列表。`n5. 按来源单号查询目标订单。`n6. 确认订单为丸友集已接单但未发给打手状态，操作区展示立即发单。`n7. 点击立即发单。`n8. 在发单弹框中选择分配方式为指派打手。`n9. 点击选择打手，按成员名称或手机号查询目标打手。`n10. 勾选目标打手并点击确认选择。`n11. 选择或确认价格模式为百分比发单价，填写收单价百分比90，并确认订单内容、时间要求、联系电话等必填字段。`n12. 点击确认发单。`n13. 回到丸友集订单列表，按来源单号查询目标订单并记录父单状态、当前打手和子单状态。`n14. 登录被指派打手账号，进入打手应用-我的订单，按来源单号确认该订单可见。`n15. 登录丸掌柜账号，进入订单详情记录主单和子单状态。"
    "预期结果" = "1. 丸友集成功将已接单订单以指派打手方式发给目标打手。`n2. 发单弹框回填的打手姓名/手机号与目标打手一致。`n3. 被指派打手侧我的订单可见该订单；指派单不需要再到抢单大厅接单，也不接 S-FLOW-026。`n4. 丸掌柜主单为服务中/代练中等继续履约状态，子单列表展示已发布、已接单、服务中或页面对应发单后状态。"
    "跨端/状态断言" = "1. 指派打手前必须存在该丸友集工作室下的已启用打手；没有则先邀请并确认打手成员。`n2. 只有被指派打手可见或处理该订单，非目标打手不应误接该单。`n3. 指派单发出后直接进入被指派打手我的订单，不需要执行 S-FLOW-026。`n4. 丸友集订单列表、打手我的订单、丸掌柜订单详情中的来源单号、订单标题、打手信息一致。"
    "可组合/被引用关系" = "FLOW-021/FLOW-022 的打手取消指派订单前置；必须接在 S-FLOW-014 后、S-FLOW-037 前；不接 S-FLOW-026。"
    "自动化状态" = "已自动化"
    "备注" = "2026-07-01修正：专门用于指派打手发单；指派单发出后直接进入打手我的订单，FLOW-021/022 中不再接 S-FLOW-026。"
}

$S037Pre = "已执行 S-FLOW-079，丸友集已按指派打手方式发单给目标打手；指派单已直接进入被指派打手的我的订单，不需要再执行 S-FLOW-026 去抢单大厅接单。"
$S037Assertion = "1. 打手取消订单需要工作室审核。`n2. 打手取消订单不同于丸掌柜向下取消订单。`n3. S-FLOW-037 不能单独作为 FLOW-021/FLOW-022 起点，必须承接 S-FLOW-079；指派单不需要再执行 S-FLOW-026。"
$S037Expected = "1. 打手订单状态为取消中。`n2. 丸友集可见取消申请。`n3. 丸掌柜订单状态和子单状态不因打手单独取消而进入已取消终态。"
$S037Updates = @{
    "所属模块" = "指派单 下游取消订单"
    "前置条件" = $S037Pre
    "跨端/状态断言" = $S037Assertion
    "备注" = "2026-07-01修正：FLOW-021/022 中 S-FLOW-037 前只承接 S-FLOW-079 指派发单；指派单不接 S-FLOW-026。"
}

$Flow021Seq = "S-FLOW-007 -> S-FLOW-014 -> S-FLOW-079 -> S-FLOW-037 -> S-FLOW-038"
$Flow022Seq = "S-FLOW-007 -> S-FLOW-014 -> S-FLOW-079 -> S-FLOW-037 -> S-FLOW-039 -> S-FLOW-032"
$Flow021Chain = "S-FLOW-007(创建主单已推单) -> S-FLOW-014(丸友集确认接单) -> S-FLOW-079(丸友集指派打手发单；无打手则先邀请打手) -> S-FLOW-037(打手代练中状态发起取消订单) -> S-FLOW-038(打手取消中状态-丸友集拒绝取消)"
$Flow022Chain = "S-FLOW-007(创建主单已推单) -> S-FLOW-014(丸友集确认接单) -> S-FLOW-079(丸友集指派打手发单；无打手则先邀请打手) -> S-FLOW-037(打手代练中状态发起取消订单) -> S-FLOW-039(打手取消中状态-丸友集同意取消) -> S-FLOW-032(前一子单已撤销/已取消状态-续发下一子单)"
$FlowStart = "丸掌柜已创建主单并推给丸友集；丸友集已确认接单；丸友集已指派打手发单；指派单已进入被指派打手我的订单；打手提交取消订单后进入取消中。"

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
try {
    $caseWb = $excel.Workbooks.Open($CaseWorkbook)
    $caseWs = $caseWb.Worksheets.Item("订单状态流转")
    $row079 = Append-Or-Update-Case $caseWs "S-FLOW-079" $S079 "S-FLOW-037"
    $row037 = Find-Row $caseWs "用例编号" "S-FLOW-037"
    if ($row037) { Set-Values $caseWs $row037 $S037Updates }
    $caseWs.Columns.AutoFit() | Out-Null
    $caseWb.Save()
    $caseWb.Close($true)

    $flowWb = $excel.Workbooks.Open($FlowWorkbook)
    $flowWs = $flowWb.Worksheets.Item("链路流程线")
    $detailWs = $flowWb.Worksheets.Item("链路步骤明细")
    $coverageWs = $flowWb.Worksheets.Item("用例覆盖索引")
    $rawWs = $flowWb.Worksheets.Item("原始用例索引")

    Set-Values $flowWs (Find-Row $flowWs "链路编号" "FLOW-021") @{
        "起点状态" = $FlowStart
        "终点状态" = "打手取消中；丸友集拒绝取消后回到代练中"
        "用例编号序列" = $Flow021Seq
        "用例链路（编号+标题）" = $Flow021Chain
        "注意事项/缺口" = "S-FLOW-037 前必须先执行 S-FLOW-079 指派打手发单；指派单直接进入打手我的订单，不接 S-FLOW-026。"
    }
    Set-Values $flowWs (Find-Row $flowWs "链路编号" "FLOW-022") @{
        "起点状态" = $FlowStart
        "终点状态" = "旧指派子单已取消；下一子单待接单/已发单/代练中"
        "用例编号序列" = $Flow022Seq
        "用例链路（编号+标题）" = $Flow022Chain
        "注意事项/缺口" = "S-FLOW-037 前必须先执行 S-FLOW-079 指派打手发单；指派单直接进入打手我的订单，不接 S-FLOW-026；同意取消后需校验旧子单与新子单互不覆盖。"
    }

    Delete-Flow-Detail-Rows $detailWs "FLOW-021"
    Delete-Flow-Detail-Rows $detailWs "FLOW-022"
    Append-Flow-Detail $detailWs "FLOW-021" 1 "S-FLOW-007" "上游发单" "【丸掌柜】主单待接单状态/子单待接单-已推单状态-创建主单已推单" "" ""
    Append-Flow-Detail $detailWs "FLOW-021" 2 "S-FLOW-014" "上游发单" "丸友集抢单大厅待接单阶段-丸友集确认接单" "" ""
    Append-Flow-Detail $detailWs "FLOW-021" 3 "S-FLOW-079" $S079["所属模块"] $S079["用例标题"] $S079["前置条件"] $S079["预期结果"]
    Append-Flow-Detail $detailWs "FLOW-021" 4 "S-FLOW-037" "指派单 下游取消订单" "打手代练中状态发起取消订单" $S037Pre $S037Expected
    Append-Flow-Detail $detailWs "FLOW-021" 5 "S-FLOW-038" "指派单 下游取消订单" "打手取消中状态-丸友集拒绝取消" "打手已提交取消订单申请，丸友集待审核。" "丸友集拒绝取消后，打手侧和丸友集侧订单恢复代练中/服务中。"
    Append-Flow-Detail $detailWs "FLOW-022" 1 "S-FLOW-007" "上游发单" "【丸掌柜】主单待接单状态/子单待接单-已推单状态-创建主单已推单" "" ""
    Append-Flow-Detail $detailWs "FLOW-022" 2 "S-FLOW-014" "上游发单" "丸友集抢单大厅待接单阶段-丸友集确认接单" "" ""
    Append-Flow-Detail $detailWs "FLOW-022" 3 "S-FLOW-079" $S079["所属模块"] $S079["用例标题"] $S079["前置条件"] $S079["预期结果"]
    Append-Flow-Detail $detailWs "FLOW-022" 4 "S-FLOW-037" "指派单 下游取消订单" "打手代练中状态发起取消订单" $S037Pre $S037Expected
    Append-Flow-Detail $detailWs "FLOW-022" 5 "S-FLOW-039" "指派单 下游取消订单" "打手取消中状态-丸友集同意取消" "打手已提交取消订单申请，丸友集待审核。" "丸友集同意取消后，旧指派子单进入已取消/撤销完成等终态。"
    Append-Flow-Detail $detailWs "FLOW-022" 6 "S-FLOW-032" "多子单履约" "前一子单已撤销/已取消状态-续发下一子单" "第一子单已发起撤销或取消并审批通过，状态进入已取消、已撤销或页面展示的终态。" "新子单创建成功，新旧子单状态互不覆盖。"

    Append-Or-Update-Case $coverageWs "S-FLOW-079" @{
        "用例编号" = "S-FLOW-079"
        "所属模块" = $S079["所属模块"]
        "用例标题" = $S079["用例标题"]
        "覆盖次数" = "2"
        "出现链路" = "FLOW-021, FLOW-022"
        "是否已覆盖" = "是"
        "备注" = "指派打手发单前置；指派单不接 S-FLOW-026。"
    } "S-FLOW-037" | Out-Null
    Append-Or-Update-Case $rawWs "S-FLOW-079" @{
        "用例编号" = "S-FLOW-079"
        "所属模块" = $S079["所属模块"]
        "用例标题" = $S079["用例标题"]
        "前置条件" = $S079["前置条件"]
        "预期结果" = $S079["预期结果"]
        "执行步骤" = $S079["执行步骤"]
    } "S-FLOW-037" | Out-Null

    $flowWs.Columns.AutoFit() | Out-Null
    $detailWs.Columns.AutoFit() | Out-Null
    $coverageWs.Columns.AutoFit() | Out-Null
    $rawWs.Columns.AutoFit() | Out-Null
    $flowWb.Save()
    $flowWb.Close($true)
}
finally {
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}

Write-Output "updated FLOW-021/FLOW-022 assigned-order Excel text; backup stamp=$Stamp"

