from __future__ import annotations

import json
from pathlib import Path

from openpyxl import load_workbook


ROOT = Path(__file__).resolve().parents[1]

FLOW011_SEQUENCE = "S-FLOW-007 -> S-FLOW-014 -> S-FLOW-018 -> S-FLOW-020"
FLOW011_CHAIN = (
    "S-FLOW-007(【丸掌柜】主单待接单状态/子单待接单-已推单状态-创建主单已推单) -> "
    "S-FLOW-014(丸友集抢单大厅待接单阶段-丸友集确认接单) -> "
    "S-FLOW-018(丸友集已接单/未发单到打手抢单大厅阶段&&丸掌柜主单服务中状态/子单代练中状态-丸掌柜主单发起售后) -> "
    "S-FLOW-020(丸友集已接单/未发单到打手抢单大厅阶段&&丸掌柜主单售后中状态-丸掌柜取消主单售后；"
    "实际平台回读丸掌柜主单恢复代练中，丸友集父单为异常中-待售后，不可继续立即发单)"
)

S_FLOW_020_TITLE = "丸友集已接单/未发单到打手抢单大厅阶段&&丸掌柜主单服务中状态/子单代练中状态-丸掌柜主单取消售后"
S_FLOW_020_PRECONDITION = "已执行 S-FLOW-018，丸掌柜已在丸友集已接单但未发单给打手阶段发起主单售后，当前订单为售后中且未处理完成。"
S_FLOW_020_STEPS = (
    "1. 登录丸掌柜账号。\n"
    "2. 进入订单管理或售后详情，按来源单号或主单号查询目标订单。\n"
    "3. 记录取消前丸掌柜订单状态为售后中、子单列表目标子单订单状态为售后中或页面对应状态。\n"
    "4. 点击取消售后。\n"
    "5. 填写取消原因并确认。\n"
    "6. 在丸掌柜订单管理页面，按来源单号或订单标题查询目标订单。\n"
    "7. 点击主单号进入订单详情，记录丸掌柜主单状态、子单汇总状态和子单列表状态。\n"
    "8. 登录丸友集账号，进入工作室履约应用-订单列表。\n"
    "9. 按来源单号或丸掌柜主单号作为上游单号查询目标订单。\n"
    "10. 记录丸友集父单状态和操作列，不继续点击立即发单。"
)
S_FLOW_020_EXPECTED = (
    "1. 丸掌柜订单取消售后成功，售后信息不再展示为售后中。\n"
    "2. 丸掌柜主单实际回读为代练中或服务中，子单列表目标子单实际回读为代练中/服务中或页面展示的异常中状态。\n"
    "3. 丸友集父单实际回读为异常中-待售后或页面对应异常待处理状态。\n"
    "4. 丸友集操作列不展示立即发单，本用例在 S-FLOW-020 收尾，不再承接 S-FLOW-021。"
)
S_FLOW_020_ASSERTION = (
    "1. 以实际平台回读为准：丸掌柜侧取消售后后恢复代练中/服务中；丸友集侧为异常中-待售后。\n"
    "2. 取消售后后不能残留售后中作为当前状态。\n"
    "3. 该状态不可直接继续立即发单，FLOW-011 不再连接 S-FLOW-021。"
)


def update_flow_workbook(path: Path) -> None:
    wb = load_workbook(path)
    if "链路流程线" in wb.sheetnames:
        ws = wb["链路流程线"]
        for row in ws.iter_rows(min_row=2):
            if row[0].value == "FLOW-011":
                row[1].value = "丸友集已接单未发打手-主单发起售后-取消售后-异常中待售后收尾"
                row[2].value = "已接单未发打手主单售后取消后异常待处理"
                row[4].value = "丸掌柜主单代练中；丸友集父单异常中-待售后；不再继续立即发单"
                row[5].value = FLOW011_SEQUENCE
                row[6].value = FLOW011_CHAIN
                row[8].value = "验证工作室接单但未发打手阶段，丸掌柜发起主单售后后取消售后，按实际平台回读在丸友集侧进入异常中-待售后。"
                row[9].value = "该链路到 S-FLOW-020 收尾；若要验证立即发单，需要重新准备已接单且操作列存在立即发单的数据。"
                row[10].value = "2026-06-24 实测：S-FLOW-020 后丸友集侧为异常中-待售后，无立即发单入口，因此 FLOW-011 不再连接 S-FLOW-021。"
    if "链路步骤明细" in wb.sheetnames:
        ws = wb["链路步骤明细"]
        for row in ws.iter_rows(min_row=2):
            flow_id = row[0].value
            step_no = row[1].value
            case_id = row[2].value
            if flow_id == "FLOW-011" and case_id == "S-FLOW-020":
                row[4].value = S_FLOW_020_TITLE
                row[5].value = S_FLOW_020_PRECONDITION
                row[6].value = S_FLOW_020_EXPECTED
            elif flow_id == "FLOW-011" and step_no == 5:
                for cell in row:
                    cell.value = None
    if "用例覆盖索引" in wb.sheetnames:
        ws = wb["用例覆盖索引"]
        for row in ws.iter_rows(min_row=2):
            if row[0].value == "S-FLOW-020":
                row[2].value = S_FLOW_020_TITLE
                row[4].value = "FLOW-011"
                row[6].value = "2026-06-24 实测：取消主单售后后丸友集侧为异常中-待售后，不再连接 S-FLOW-021。"
            elif row[0].value == "S-FLOW-021" and isinstance(row[4].value, str):
                row[4].value = remove_flow_id(row[4].value, "FLOW-011")
    if "原始用例索引" in wb.sheetnames:
        ws = wb["原始用例索引"]
        for row in ws.iter_rows(min_row=2):
            if row[0].value == "S-FLOW-020":
                row[2].value = S_FLOW_020_TITLE
                row[3].value = S_FLOW_020_PRECONDITION
                row[4].value = S_FLOW_020_EXPECTED
                row[5].value = S_FLOW_020_STEPS
    wb.save(path)


