from __future__ import annotations

from datetime import datetime
from pathlib import Path

from openpyxl import load_workbook


FLOW_XLSX = Path("测试用例/订单状态流转_链路流程线整理.xlsx")

TITLE = "【丸友集】已完成/撤销完成子单-选择处罚追缴类型并创建追缴/处罚单"
PRECONDITION = "丸友集工作室履约应用-订单列表存在子单状态为已完成或撤销完成的订单；目标子单操作列展示【处罚追缴】入口。"
EXPECTED = (
    "1. 点击【处罚追缴】后弹框正常打开。\n"
    "2. FLOW-013 中选择【追缴单】，填写追缴原因、追缴内容、追缴金额等必填信息并确认创建。\n"
    "3. FLOW-014 中选择【处罚单】，填写处罚原因、处罚金额等必填信息并确认创建。\n"
    "4. 创建成功后台账分别流转到 S-FLOW-073 或 S-FLOW-074。"
)


def headers(ws) -> dict[str, int]:
    return {str(cell.value).strip(): cell.column for cell in ws[1] if cell.value}


def update_case_rows(ws) -> None:
    h = headers(ws)
    for row in range(2, ws.max_row + 1):
        if str(ws.cell(row, h.get("用例编号", 3)).value or "").strip() == "S-FLOW-072":
            ws.cell(row, h["用例标题"]).value = TITLE
            if "前置条件" in h:
                ws.cell(row, h["前置条件"]).value = PRECONDITION
            if "预期结果" in h:
                ws.cell(row, h["预期结果"]).value = EXPECTED


def update_coverage(ws) -> None:
    h = headers(ws)
    for row in range(2, ws.max_row + 1):
        if str(ws.cell(row, h["用例编号"]).value or "").strip() == "S-FLOW-072":
            ws.cell(row, h["用例标题"]).value = TITLE
            ws.cell(row, h["备注"]).value = "承接 S-FLOW-078 产出的撤销完成子单；在本用例内选择追缴单/处罚单并提交创建，后接 073/074。"


def update_summary(ws) -> None:
    h = headers(ws)
    for row in range(2, ws.max_row + 1):
        flow_id = str(ws.cell(row, h["链路编号"]).value or "").strip()
        if flow_id == "FLOW-013":
            ws.cell(row, h["用例链路（编号+标题）"]).value = (
                "S-FLOW-007(创建主单已推单) -> S-FLOW-014(丸友集确认接单) -> "
                "S-FLOW-021(丸友集立即发单到打手) -> S-FLOW-026(打手立即抢单进入代练中) -> "
                "S-FLOW-078(丸友集订单列表代练中子单-撤销子单并进入撤销完成) -> "
                "S-FLOW-072(选择追缴单并确认创建) -> S-FLOW-073(打手完成追缴)"
            )
        elif flow_id == "FLOW-014":
            ws.cell(row, h["用例链路（编号+标题）"]).value = (
                "S-FLOW-007(创建主单已推单) -> S-FLOW-014(丸友集确认接单) -> "
                "S-FLOW-021(丸友集立即发单到打手) -> S-FLOW-026(打手立即抢单进入代练中) -> "
                "S-FLOW-078(丸友集订单列表代练中子单-撤销子单并进入撤销完成) -> "
                "S-FLOW-072(选择处罚单并确认创建) -> S-FLOW-074(打手侧查看处罚金额)"
            )


def main() -> None:
    wb = load_workbook(FLOW_XLSX)
    update_summary(wb["链路流程线"])
    update_case_rows(wb["链路步骤明细"])
    update_coverage(wb["用例覆盖索引"])
    if "原始用例索引" in wb.sheetnames:
        update_case_rows(wb["原始用例索引"])
    wb["说明"].append(["更新记录", f"{datetime.now():%Y-%m-%d %H:%M:%S} S-FLOW-072 改为选择追缴单/处罚单并确认创建，不再只打开入口。"])
    wb.save(FLOW_XLSX)
    print(f"updated {FLOW_XLSX}")


if __name__ == "__main__":
    main()
