use crate::arg::get_arg;
use crate::time::get_time;
use crate::IResult;
use once_cell::sync::Lazy;
use std::sync::{Arc, Mutex};
use std::thread::sleep;
use std::time::Duration;

/// 定时发邮件: 达到5封邮件, 或者时间达到1分钟
static MSG_LIST: Lazy<Arc<Mutex<(Vec<String>, u128)>>> = Lazy::new(|| {
    let v = Arc::new(Mutex::new((vec![], 0)));
    let v2 = v.clone();
    std::thread::spawn(move || loop {
        sleep(Duration::from_millis(10 * 1000));
        let (cur, _) = get_time();
        let count = get_arg("mail.limit.count").as_u64().unwrap_or_else(|| 5) as usize;
        if let Ok(mut lock) = v2.lock() {
            if lock.0.len() >= count || (lock.1 != 0 && lock.1 <= cur) {
                let mut content = String::default();
                for x in lock.0.iter() {
                    content.push_str(&format!("<br/><br/> {}", x));
                }
                lock.0.clear();
                lock.1 = 0;
                drop(lock);

                let content = content.trim_start_matches("<br/><br/>");
                if let Err(e) = send::send(content) {
                    error!("发送邮件失败:{:?}", e);
                };
            }
        }
    });
    v
});

pub mod send {
    use crate::string::StringExentd;
    use crate::{get_arg, IResult, JsonVExentd};
    use lettre::{transport::smtp::authentication::Credentials, Message, Transport};

    /// 发送邮件
    pub fn send(content: impl Into<String>) -> IResult<()> {
        let content = content.into();
        let from_name = get_arg("mail.from_name").as_string2().ok_or("mail.from_name 配置为空")?;
        let user_name = get_arg("mail.user_name").as_string2().ok_or("mail.user_name 配置为空")?;
        let passpord = get_arg("mail.passpord").as_string2().ok_or("mail.passpord 配置为空")?;
        let subject = get_arg("mail.subject").as_string2().unwrap_or_else(|| "未配置主题".into());
        let to = get_arg("mail.to").as_string2().unwrap_or_default();

        let to = to.split_char(",");
        for x in to {
            if x.trim() == "" {
                continue;
            }
            send2(user_name.clone(), passpord.clone(), content.clone(), from_name.clone(), subject.clone(), x.to_string())?;
        }
        Ok(())
    }

    fn send2(user_name: String, passpord: String, content: String, from_name: String, subject: String, to: String) -> IResult<()> {
        let email = Message::builder().from(from_name.parse()?).to(to.parse()?).subject(subject).body(content)?;

        let creds = Credentials::new(user_name, passpord);
        let mailer = lettre::SmtpTransport::relay("smtp.126.com")?.credentials(creds).build();
        _ = mailer.send(&email).map_err(|e| format!("mailer.send {:?}", e))?;
        Ok(())
    }

    #[test]
    fn test_send() -> IResult {
        send("下单成功")
    }
}

pub fn send(content: impl Into<String>) -> IResult<()> {
    let content = content.into();
    let enable = get_arg("mail.enable").as_bool().unwrap_or_else(|| false);
    if !enable {
        return Ok(());
    }
    match MSG_LIST.lock() {
        Ok(mut lock) => {
            let wait = get_arg("mail.limit.wait").as_u64().unwrap_or_else(|| 60) as u128;
            lock.0.push(content.to_string());
            let (cur, _) = get_time();
            if lock.1 == 0 {
                lock.1 = cur + 1000 * wait;
            }
            drop(lock);
        }
        Err(e) => Err(e.to_string())?,
    }
    Ok(())
}

/**
/// 发送邮件
fn send0(content: &str) -> IResult<()> {
    // let enable = get_arg("mail.enable").map(|v| v == "true").unwrap_or(false);
    // if !enable {
    //     return;
    // }

    let from_name = get_arg("mail.from_name").as_string2().ok_or("mail.from_name 配置为空")?;
    let user_name = get_arg("mail.user_name").as_string2().ok_or("mail.user_name 配置为空")?;
    let passpord = get_arg("mail.passpord").as_string2().ok_or("mail.passpord 配置为空")?;
    let subject = get_arg("mail.subject").as_string2().ok_or("mail.subject 配置为空")?;

    let to = get_arg("mail.to").as_string2().unwrap_or_default();
    let to = to.split_arr(",");
    for x in to.iter() {
        if x.trim() == "" {
            continue;
        }
        send2(content, from_name.clone(), user_name.clone(), passpord.clone(), subject.clone(), x.to_string())?;
    }
    Ok(())
}
fn send2(content: &str, from_name: String, user_name: String, passpord: String, subject: String, to: String) -> IResult<()> {
    let email = EmailBuilder::new()
        .from(Mailbox::new_with_name(from_name, user_name.clone()))
        .to(Mailbox::new(to.clone()))
        .subject(subject)
        .html(content) //邮件标题 //邮件内容
        .build()?;

    //for example: xiaoming@163.com, password: 123456
    //let creds = Credentials::new("xiaoming".to_string(), "123456".to_string());
    let creds = Credentials::new(user_name, passpord);

    //如163的邮箱就是smtp.163.com, 126的邮箱就是smtp.126.com
    let mut mailer = SmtpClient::new_simple("smtp.126.com")?.credentials(creds).transport();

    let result = mailer.send(email.into());

    if result.is_ok() {
        debug!("Email sent is ok: {}", to);
        Ok(())
    } else {
        Err(format!("Could not send email({}): {:?}", to, result).into())
    }
}
*/


// #[test]
// fn test_send() {
//     let _ = crate::toml_read::run_watch("D:\\code_dsp\\etax\\config_rpa.toml");
//     // crate::mylog::init_log("mailtest");
//     error!("1111111");
//     error!("222222");
//     error!("33333333");
//     error!("444444");
//     error!("55555");
//     error!("99999");

//     // send("1111111");
//     // send("222222");
//     // send("33333333");
//     // send("444444");
//     // send("55555");

//     sleep(Duration::from_millis(120 * 1000));
// }
fn _f(){}