def update_case_workbook(path: Path) -> None:
    wb = load_workbook(path)
    if "订单状态流转" in wb.sheetnames:
        ws = wb["订单状态流转"]
        for row in ws.iter_rows(min_row=2):
            if row[0].value == "S-FLOW-020":
                row[3].value = S_FLOW_020_TITLE
                row[5].value = S_FLOW_020_PRECONDITION
                row[7].value = S_FLOW_020_STEPS
                row[8].value = S_FLOW_020_EXPECTED
                row[9].value = S_FLOW_020_ASSERTION
                row[10].value = "订单状态流转分支库；FLOW-011 在 S-FLOW-020 收尾，不再承接 S-FLOW-021。"
            elif row[0].value == "S-FLOW-021" and isinstance(row[10].value, str):
                row[10].value = remove_flow_id(row[10].value, "FLOW-011")
    wb.save(path)


def update_json_file(path: Path) -> None:
    if not path.exists():
        return
    data = json.loads(path.read_text(encoding="utf-8-sig"))
    changed = False
    if isinstance(data, list):
        for item in data:
            if not isinstance(item, dict):
                continue
            if item.get("用例编号") == "S-FLOW-020":
                item["用例标题"] = S_FLOW_020_TITLE
                item["前置条件"] = S_FLOW_020_PRECONDITION
                item["执行步骤"] = S_FLOW_020_STEPS
                item["预期结果"] = S_FLOW_020_EXPECTED
                item["跨端/状态断言"] = S_FLOW_020_ASSERTION
                changed = True
            if item.get("用例编号") == "S-FLOW-021":
                for key, value in list(item.items()):
                    if isinstance(value, str) and "FLOW-011" in value:
                        item[key] = remove_flow_id(value, "FLOW-011")
                        changed = True
    if changed:
        path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def update_ledger() -> None:
    path = ROOT / "runtime/e2e_accounts.json"
    if not path.exists():
        return
    data = json.loads(path.read_text(encoding="utf-8-sig"))
    for item in data.get("dispatched_orders", []):
        if item.get("source_order_no") != "E2EORDER0624215221":
            continue
        item["status"] = "wanyouji_abnormal_pending_after_main_aftersale_cancelled"
        item["current_flow_state"] = "wanyouji_abnormal_pending_after_main_aftersale_cancelled_without_player"
        item["available_for_cases"] = []
        item["wanzhanggui_main_status"] = "代练中"
        item["wanzhanggui_sub_order_status"] = "代练中/异常中"
        item["wanyouji_parent_status"] = "异常中-待售后"
        item["wanyouji_visibility"] = "workshop_order_list_visible_but_not_dispatchable"
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def remove_flow_id(value: str, flow_id: str) -> str:
    parts = [part.strip(" 、,，") for part in value.replace("，", "、").split("、")]
    filtered = [part for part in parts if part and part != flow_id]
    if len(filtered) != len(parts):
        return "、".join(filtered)
    return value.replace(f"{flow_id}、", "").replace(f"、{flow_id}", "").replace(flow_id, "").strip("、,， ")


def main() -> None:
    update_flow_workbook(ROOT / "订单状态流转_链路流程线整理.xlsx")
    update_case_workbook(ROOT / "SaaS_E2E测试用例_单Sheet用例测试列表.xlsx")
    for name in [
        "runtime/order_status_flow_cases_for_sheet.json",
        "runtime/s_flow_expected_status_audit.json",
    ]:
        update_json_file(ROOT / name)
    update_ledger()


if __name__ == "__main__":
    main()
