use axum::{
    extract::State,
    http::Method,
    response::sse::{Event, Sse},
    routing::post,
    Json, Router,
};
use futures::stream::Stream;
use serde::{Deserialize, Serialize};
use std::convert::Infallible;
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;
use tokio_stream::StreamExt;
use tower_http::cors::{Any, CorsLayer};
use crate::*;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcRequest {
    pub cmd: String,
    pub args: serde_json::Value,
    pub username: String,
    pub real_name: String,
}

#[derive(Serialize)]
pub struct RpcResponse {
    pub ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl RpcResponse {
    fn ok(data: serde_json::Value) -> Self { RpcResponse { ok: true, data: Some(data), error: None } }
    fn err(e: String) -> Self { RpcResponse { ok: false, data: None, error: Some(e) } }
}

type AppState = Arc<broadcast::Sender<String>>;

pub async fn start_server(port: u16) {
    let cors = CorsLayer::new().allow_methods([Method::POST, Method::GET]).allow_origin(Any).allow_headers(Any);
    let (tx, _rx) = broadcast::channel::<String>(32);
    let state = Arc::new(tx);

    let app = Router::new()
        .route("/rpc", post(handle_rpc))
        .route("/ping", post(|| async { Json(serde_json::json!({"ok": true})) }))
        .route("/events", axum::routing::get(sse_handler))
        .layer(cors)
        .with_state(state.clone());

    let addr = format!("0.0.0.0:{}", port);

    // 闇茶劊椹磋劮鍗ょ鑴綍鑴剻鑴㈠崵鑴宠劖闇茬倝鑴㈣劌璺劀
    let listener = loop {
        match tokio::net::TcpListener::bind(&addr).await {
            Ok(listener) => break listener,
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
            println!("[Server] Port {} in use, releasing...", port);
                kill_process_on_port(port);
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            }
            Err(e) => {
                panic!("[Server] 鑴﹁劶璺瘬鎺宠锤闇茬瘬闇茶劊椹磋劮 {}: {}", port, e);
            }
        }
    };

    println!("      [OK] HTTP server started");
    println!();
    println!("===================================");
    println!("  Server Info");
    println!("===================================");
    println!("  Port:       {}", port);
    println!("  Local:      http://127.0.0.1:{}", port);
    println!();
    println!("  Other PCs: use this machine IP + port 9520 to connect");
    // Get and display local IP addresses
    #[cfg(target_os = "windows")]
    {
        let output = std::process::Command::new("ipconfig").output().ok();
        if let Some(out) = output {
            let stdout = String::from_utf8_lossy(&out.stdout);
            for line in stdout.lines() {
                let trimmed = line.trim();
                if trimmed.contains("IPv4") || trimmed.contains("IP Address") {
                    if let Some(ip) = trimmed.split(':').nth(1).or_else(|| trimmed.split(' ').last()) {
                        let ip = ip.trim();
                        if !ip.is_empty() && ip != "127.0.0.1" {
                            println!("  -> IP: {}    Port: {}", ip, port);
                        }
                    }
                }
            }
        }
    }
    #[cfg(not(target_os = "windows"))]
    {
        let output = std::process::Command::new("hostname").arg("-I").output().ok();
        if let Some(out) = output {
            let stdout = String::from_utf8_lossy(&out.stdout);
            for ip in stdout.split_whitespace() {
                if !ip.is_empty() && ip != "127.0.0.1" {
                    println!("  -> IP: {}    Port: {}", ip, port);
                }
            }
        }
    }
    println!();
    println!("  Press Ctrl+C to stop");
    println!("===================================");
    println!();

    axum::serve(listener, app).await.unwrap();
}

