// 发票管理模块
use serde::{Deserialize, Serialize};
use crate::database::DB_CONN;
use crate::operation_logs::log_operation;
use crate::error_util;
use crate::permissions::check_permission;
use uuid::Uuid;
use chrono::Local;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Invoice {
    pub id: String,
    pub invoice_type: String,
    pub invoice_no: String,
    pub party_id: String,
    pub party_name: String,
    pub order_id: String,
    pub order_no: String,
    pub amount: f64,
    pub tax_amount: f64,
    pub invoice_date: String,
    pub remark: String,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct CreateInvoiceRequest {
    pub invoice_type: String,
    pub invoice_no: String,
    pub party_id: String,
    pub party_name: String,
    pub order_id: String,
    pub order_no: String,
    pub amount: f64,
    pub tax_amount: f64,
    pub invoice_date: String,
    pub remark: String,
}

fn row_to_invoice(row: &rusqlite::Row) -> rusqlite::Result<Invoice> {
    Ok(Invoice {
        id: row.get(0)?,
        invoice_type: row.get(1)?,
        invoice_no: row.get(2)?,
        party_id: row.get::<_, Option<String>>(3)?.unwrap_or_default(),
        party_name: row.get::<_, Option<String>>(4)?.unwrap_or_default(),
        order_id: row.get::<_, Option<String>>(5)?.unwrap_or_default(),
        order_no: row.get::<_, Option<String>>(6)?.unwrap_or_default(),
        amount: row.get::<_, Option<f64>>(7)?.unwrap_or(0.0),
        tax_amount: row.get::<_, Option<f64>>(8)?.unwrap_or(0.0),
        invoice_date: row.get::<_, Option<String>>(9)?.unwrap_or_default(),
        remark: row.get::<_, Option<String>>(10)?.unwrap_or_default(),
        created_at: row.get(11)?,
    })
}

#[tauri::command]
pub fn add_invoice(request: CreateInvoiceRequest, username: String, real_name: String) -> Result<Invoice, String> {
    if !check_permission(&username, "sales_edit") && !check_permission(&username, "purchases_edit") {
        return Err("权限不足：没有添加发票的权限".to_string());
    }
    let mut conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_mut().ok_or("系统错误：数据库未初始化")?;
    let id = Uuid::new_v4().to_string();
    let now = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
    conn.execute(
        "INSERT INTO invoices (id, invoice_type, invoice_no, party_id, party_name, order_id, order_no, amount, tax_amount, invoice_date, remark, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12)",
        [&id, &request.invoice_type, &request.invoice_no, &request.party_id, &request.party_name, &request.order_id, &request.order_no, &request.amount.to_string(), &request.tax_amount.to_string(), &request.invoice_date, &request.remark, &now],
    ).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "添加", "发票管理", &format!("添加发票: {} 金额: {:.2}", request.invoice_no, request.amount));
    Ok(Invoice { id, invoice_type: request.invoice_type, invoice_no: request.invoice_no, party_id: request.party_id, party_name: request.party_name, order_id: request.order_id, order_no: request.order_no, amount: request.amount, tax_amount: request.tax_amount, invoice_date: request.invoice_date, remark: request.remark, created_at: now })
}

#[tauri::command]
pub fn get_invoices(invoice_type: String) -> Result<Vec<Invoice>, String> {
    let conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    let sql = if invoice_type.is_empty() { "SELECT * FROM invoices ORDER BY created_at DESC".to_string() } else { format!("SELECT * FROM invoices WHERE invoice_type='{}' ORDER BY created_at DESC", invoice_type) };
    let mut stmt = conn.prepare(&sql).map_err(|e| error_util::to_chinese_error(e))?;
    let rows = stmt.query_map([], |row| row_to_invoice(row)).map_err(|e| error_util::to_chinese_error(e))?;
    rows.collect::<Result<Vec<_>, _>>().map_err(|e| error_util::to_chinese_error(e))
}

#[tauri::command]
pub fn delete_invoice(invoice_id: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "sales_edit") && !check_permission(&username, "purchases_edit") {
        return Err("权限不足：没有删除发票的权限".to_string());
    }
    let conn_guard = DB_CONN.lock().map_err(|e| error_util::to_chinese_error(e))?;
    let conn = conn_guard.as_ref().ok_or("系统错误：数据库未初始化")?;
    let inv_no: String = conn.query_row("SELECT invoice_no FROM invoices WHERE id=?1", [&invoice_id], |row| row.get(0)).unwrap_or_default();
    conn.execute("DELETE FROM invoices WHERE id=?1", [&invoice_id]).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "删除", "发票管理", &format!("删除发票: {}", inv_no));
    Ok("删除成功".to_string())
}