// 打印管理模块 - v2 支持按模块类型筛选模板
use crate::models::*;
use crate::database::DB_CONN;
use crate::permissions::check_permission;
use uuid::Uuid;
use chrono::Local;

/// 模板类型常量（用于 print_templates.template_type）
pub const TYPE_SALE: &str = "sale";
pub const TYPE_PURCHASE: &str = "purchase";
pub const TYPE_STOCK_IN: &str = "stock_in";
pub const TYPE_STOCK_OUT: &str = "stock_out";
pub const TYPE_RETURN: &str = "return";
pub const TYPE_TRANSFER: &str = "transfer";
pub const TYPE_BILLING: &str = "billing";

/// 从行映射 PrintTemplate（第16列是新增的 template_type）
fn row_to_template(row: &rusqlite::Row) -> Result<PrintTemplate, rusqlite::Error> {
    Ok(PrintTemplate {
        id: row.get(0)?,
        template_name: row.get(1)?,
        paper_size: row.get(2)?,
        paper_width: row.get(3)?,
        paper_height: row.get(4)?,
        margin_top: row.get(5)?,
        margin_bottom: row.get(6)?,
        margin_left: row.get(7)?,
        margin_right: row.get(8)?,
        header_text: row.get(9)?,
        footer_text: row.get(10)?,
        show_logo: row.get::<_, i32>(11)? == 1,
        logo_path: row.get(12)?,
        font_size: row.get(13)?,
        is_default: row.get::<_, i32>(14)? == 1,
        created_at: row.get(15)?,
        template_type: row.get::<_, Option<String>>(16)?.unwrap_or_default(),
        subheader_text: row.get::<_, Option<String>>(17)?.unwrap_or_default(),
        show_company_info: row.get::<_, Option<i32>>(18)?.unwrap_or(1) == 1,
        show_order_no: row.get::<_, Option<i32>>(19)?.unwrap_or(1) == 1,
        show_date: row.get::<_, Option<i32>>(20)?.unwrap_or(1) == 1,
        show_customer: row.get::<_, Option<i32>>(21)?.unwrap_or(1) == 1,
        show_items: row.get::<_, Option<i32>>(22)?.unwrap_or(1) == 1,
        show_total: row.get::<_, Option<i32>>(23)?.unwrap_or(1) == 1,
        show_remark: row.get::<_, Option<i32>>(24)?.unwrap_or(1) == 1,
        show_signature: row.get::<_, Option<i32>>(25)?.unwrap_or(1) == 1,
        show_unit_price: row.get::<_, Option<i32>>(26)?.unwrap_or(1) == 1,
        show_amount: row.get::<_, Option<i32>>(27)?.unwrap_or(1) == 1,
        show_model: row.get::<_, Option<i32>>(28)?.unwrap_or(1) == 1,
        signer_name: row.get::<_, Option<String>>(29)?.unwrap_or_default(),
        auditor_name: row.get::<_, Option<String>>(30)?.unwrap_or_default(),
        confirmer_name: row.get::<_, Option<String>>(31)?.unwrap_or_default(),
    })
}

/// 获取当前模板类型的显示名称
pub fn template_type_label(t: &str) -> &str {
    match t {
        TYPE_SALE => "销售单",
        TYPE_PURCHASE => "采购单",
        TYPE_STOCK_IN => "入库单",
        TYPE_STOCK_OUT => "出库单",
        TYPE_RETURN => "退货单",
        TYPE_TRANSFER => "调拨单",
        TYPE_BILLING => "账单",
        _ => "通用",
    }
}