/// Kill process occupying the given port (cross-platform)
fn kill_process_on_port(port: u16) {
    #[cfg(target_os = "windows")]
    {
        let output = std::process::Command::new("cmd")
            .args(["/C", &format!("netstat -ano | findstr :{}", port)])
            .output()
            .ok();
        if let Some(out) = output {
            let stdout = String::from_utf8_lossy(&out.stdout);
            for line in stdout.lines() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if let Some(pid_str) = parts.last() {
                    if std::process::Command::new("taskkill")
                        .args(["/F", "/PID", pid_str])
                        .output()
                        .is_ok()
                    {
                        println!("[Server] Killed process PID: {}", pid_str);
                    }
                }
            }
        }
    }
    #[cfg(not(target_os = "windows"))]
    {
        // Linux/macOS: use fuser to kill process on port
        let _ = std::process::Command::new("fuser")
            .args(["-k", &format!("{}/tcp", port)])
            .output();
    }
}
// SSE endpoint: clients subscribe to real-time events
async fn sse_handler(State(tx): State<AppState>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
    let rx = tx.subscribe();
    let stream = BroadcastStream::new(rx).filter_map(|msg| match msg {
        Ok(data) => Some(Ok(Event::default().data(data))),
        Err(_) => None,
    });
    Sse::new(stream).keep_alive(axum::response::sse::KeepAlive::new())
}

/// 鑴ㄧ尗鑴檵鑴ョ瘬鑴伴檵鑴濈洸鑴ｆ病椹磋劌绂勬悅闇茶劊纰岃剾鑴ㄩ簱鑴犳瘺铏忚劦鑴虫鑴欑湁鑴曞嵂
const WRITE_COMMANDS: &[&str] = &[
    "add_user", "delete_user", "change_password", "admin_reset_password",
    "add_product", "update_product", "delete_product", "batch_add_products", "batch_delete_products",
    "update_product_image", "add_product_spec", "update_product_spec", "delete_product_spec",
    "add_customer", "update_customer", "delete_customer",
    "add_supplier", "update_supplier", "delete_supplier",
    "create_sale_order", "batch_create_sale_orders", "update_sale_order_status", "delete_sale_order", "toggle_sale_invoice", "update_sale_order_remark",
    "create_purchase_order", "update_purchase_order_status", "delete_purchase_order", "toggle_purchase_invoice", "update_purchase_order_remark",
    "adjust_inventory",
    "add_warehouse", "update_warehouse", "delete_warehouse",
    "add_location", "update_location", "delete_location",
    "set_system_config", "create_billing", "update_billing", "update_billing_payment", "delete_billing", "auto_create_billing", "add_payment_record", "delete_payment_record", "create_transfer_order", "delete_transfer_order", "create_return_order", "delete_return_order", "create_assembly_record", "delete_assembly_record", "add_invoice", "delete_invoice", "add_product_package", "delete_product_package", "backup_database", "restore_database",
    "add_category", "delete_category",
    "stock_in", "stock_out", "stock_count", "batch_stock_in", "batch_stock_out",
    "add_print_template", "update_print_template", "delete_print_template", "set_default_print_template",
    "create_billing", "update_billing", "delete_billing",
    "create_transfer_order", "delete_transfer_order",
    "add_product_package", "delete_product_package",
    "create_assembly_record", "delete_assembly_record",
    "import_products", "import_customers", "import_suppliers",
    "add_invoice", "delete_invoice",
    "create_return_order", "delete_return_order",
    "add_payment_record", "delete_payment_record",
    "backup_database", "restore_database",
    "add_operation_log", "clear_operation_logs",
    "set_role_permission",
];

