use crate::constants::{common::*, window::*};
use crate::env::TEACHERCONTROL_JK_URL;
use crate::window::WindowLabel;
use tauri::{AppHandle, Manager, Runtime, WebviewUrl, WebviewWindowBuilder};

/// 创建会议窗口（内部实现）
pub async fn create_meeting_window_impl<R: Runtime>(app: &AppHandle<R>, window_type: u8, course_id: Option<u64>) -> Result<(), String> {
    // 根据窗口类型定义label和url
    let (label, url, title, width, height, decorations, transparent) = match window_type {
        1 => {
            let label = WindowLabel::MEETING.as_ref();
            (
                label,
                WebviewUrl::App("/#/meeting".into()),
                "会议",
                MEETING_TYPE_1_WIDTH,
                MEETING_TYPE_1_HEIGHT,
                false,
                true,
            )
        }
        2 => {
            if let Some(id) = course_id {
                println!("创建会议窗口2: {}", TEACHERCONTROL_JK_URL);
                let url = format!("{}?CourseID={}", TEACHERCONTROL_JK_URL, id);
                let label = WindowLabel::MEETING2.as_ref();
                (
                    label,
                    WebviewUrl::External(url.parse().map_err(|_| "URL格式错误".to_string())?),
                    "会议2",
                    MEETING_TYPE_2_WIDTH,
                    MEETING_TYPE_2_HEIGHT,
                    true,
                    false,
                )
            } else {
                return Err(MSG_MEETING_TYPE_2_NEEDS_COURSE_ID.to_string());
            }
        }
        _ => return Err(MSG_UNSUPPORTED_MEETING_WINDOW_TYPE.to_string()),
    };

    // 如果窗口已存在，先关闭它
    if let Some(win) = app.get_webview_window(label) {
        let _ = win.close();
    }

    // 创建窗口
    WebviewWindowBuilder::new(app, label, url)
        .title(title)
        .inner_size(width, height)
        .decorations(decorations)
        .transparent(transparent)
        .devtools(true)
        .build()
        .map_err(|e| format!("{} {}", MSG_FAILED_CREATE_MEETING_WINDOW, e))?;

    Ok(())
}