#[tauri::command]
pub fn add_print_template(request: CreatePrintTemplateRequest, username: String) -> Result<PrintTemplate, String> {
    if !check_permission(&username, "print_edit") {
        return Err("权限不足：没有新增打印模板的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_mut().ok_or("Database not initialized")?;
    
    let id = Uuid::new_v4().to_string();
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    
    if request.is_default {
        conn.execute("UPDATE print_templates SET is_default = 0 WHERE is_default = 1", [])
            .map_err(|e| e.to_string())?;
    }
    
    conn.execute(
        "INSERT INTO print_templates (id, template_name, paper_size, paper_width, paper_height, 
         margin_top, margin_bottom, margin_left, margin_right, header_text, footer_text, 
         show_logo, logo_path, font_size, is_default, created_at, template_type,
         subheader_text, show_company_info, show_order_no, show_date, show_customer,
         show_items, show_total, show_remark, show_signature,
         show_unit_price, show_amount, show_model, signer_name, auditor_name, confirmer_name) 
         VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,
         ?18,?19,?20,?21,?22,?23,?24,?25,?26,?27,?28,?29,?30,?31,?32)",
        rusqlite::params![
            id, request.template_name, request.paper_size,
            request.paper_width, request.paper_height,
            request.margin_top, request.margin_bottom,
            request.margin_left, request.margin_right,
            request.header_text, request.footer_text,
            if request.show_logo { 1 } else { 0 },
            request.logo_path, request.font_size,
            if request.is_default { 1 } else { 0 },
            now, request.template_type,
            request.subheader_text.clone().unwrap_or_default(),
            if request.show_company_info.unwrap_or(true) { 1 } else { 0 },
            if request.show_order_no.unwrap_or(true) { 1 } else { 0 },
            if request.show_date.unwrap_or(true) { 1 } else { 0 },
            if request.show_customer.unwrap_or(true) { 1 } else { 0 },
            if request.show_items.unwrap_or(true) { 1 } else { 0 },
            if request.show_total.unwrap_or(true) { 1 } else { 0 },
            if request.show_remark.unwrap_or(true) { 1 } else { 0 },
            if request.show_signature.unwrap_or(true) { 1 } else { 0 },
            if request.show_unit_price.unwrap_or(true) { 1 } else { 0 },
            if request.show_amount.unwrap_or(true) { 1 } else { 0 },
            if request.show_model.unwrap_or(true) { 1 } else { 0 },
            request.signer_name.clone().unwrap_or_default(),
            request.auditor_name.clone().unwrap_or_default(),
            request.confirmer_name.clone().unwrap_or_default(),
        ]
    ).map_err(|e| e.to_string())?;
    
    Ok(PrintTemplate {
        id, template_name: request.template_name,
        paper_size: request.paper_size, paper_width: request.paper_width,
        paper_height: request.paper_height, margin_top: request.margin_top,
        margin_bottom: request.margin_bottom, margin_left: request.margin_left,
        margin_right: request.margin_right, header_text: request.header_text,
        footer_text: request.footer_text, show_logo: request.show_logo,
        logo_path: request.logo_path, font_size: request.font_size,
        is_default: request.is_default, created_at: now,
        template_type: request.template_type,
        subheader_text: request.subheader_text.clone().unwrap_or_default(),
        show_company_info: request.show_company_info.unwrap_or(true),
        show_order_no: request.show_order_no.unwrap_or(true),
        show_date: request.show_date.unwrap_or(true),
        show_customer: request.show_customer.unwrap_or(true),
        show_items: request.show_items.unwrap_or(true),
        show_total: request.show_total.unwrap_or(true),
        show_remark: request.show_remark.unwrap_or(true),
        show_signature: request.show_signature.unwrap_or(true),
        show_unit_price: request.show_unit_price.unwrap_or(true),
        show_amount: request.show_amount.unwrap_or(true),
        show_model: request.show_model.unwrap_or(true),
        signer_name: request.signer_name.clone().unwrap_or_default(),
        auditor_name: request.auditor_name.clone().unwrap_or_default(),
        confirmer_name: request.confirmer_name.clone().unwrap_or_default(),
    })
}

#[tauri::command]
pub fn get_print_templates() -> Result<Vec<PrintTemplate>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_ref().ok_or("Database not initialized")?;
    
    let mut stmt = conn.prepare(
        "SELECT id, template_name, paper_size, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, header_text, footer_text, show_logo, logo_path, font_size, is_default, created_at, template_type, subheader_text, show_company_info, show_order_no, show_date, show_customer, show_items, show_total, show_remark, show_signature, show_unit_price, show_amount, show_model, signer_name, auditor_name, confirmer_name FROM print_templates ORDER BY template_type, is_default DESC, created_at DESC"
    ).map_err(|e| e.to_string())?;
    
    let templates = stmt.query_map([], |row| row_to_template(row))
        .map_err(|e| e.to_string())?;
    templates.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}

/// 按模块类型获取打印模板
#[tauri::command]
pub fn get_print_templates_by_type(template_type: String) -> Result<Vec<PrintTemplate>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_ref().ok_or("Database not initialized")?;
    
    let mut stmt = conn.prepare(
        "SELECT id, template_name, paper_size, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, header_text, footer_text, show_logo, logo_path, font_size, is_default, created_at, template_type, subheader_text, show_company_info, show_order_no, show_date, show_customer, show_items, show_total, show_remark, show_signature, show_unit_price, show_amount, show_model, signer_name, auditor_name, confirmer_name FROM print_templates WHERE template_type = ?1 OR template_type = '' ORDER BY is_default DESC, created_at DESC"
    ).map_err(|e| e.to_string())?;
    
    let templates = stmt.query_map([&template_type], |row| row_to_template(row))
        .map_err(|e| e.to_string())?;
    templates.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}

