// 还款记录模块
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 PaymentRecord {
    pub id: String,
    pub billing_id: String,
    pub party_type: String,
    pub party_id: String,
    pub party_name: String,
    pub amount: f64,
    pub payment_date: String,
    pub remark: String,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct AddPaymentRecordRequest {
    pub billing_id: String,
    pub party_type: String,
    pub party_id: String,
    pub party_name: String,
    pub amount: f64,
    pub payment_date: String,
    pub remark: String,
}

#[tauri::command]
pub fn add_payment_record(request: AddPaymentRecordRequest, username: String, real_name: String) -> Result<PaymentRecord, String> {
    if !check_permission(&username, "billing_edit") {
        return Err("权限不足：没有新增还款记录的权限".to_string());
    }
    if request.amount <= 0.0 {
        return Err("还款金额必须大于0".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 payment_records (id, billing_id, party_type, party_id, party_name, amount, payment_date, remark, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
        [&id, &request.billing_id, &request.party_type, &request.party_id, &request.party_name, &request.amount.to_string(), &request.payment_date, &request.remark, &now],
    ).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "添加还款记录", "应收应付", &format!("{} 还款{}", request.party_name, request.amount));
    Ok(PaymentRecord { id, billing_id: request.billing_id, party_type: request.party_type, party_id: request.party_id, party_name: request.party_name, amount: request.amount, payment_date: request.payment_date, remark: request.remark, created_at: now })
}

#[tauri::command]
pub fn get_payment_records(billing_id: String) -> Result<Vec<PaymentRecord>, 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 mut stmt = conn.prepare("SELECT * FROM payment_records WHERE billing_id=?1 ORDER BY created_at DESC").map_err(|e| error_util::to_chinese_error(e))?;
    let rows = stmt.query_map([&billing_id], |row| {
        Ok(PaymentRecord { id: row.get(0)?, billing_id: row.get(1)?, party_type: row.get::<_, Option<String>>(2)?.unwrap_or_default(), party_id: row.get::<_, Option<String>>(3)?.unwrap_or_default(), party_name: row.get::<_, Option<String>>(4)?.unwrap_or_default(), amount: row.get::<_, Option<f64>>(5)?.unwrap_or(0.0), payment_date: row.get::<_, Option<String>>(6)?.unwrap_or_default(), remark: row.get::<_, Option<String>>(7)?.unwrap_or_default(), created_at: row.get(8)? })
    }).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_payment_record(record_id: String, username: String, real_name: String) -> Result<String, String> {
    if !check_permission(&username, "billing_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 info: (String, f64) = conn.query_row(
        "SELECT COALESCE(party_name,''), COALESCE(amount,0.0) FROM payment_records WHERE id=?1", [&record_id],
        |row| Ok((row.get(0)?, row.get(1)?))
    ).unwrap_or_default();
    conn.execute("DELETE FROM payment_records WHERE id=?1", [&record_id]).map_err(|e| error_util::to_chinese_error(e))?;
    log_operation(&username, &real_name, "删除还款记录", "应收应付", &format!("删除还款记录: {} {:.2}", info.0, info.1));
    Ok("删除成功".to_string())
}