async fn handle_rpc(State(tx): State<AppState>, Json(req): Json<RpcRequest>) -> Json<RpcResponse> {
    let is_write = WRITE_COMMANDS.contains(&req.cmd.as_str());

    let result = (|| -> Result<serde_json::Value, String> {
        let a = &req.args;
        let s = |k: &str| -> String { a[k].as_str().unwrap_or("").to_string() };
        let o = |k: &str| -> serde_json::Value { a[k].clone() };

        let opt_s = |k: &str| -> Option<String> {
            a.get(k).and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(|s| s.to_string())
        };

        macro_rules! rpc_call {
            ($fn:path) => { serde_json::to_value($fn().map_err(|e| e.to_string())?).map_err(|e| e.to_string())? };
            ($fn:path, $($arg:expr),+) => { serde_json::to_value($fn($($arg),+).map_err(|e| e.to_string())?).map_err(|e| e.to_string())? };
        }
        macro_rules! from_val {
            ($v:expr) => { serde_json::from_value($v).map_err(|e: serde_json::Error| e.to_string())? };
        }

        let json: serde_json::Value = match req.cmd.as_str() {
            "ping" => serde_json::json!({"ok": true}),

            // auth
            "login" => rpc_call!(auth::login, from_val!(o("request"))),
            "get_users" => rpc_call!(auth::get_users, req.username.clone()),
            "add_user" => rpc_call!(auth::add_user, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_user" => rpc_call!(auth::delete_user, s("userId"), req.username.clone(), req.real_name.clone()),
            "change_password" => rpc_call!(auth::change_password, s("userId"), s("oldPassword"), s("newPassword"), req.username.clone(), req.real_name.clone()),
            "admin_reset_password" => rpc_call!(auth::admin_reset_password, s("targetUserId"), s("newPassword"), req.username.clone(), req.real_name.clone()),
            "get_accounts" => rpc_call!(auth::get_accounts),

            // products
            "get_products" => rpc_call!(products::get_products, req.username.clone()),
            "add_product" => rpc_call!(products::add_product, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "update_product" => rpc_call!(products::update_product, from_val!(o("product")), req.username.clone(), req.real_name.clone()),
            "delete_product" => rpc_call!(products::delete_product, s("productId"), req.username.clone(), req.real_name.clone()),
            "get_or_create_product" => rpc_call!(products::get_or_create_product, s("code"), s("name"), a["price"].as_f64().unwrap_or(0.0), a["cost"].as_f64().unwrap_or(0.0), s("unit")),
            "batch_add_products" => rpc_call!(products::batch_add_products, from_val!(o("products"))),
            "update_product_image" => rpc_call!(products::update_product_image, from_val!(o("request"))),
            "add_product_spec" => rpc_call!(products::add_product_spec, from_val!(o("request"))),
            "get_product_specs" => rpc_call!(products::get_product_specs, s("productId")),
            "delete_product_spec" => rpc_call!(products::delete_product_spec, s("specId")),
            "batch_delete_products" => rpc_call!(products::batch_delete_products, from_val!(o("productIds")), req.username.clone(), req.real_name.clone()),
            "update_product_spec" => rpc_call!(products::update_product_spec, from_val!(o("request"))),

            // customers
            "get_customers" => rpc_call!(customers::get_customers, req.username.clone()),
            "add_customer" => rpc_call!(customers::add_customer, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "update_customer" => rpc_call!(customers::update_customer, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_customer" => rpc_call!(customers::delete_customer, s("customerId"), req.username.clone(), req.real_name.clone()),

            // suppliers
            "get_suppliers" => rpc_call!(suppliers::get_suppliers, req.username.clone()),
            "add_supplier" => rpc_call!(suppliers::add_supplier, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "update_supplier" => rpc_call!(suppliers::update_supplier, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_supplier" => rpc_call!(suppliers::delete_supplier, s("supplierId"), req.username.clone(), req.real_name.clone()),

            // sales
            "get_sale_orders" => rpc_call!(sales::get_sale_orders, req.username.clone()),
            "create_sale_order" => rpc_call!(sales::create_sale_order, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "update_sale_order_status" => rpc_call!(sales::update_sale_order_status, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_sale_order" => rpc_call!(sales::delete_sale_order, s("orderId"), req.username.clone(), req.real_name.clone()),
            "toggle_sale_invoice" => rpc_call!(sales::toggle_sale_invoice, s("orderId"), a["invoiced"].as_bool().unwrap_or(false), req.username.clone()),
            "get_sale_order_items" => rpc_call!(sales::get_sale_order_items, s("orderId")),
            "batch_create_sale_orders" => rpc_call!(sales::batch_create_sale_orders, from_val!(o("requests")), req.username.clone(), req.real_name.clone()),
            "update_sale_order_remark" => rpc_call!(sales::update_sale_order_remark, s("orderId"), s("remark"), req.username.clone(), req.real_name.clone()),

            // purchases
            "get_purchase_orders" => rpc_call!(purchases::get_purchase_orders, req.username.clone()),
            "create_purchase_order" => rpc_call!(purchases::create_purchase_order, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "update_purchase_order_status" => rpc_call!(purchases::update_purchase_order_status, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_purchase_order" => rpc_call!(purchases::delete_purchase_order, s("orderId"), req.username.clone(), req.real_name.clone()),
            "toggle_purchase_invoice" => rpc_call!(purchases::toggle_purchase_invoice, s("orderId"), a["invoiced"].as_bool().unwrap_or(false), req.username.clone()),
            "get_purchase_order_items" => rpc_call!(purchases::get_purchase_order_items, s("orderId")),
            "update_purchase_order_remark" => rpc_call!(purchases::update_purchase_order_remark, s("orderId"), s("remark"), req.username.clone(), req.real_name.clone()),

            // inventory
            "get_inventory" => rpc_call!(inventory::get_inventory),
            "get_inventory_records" => rpc_call!(inventory::get_inventory_records),
            "adjust_inventory" => rpc_call!(inventory::adjust_inventory, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "get_warehouse_stock" => rpc_call!(inventory::get_warehouse_stock),

            // statistics
            "get_statistics" => rpc_call!(statistics::get_statistics),
            "get_statistics_detail" => rpc_call!(statistics::get_statistics_detail),

            // warehouses
            "get_warehouses" => rpc_call!(warehouses::get_warehouses),
            "add_warehouse" => rpc_call!(warehouses::add_warehouse, from_val!(o("request")), req.username.clone()),
            "update_warehouse" => rpc_call!(warehouses::update_warehouse, from_val!(o("request")), req.username.clone()),
            "delete_warehouse" => rpc_call!(warehouses::delete_warehouse, s("warehouseId"), req.username.clone()),

            // locations
            "get_locations" => rpc_call!(locations::get_locations, s("warehouseId")),
            "add_location" => rpc_call!(locations::add_location, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "update_location" => rpc_call!(locations::update_location, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_location" => rpc_call!(locations::delete_location, s("locationId"), req.username.clone(), req.real_name.clone()),
            "get_all_locations" => rpc_call!(locations::get_all_locations),
            "debug_locations" => rpc_call!(locations::debug_locations),

            // system config
            "get_system_config" => rpc_call!(system_config::get_system_config, s("configKey")),
            "set_system_config" => rpc_call!(system_config::set_system_config, from_val!(o("request")), req.username.clone()),
            "get_all_system_configs" => rpc_call!(system_config::get_all_system_configs),

            // categories
            "get_categories" => rpc_call!(categories::get_categories),
            "add_category" => rpc_call!(categories::add_category, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_category" => rpc_call!(categories::delete_category, s("categoryId"), req.username.clone(), req.real_name.clone()),

            // warehouse ops
            "stock_in" => rpc_call!(warehouse_ops::stock_in, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "stock_out" => rpc_call!(warehouse_ops::stock_out, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "stock_count" => rpc_call!(warehouse_ops::stock_count, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "batch_stock_in" => rpc_call!(warehouse_ops::batch_stock_in, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "batch_stock_out" => rpc_call!(warehouse_ops::batch_stock_out, from_val!(o("request")), req.username.clone(), req.real_name.clone()),

            // print templates
            "get_print_templates" => rpc_call!(print::get_print_templates),
            "get_print_templates_by_type" => rpc_call!(print::get_print_templates_by_type, s("templateType")),
            "add_print_template" => rpc_call!(print::add_print_template, from_val!(o("request")), req.username.clone()),
            "update_print_template" => rpc_call!(print::update_print_template, from_val!(o("request")), req.username.clone()),
            "delete_print_template" => rpc_call!(print::delete_print_template, s("templateId"), req.username.clone()),
            "set_default_print_template" => rpc_call!(print::set_default_print_template, s("templateId"), req.username.clone()),
            "get_default_print_template" => rpc_call!(print::get_default_print_template),

            // billing
            "get_billings" => rpc_call!(billing::get_billings, opt_s("partyType"), opt_s("partyId"), opt_s("status"), req.username.clone()),
            "create_billing" => rpc_call!(billing::create_billing, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "update_billing" => rpc_call!(billing::update_billing, from_val!(o("request")), s("billingId"), req.username.clone(), req.real_name.clone()),
            "delete_billing" => rpc_call!(billing::delete_billing, s("billingId"), req.username.clone(), req.real_name.clone()),
            "get_party_balance" => rpc_call!(billing::get_party_balance, s("partyType"), s("partyId"), s("billType")),
            "update_billing_payment" => rpc_call!(billing::update_billing_payment, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "auto_create_billing" => rpc_call!(billing::auto_create_billing, s("partyType"), s("partyId"), s("partyName"), s("orderId"), s("orderNo"), from_val!(o("amount")), s("billType"), req.username.clone(), req.real_name.clone()),
            "get_customer_statement" => rpc_call!(billing::get_customer_statement, s("partyId"), s("startDate"), s("endDate")),
            "get_supplier_statement" => rpc_call!(billing::get_supplier_statement, s("partyId"), s("startDate"), s("endDate")),

            // transfers
            "get_transfer_orders" => rpc_call!(transfers::get_transfer_orders),
            "create_transfer_order" => rpc_call!(transfers::create_transfer_order, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "get_transfer_order_items" => rpc_call!(transfers::get_transfer_order_items, s("orderId")),
            "delete_transfer_order" => rpc_call!(transfers::delete_transfer_order, s("orderId"), req.username.clone(), req.real_name.clone()),

            // packages
            "add_product_package" => rpc_call!(packages::add_product_package, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "get_product_packages" => rpc_call!(packages::get_product_packages, s("productId")),
            "get_all_packages" => rpc_call!(packages::get_all_packages),
            "delete_product_package" => rpc_call!(packages::delete_product_package, s("packageId"), req.username.clone(), req.real_name.clone()),

            // SSE endpoint: clients subscribe to real-time events
            "create_assembly_record" => rpc_call!(assembly::create_assembly_record, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "get_assembly_records" => rpc_call!(assembly::get_assembly_records),
            "delete_assembly_record" => rpc_call!(assembly::delete_assembly_record, s("recordId"), req.username.clone(), req.real_name.clone()),

            // excel
            "export_products" => rpc_call!(excel::export_products, req.username.clone()),
            "export_sale_orders" => rpc_call!(excel::export_sale_orders, req.username.clone()),
            "export_purchase_orders" => rpc_call!(excel::export_purchase_orders, req.username.clone()),
            "export_customers" => rpc_call!(excel::export_customers, req.username.clone()),
            "export_suppliers" => rpc_call!(excel::export_suppliers, req.username.clone()),
            "import_products" => rpc_call!(excel::import_products, from_val!(o("products")), req.username.clone()),
            "import_customers" => rpc_call!(excel::import_customers, from_val!(o("customers")), req.username.clone()),
            "import_suppliers" => rpc_call!(excel::import_suppliers, from_val!(o("suppliers")), req.username.clone()),
            "import_sale_orders" => rpc_call!(excel::import_sale_orders, from_val!(o("orders")), req.username.clone()),
            "import_purchase_orders" => rpc_call!(excel::import_purchase_orders, from_val!(o("orders")), req.username.clone()),

            // invoices
            "get_invoices" => rpc_call!(invoices::get_invoices, s("invoiceType")),
            "add_invoice" => rpc_call!(invoices::add_invoice, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_invoice" => rpc_call!(invoices::delete_invoice, s("invoiceId"), req.username.clone(), req.real_name.clone()),

            // returns
            "get_return_orders" => rpc_call!(returns::get_return_orders, s("returnType")),
            "create_return_order" => rpc_call!(returns::create_return_order, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_return_order" => rpc_call!(returns::delete_return_order, s("orderId"), req.username.clone(), req.real_name.clone()),
            "get_return_order_items" => rpc_call!(returns::get_return_order_items, s("returnId")),

            // payments
            "get_payment_records" => rpc_call!(payments::get_payment_records, s("billingId")),
            "add_payment_record" => rpc_call!(payments::add_payment_record, from_val!(o("request")), req.username.clone(), req.real_name.clone()),
            "delete_payment_record" => rpc_call!(payments::delete_payment_record, s("recordId"), req.username.clone(), req.real_name.clone()),

            // documents
            "save_product_document" => rpc_call!(documents::save_product_document, from_val!(o("request")), req.username.clone()),
            "get_product_documents" => rpc_call!(documents::get_product_documents, s("productId")),
            "delete_product_document" => rpc_call!(documents::delete_product_document, s("docId"), req.username.clone()),
            "read_file_base64" => rpc_call!(documents::read_file_base64, s("sourcePath")),

            // backup
            "backup_database" => rpc_call!(backup::backup_database, req.username.clone()),
            "list_backups" => rpc_call!(backup::list_backups),
            "get_last_backup_path" => rpc_call!(backup::get_last_backup_path),
            "restore_database" => rpc_call!(backup::restore_database, s("backupId"), req.username.clone()),
            "check_and_run_auto_backup" => rpc_call!(backup::check_and_run_auto_backup),
            "get_auto_backup_config" => rpc_call!(backup::get_auto_backup_config),

            // logs
            "get_operation_logs" => rpc_call!(operation_logs::get_operation_logs, None::<i64>, None::<String>, req.username.clone()),
            "add_operation_log" => rpc_call!(operation_logs::add_operation_log, from_val!(o("request"))),
            "clear_operation_logs" => rpc_call!(operation_logs::clear_operation_logs, req.username.clone()),

            // permissions
            "get_role_permissions" => rpc_call!(permissions::get_role_permissions, s("roleName")),
            "set_role_permission" => rpc_call!(permissions::set_role_permission, from_val!(o("request")), req.username.clone()),

            // global search
            "global_search" => rpc_call!(statistics::global_search, s("keyword")),

            // local-only
            "get_machine_code" | "activate_license" | "check_license" | "init_local_database" | "save_product_image" | "generate_billing_pdf" | "restart_app" | "save_backup_to" | "restore_database_from"
                => return Err("楹撹劊鑴欑湁鑴曞嵂鑴ㄧ尗鑴檵鑴劮椹磋劌绂勬悅闇茶劊鍗ゆ埉纰岃劥鑴伴簱鑴ㄨ劏".to_string()),

            _ => return Err(format!("鑴﹂簱鑴伴檵鑴欑湁鑴曞嵂: {}", req.cmd)),
        };
        Ok(json)
    })();

    // 鑴犺幗楣挎病鑴㈣劅鑴ㄩ簱鑴犳瘺铏忚劦鑴虫鎷㈠崲楣胯尗铏忔ゼ鑴ョ瘬鑴伴檵鑴ｉ湁鑴劏鑴劮鑴ц劷椹磋劌绂勬悅闇茶劊
    if is_write && result.is_ok() {
        let _ = tx.send(req.cmd.clone());
    }

    match result {
        Ok(data) => Json(RpcResponse::ok(data)),
        Err(e) => Json(RpcResponse::err(e)),
    }
}