#[tauri::command]
pub fn update_print_template(template: PrintTemplate, username: String) -> Result<PrintTemplate, String> {
    if !check_permission(&username, "print_edit") {
        return Err("权限不足：没有编辑打印模板的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_mut().ok_or("Database not initialized")?;
    
    if template.is_default {
        conn.execute(
            "UPDATE print_templates SET is_default = 0 WHERE is_default = 1 AND id != ?1",
            rusqlite::params![template.id]
        ).map_err(|e| e.to_string())?;
    }
    
    conn.execute(
        "UPDATE print_templates SET template_name=?1, paper_size=?2, paper_width=?3, 
         paper_height=?4, margin_top=?5, margin_bottom=?6, margin_left=?7, 
         margin_right=?8, header_text=?9, footer_text=?10, show_logo=?11, 
         logo_path=?12, font_size=?13, is_default=?14, template_type=?16,
         subheader_text=?17, show_company_info=?18, show_order_no=?19,
         show_date=?20, show_customer=?21, show_items=?22,
         show_total=?23, show_remark=?24, show_signature=?25,
         show_unit_price=?26, show_amount=?27, show_model=?28,
         signer_name=?29, auditor_name=?30, confirmer_name=?31 WHERE id=?15",
        rusqlite::params![
            template.template_name, template.paper_size, template.paper_width,
            template.paper_height, template.margin_top, template.margin_bottom,
            template.margin_left, template.margin_right, template.header_text,
            template.footer_text, if template.show_logo { 1 } else { 0 },
            template.logo_path, template.font_size,
            if template.is_default { 1 } else { 0 },
            template.id, template.template_type,
            template.subheader_text,
            if template.show_company_info { 1 } else { 0 },
            if template.show_order_no { 1 } else { 0 },
            if template.show_date { 1 } else { 0 },
            if template.show_customer { 1 } else { 0 },
            if template.show_items { 1 } else { 0 },
            if template.show_total { 1 } else { 0 },
            if template.show_remark { 1 } else { 0 },
            if template.show_signature { 1 } else { 0 },
            if template.show_unit_price { 1 } else { 0 },
            if template.show_amount { 1 } else { 0 },
            if template.show_model { 1 } else { 0 },
            template.signer_name,
            template.auditor_name,
            template.confirmer_name,
        ]
    ).map_err(|e| e.to_string())?;
    
    Ok(template)
}

#[tauri::command]
pub fn delete_print_template(template_id: String, username: String) -> Result<(), String> {
    if !check_permission(&username, "print_edit") {
        return Err("权限不足：没有删除打印模板的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_mut().ok_or("Database not initialized")?;
    conn.execute("DELETE FROM print_templates WHERE id = ?1", rusqlite::params![template_id])
        .map_err(|e| e.to_string())?;
    Ok(())
}

#[tauri::command]
pub fn set_default_print_template(template_id: String, username: String) -> Result<(), String> {
    if !check_permission(&username, "print_edit") {
        return Err("权限不足：没有设置默认模板的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    conn.execute("UPDATE print_templates SET is_default = 0 WHERE is_default = 1", [])
        .map_err(|e| e.to_string())?;
    conn.execute("UPDATE print_templates SET is_default = 1 WHERE id = ?1", rusqlite::params![template_id])
        .map_err(|e| e.to_string())?;
    Ok(())
}

#[tauri::command]
pub fn get_default_print_template() -> Result<Option<PrintTemplate>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| e.to_string())?;
    let conn = conn_guard.as_ref().ok_or("Database not initialized")?;
    
    let mut stmt = conn.prepare(
        "SELECT id, template_name, paper_size, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, header_text, footer_text, show_logo, logo_path, font_size, is_default, created_at, template_type, subheader_text, show_company_info, show_order_no, show_date, show_customer, show_items, show_total, show_remark, show_signature, show_unit_price, show_amount, show_model, signer_name, auditor_name, confirmer_name FROM print_templates WHERE is_default = 1 LIMIT 1"
    ).map_err(|e| e.to_string())?;
    let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
    
    if let Some(row) = rows.next().map_err(|e| e.to_string())? {
        Ok(Some(row_to_template(&row).map_err(|e| e.to_string())?))
    } else {
        Ok(None)
    }
}
