use std::collections::HashMap;
use br_crypto::{base64, qp};
use br_crypto::encoding::urlencoding_decode;
use br_crypto::hash::{u8_to_md5};
use chrono::{DateTime, Utc};
use json::{JsonValue, object};

// const JOIN_STR: &str = "####################";
const JOIN_STR: &str = "\r\n\r\n";


#[derive(Clone, Debug)]
pub struct MailHead {
    email: String,
    email_type: String,
    head_list: Vec<String>,

    from_name: String,
    from_mail: String,
    from_tail: String,
    subject: String,

    to_arr: Vec<JsonValue>,
    cc_arr: Vec<JsonValue>,

    version: String,
    date: String,
    timestamp: String,

    content_type: String,
    charset: String,
    encoding: String,
    pub boundary: String,
}

impl MailHead {
    pub fn new(mail_data: &str, email: &str) -> Self {
        let temp_data = mail_data.to_string();

        // // 兼容腾讯系统邮件
        // if mail_data.contains("\n\n") {
        //     temp_data = mail_data.replace("\n\n", "\r\n\r\n");
        // }
        // let mail_list: Vec<&str> = temp_data.split("\r\n\r\n").collect();
        //
        // println!("{:#?}", mail_list);
        //
        //
        // let mut temp = mail_list[0].to_string();
        // if mail_list[0].contains("\n") {
        //     temp = mail_list[0].replace("\n", "\r\n");
        // }
        // if temp_data.contains("\n") {
        //     temp_data = temp_data.replace("\n", "\r\n");
        // }

        let head_list = temp_data.split("\r\n").map(|x| x.to_string()).collect::<Vec<String>>();

        Self {
            email: email.to_string(),
            email_type: "".to_string(),
            head_list,

            from_name: "".to_string(),
            from_mail: "".to_string(),
            from_tail: "".to_string(),
            subject: "".to_string(),

            to_arr: vec![],
            cc_arr: vec![],

            version: "".to_string(),
            date: "".to_string(),
            timestamp: "".to_string(),

            content_type: "".to_string(),
            charset: "".to_string(),
            encoding: "".to_string(),
            boundary: "".to_string(),
        }
    }

    pub fn default() -> Self {
        Self {
            email: "".to_string(),
            email_type: "".to_string(),
            head_list: vec![],
            from_name: "".to_string(),
            from_mail: "".to_string(),
            from_tail: "".to_string(),
            subject: "".to_string(),
            to_arr: vec![],
            cc_arr: vec![],
            version: "".to_string(),
            date: "".to_string(),
            timestamp: "".to_string(),
            content_type: "".to_string(),
            charset: "".to_string(),
            encoding: "".to_string(),
            boundary: "".to_string(),
        }
    }


    pub fn handle_head(&mut self) {
        let head = self.head_list.clone();

        let data = if head.contains(&"\t".to_string()) {
            self.remove_head_trash_imap();
            self.head_list.clone()
        } else {
            self.remove_head_trash_pop();
            self.head_list.clone()
        };

        for item in data {
            if item.starts_with("Subject:") {
                self.get_subject(item.clone());
            }
            if item.starts_with("From:") {
                self.get_from(item.clone());
                self.get_email_type();
            }
            if item.starts_with("To:") {
                self.get_to(item.clone());
            }
            if item.starts_with("Cc:") {
                self.get_cc(item.clone());
            }
            if item.to_lowercase().starts_with("date:") {
                self.get_date(item.clone());
            }
            if item.starts_with("Content-Transfer-Encoding:") {
                self.get_head_encoding(item.clone());
            }
            if item.starts_with("Content-Type:") {
                self.get_content_type(item.clone());
            }
        }
    }

    /// 对邮件头的第一次格式化处理
    /// 去掉邮件头中的空数组, 以"X-"开头的字段, 以及将以\t或空格开头的字段进行与上一行拼接并删除
    pub fn remove_head_trash_imap(&mut self) {
        let mut item = 0;
        let mut index = 0;
        let temp = self.head_list.clone();
        for cell in temp {
            if cell.trim().is_empty() {
                self.head_list.remove(index);
            } else {
                index += 1;
            }
        }
        index = 0;
        let mut list = "".to_string();
        let data = self.head_list.clone();
        for head in data.iter() {
            if &head.as_str()[0..1] == "\t" {
                list = format!("{} {}", list.clone(), head.trim_start_matches("\t"));
                self.head_list[item] = list.clone();
            } else if &head.as_str()[0..1] == " " {
                list = format!("{} {}", list.clone(), head.trim_start_matches(" "));
                self.head_list[item] = list.clone();
            } else {
                item = index;
                list = head.to_string();
            }
            index += 1;
        }
        self.head_list.retain(|x| &x.as_str()[0..1] != "\t");
        self.head_list.retain(|x| &x.as_str()[0..1] != " ");
        self.head_list.retain(|x| &x.as_str()[0..2] != "X-");
    }

    pub fn remove_head_trash_pop(&mut self) {
        let mut index = 0;
        let mut list = HashMap::new();
        let mut data = vec![];
        let mut switch = 0;

        let head = self.head_list.clone();

        for item in head {
            let temp = item.clone();
            match temp.clone().find(": ") {
                None => {
                    if switch == 0 {
                        switch = index - 1;
                    }
                    if switch < 0 {
                        switch = 0;
                    }
                    let _ = list.insert(switch, temp.to_string()).clone();
                    data.push("".to_string());
                }
                Some(_) => {
                    switch = 0;
                    data.push(temp.clone());
                }
            }
            index += 1;
        }

        for (key, value) in list {
            data[key] = format!("{}{}", data[key].clone(), value);
        }

        data.retain(|x| !x.is_empty());
        data.retain(|x| &x.as_str()[0..2] != "X-");

        self.head_list = data;
    }

    pub fn get_boundary(&mut self) {
        self.head_list.retain(|x| {
            if x.contains("boundary=") {
                self.boundary = x.split("boundary=").collect::<Vec<&str>>()[1].to_string();
                self.boundary = self.boundary.replace("\"", "");
                false
            } else {
                true
            }
        });
    }
    /// 获取邮件主题 Subject
    pub fn get_subject(&mut self, text: String) {
        let data = text.trim_start_matches("Subject:").trim();

        if !data.contains("=?") && !data.contains("?=") {
            self.subject = data.to_string();
            return;
        }

        let (state, _) = get_charset(data.to_string());
        if state {
            let data_vec: Vec<&str> = data.clone().split("?").collect();

            let mut sub_vec = vec![];
            let mut index = 0;

            if data_vec.len() < 5 {
                self.subject = data_vec.join("?");
                return;
            }
            loop {
                if index == data_vec.len() - 1 {
                    break;
                }

                match data_vec.len() {
                    1..=5 => {
                        let temp = get_decode_method(data_vec[1], data_vec[2], data_vec[3]);
                        index = 4;
                        sub_vec.push(temp);
                    }
                    _ => {
                        if data_vec.len() < index + 4 {
                            for i in index + 1..data_vec.len() {
                                sub_vec.push(data_vec[i].to_string())
                            }
                            self.subject = sub_vec.join("?");
                            return;
                        }
                        let temp = get_decode_method(data_vec[index + 1], data_vec[index + 2], data_vec[index + 3]);
                        index += 4;
                        sub_vec.push(temp);
                    }
                }
            }
            self.subject = sub_vec.join("");
        } else {
            self.subject = data.to_string();
        }


        // let (state, _) = get_charset(data.to_string());
        // if state {
        //     if data.contains(" ") {
        //         let sub_vec: Vec<&str> = data.trim().split(" ").collect();
        //         for cell in sub_vec {
        //             let part_subject = if cell.contains("?") {
        //                 let temp_vec: Vec<&str> = cell.split("?").collect();
        //                 if temp_vec.len() < 3 {
        //                     cell.to_string()
        //                 } else {
        //                     get_decode_method(temp_vec[1], temp_vec[2], temp_vec[3])
        //                 }
        //             } else {
        //                 format!("{}", cell)
        //             };
        //             all_subject.push_str(part_subject.as_str());
        //         }
        //     } else {
        //         if data.contains("==") {
        //             let temp_vec: Vec<&str> = data.split("==").collect();
        //             for cell in temp_vec {
        //
        //             }
        //         } else {
        //             let temp_vec: Vec<&str> = data.split("?").collect();
        //             all_subject = get_decode_method(temp_vec[1], temp_vec[2], temp_vec[3]);
        //         }
        //     }
        // } else {
        //     all_subject = data.to_string();
        // }
        // all_subject = all_subject.replace("\r\n", "").replace("\r", "").replace("\n", "");
        // self.subject = all_subject.clone();
        // println!("{}", self.subject);
    }

    /// 获取邮件的发送人 From
    pub fn get_from(&mut self, text: String) {
        let data = text.trim_start_matches("From:").trim();
        if data.contains("<") {
            let from_list: Vec<&str> = data.trim().split("<").collect();
            if from_list[0].is_empty() {
                self.from_mail = from_list[1].trim().trim_end_matches(">").to_string();
                self.from_name = self.from_mail.clone();
            } else {
                let (state, _) = get_charset(from_list[0].to_string());
                if state {
                    let name_vec: Vec<&str> = from_list[0].split("?").collect();
                    self.from_name = get_decode_method(name_vec[1], name_vec[2], name_vec[3]);
                } else {
                    self.from_name = from_list[0].trim().trim_start_matches('"').trim_end_matches('"').to_string();
                }
                self.from_mail = from_list[1].trim().trim_end_matches(">").to_string();
            }
        } else {
            if data.contains("?") {
                let (state, _) = get_charset(data.to_string());
                if state {
                    let from_vec: Vec<&str> = data.trim().split("?").collect();
                    let from_text = get_decode_method(from_vec[1], from_vec[2], from_vec[3]);
                    if from_text.contains("<") {
                        let from_list: Vec<&str> = from_text.trim().split("<").collect();
                        self.from_mail = from_list[from_list.len() - 1].trim_end_matches(">").trim().to_string();
                        if from_list.len() > 1 {
                            self.from_name = from_list[0].trim().to_string();
                        } else {
                            self.from_name = self.from_mail.clone();
                        }
                    }
                }
            } else {
                self.from_mail = data.trim().to_string();
                self.from_name = self.from_mail.clone();
            }
        }
        let tail: Vec<&str> = self.from_mail.split("@").collect();
        self.from_tail = tail[tail.len() - 1].to_string();
    }

    /// 获取该封邮件对于该账号是收件还是发件
    pub fn get_email_type(&mut self) {
        if self.email.eq(&self.from_mail) {
            self.email_type = "发件".to_string();
        } else {
            self.email_type = "收件".to_string();
        }
    }

    /// 获取邮件的收件人 To
    pub fn get_to(&mut self, text: String) {
        let data = text.trim_start_matches("To:").trim();
        let mut to_vec: Vec<&str> = Vec::new();
        if data.contains(",") {
            to_vec = data.split(",").collect();
        } else {
            to_vec.push(data);
        }
        for cell in to_vec {
            if !cell.contains("<") {
                let to_mail = cell.trim();
                let temp = object! { name: to_mail, mail: to_mail };
                self.to_arr.push(temp);
            } else {
                let to_list: Vec<&str> = cell.split("<").collect();
                let (state, _) = get_charset(to_list[0].to_string());
                let to_name = if state {
                    let name_vec: Vec<&str> = to_list[0].split("?").collect();
                    get_decode_method(name_vec[1], name_vec[2], name_vec[3])
                } else {
                    if to_list[0].trim().is_empty() {
                        to_list[1].trim().trim_end_matches(">").to_string()
                    } else {
                        to_list[0].trim().trim_start_matches('"').trim_end_matches('"').to_string()
                    }
                };
                let to_mail = to_list[1].trim().trim_end_matches(">").to_string();
                let temp = object! { name: to_name, mail: to_mail };
                self.to_arr.push(temp);
            }
        }
    }

    /// 获取邮件的抄送人 Cc
    pub fn get_cc(&mut self, text: String) {
        let data = text.trim_start_matches("Cc:").trim();
        let mut cc_vec: Vec<&str> = Vec::new();
        if data.contains(",") {
            cc_vec = data.split(",").collect();
        } else {
            cc_vec.push(data);
        }
        for cell in cc_vec {
            if cell.trim().is_empty() {
                break;
            }
            if !cell.contains("<") {
                let cc_mail = cell.trim();
                let temp = object! { name: cc_mail, mail: cc_mail };
                self.cc_arr.push(temp);
            } else {
                let cc_list: Vec<&str> = cell.split("<").collect();
                let (state, _) = get_charset(cc_list[0].to_string());
                let cc_name = if state {
                    let name_vec: Vec<&str> = cc_list[0].split("?").collect();
                    get_decode_method(name_vec[1], name_vec[2], name_vec[3])
                } else {
                    cc_list[0].trim().trim_start_matches('"').trim_end_matches('"').to_string()
                };
                let cc_mail = cc_list[1].trim().trim_end_matches(">").to_string();
                let temp = object! { name: cc_name, mail: cc_mail };
                self.cc_arr.push(temp);
            }
        }
    }

    /// 获取邮件格式版本 Version
    pub fn get_version(&mut self) {
        for item in self.head_list.iter_mut() {
            if item.to_lowercase().starts_with("mime-version:") {
                self.version = item.to_lowercase().trim_start_matches("mime-version:").trim().to_string();
                item.clear();
                break;
            }
        }
    }

    /// 获取邮件时间,时间戳 Date,Timestamp
    pub fn get_date(&mut self, text: String) {
        self.date = text.to_lowercase().trim_start_matches("date:").trim().to_string();

        if let Ok(parsed_date) = DateTime::parse_from_rfc2822(self.date.as_str()) {
            self.timestamp = parsed_date.with_timezone(&Utc).timestamp().to_string();
        } else if let Ok(parsed_date) = DateTime::parse_from_str(self.date.as_str(), "%a,%b %e %Y %H:%M:%S %z") {
            self.timestamp = parsed_date.with_timezone(&Utc).timestamp().to_string();
        } else {
            self.timestamp = 0.to_string();
        }
    }

    /// 获取邮件头中的格式相关信息 Content-Type,Charset,Boundary
    pub fn get_content_type(&mut self, text: String) {
        let data = text.trim_start_matches("Content-Type:").trim().to_string();
        let temp_vec: Vec<&str> = data.split(";").collect();
        self.content_type = temp_vec[0].to_lowercase().trim().to_string();
        for cell in temp_vec {
            if cell.to_lowercase().contains("charset") {
                self.charset = get_charset(cell.to_string()).1.to_string();
            }
            if cell.contains("boundary=") {
                self.boundary = cell.split("boundary=").collect::<Vec<&str>>()[1].to_string();
                self.boundary = self.boundary.replace("\"", "");
            }
        }
    }

    /// 获取邮件头中的加密方式 Content-Transfer-Encoding
    pub fn get_head_encoding(&mut self, text: String) {
        self.encoding = text.trim_start_matches("Content-Transfer-Encoding:").trim().to_string();
    }
}

pub struct Mail {
    md5: String,
    size: usize,
    head: MailHead,
    data: String,
    all_body: String,
    final_body: Vec<String>,
    body_text: String,
    body_html: String,
    attachment: Vec<String>,
    attachment_body: Vec<JsonValue>,
    pub body_list: String,
}

impl Mail {
    /// Mail::new() 方法参数: _邮件名, 邮件内容, 邮箱账号, _邮件加密分组个数
    pub fn new(mail_data: String, email: &str) -> Self {

        // 邮件唯一编号
        let md5 = u8_to_md5(mail_data.as_bytes().to_vec());
        let size = mail_data.len().clone();

        let temp_data = mail_data.clone();

        let mut mail_list: Vec<&str> = temp_data.split("\r\n\r\n").collect();
        let header = mail_list[0].clone();
        mail_list.remove(0);

        // let body_list = mail_list.join("\r\n\r\n");

        let body_list = mail_list.join(JOIN_STR);


        Self {
            md5,
            size,
            head: MailHead::new(header, email),
            data: mail_data,
            body_list: body_list.clone(),
            all_body: body_list,
            final_body: vec![],
            body_text: "".to_string(),
            body_html: "".to_string(),
            attachment: vec![],
            attachment_body: vec![],
        }
    }

    pub fn json(&mut self) -> JsonValue {
        self.head.handle_head();
        self.get_parse_attachment();
        self.get_body();
        self.attachment_parse();
        object! {
            size:self.size.clone(),
            md5:self.md5.clone(),
            email_type:self.head.email_type.clone(),
            subject:self.head.subject.clone(),
            date:self.head.date.clone(),
            timestamp:self.head.timestamp.clone(),
            from_name:self.head.from_name.clone(),
            from_mail:self.head.from_mail.clone(),
            from_tail:self.head.from_tail.clone(),
            to_arr:self.head.to_arr.clone(),
            cc_arr:self.head.cc_arr.clone(),
            version:self.head.version.clone(),
            content_type:self.head.content_type.clone(),
            encoding:self.head.encoding.clone(),
            body_text:self.body_text.clone(),
            body_html:self.body_html.clone(),
            attachment:self.attachment.clone(),
            attachment_body:self.attachment_body.clone(),
            boundary:self.head.boundary.clone()
        }
    }

    /// 处理boundary为段落中和段落尾的格式并返回
    /// * (段落中的bd样式, 段落尾的bd样式)
    fn handle_boundary(text: String) -> (String, String) {
        let mut mid_bd = String::from("--");
        mid_bd.push_str(text.as_str());
        mid_bd.push_str("\r\n");
        let mut end_bd = mid_bd.trim().to_string();
        end_bd.push_str("--");
        (mid_bd, end_bd)
    }

    /// 移除boundary并删除无效信息
    fn remove_boundary(boundary: String, text: String) -> Vec<String> {
        let mut body: Vec<String> = vec![];
        if !boundary.trim().is_empty() {
            let (mid, end) = Mail::handle_boundary(boundary);
            body = text.trim_start().split(&end).map(|x| x.to_string()).collect();
            // 判断尾部是否有开始处理时候添加的连接字符串, 如果有就删除
            if body[body.len() - 1].trim().eq(JOIN_STR) {
                body.remove(body.len() - 1);
            }
            let data = body[0].clone();
            body = data.split(&mid).map(|x| x.to_string()).collect();
            if body.len() > 1 && body[0].is_empty() || body[0].to_lowercase().contains("this is a multi-part message in mime format") {
                body.remove(0);
            }
        } else {
            body.push(text);
        }
        // println!("first rm bd: {:?}", body.clone());
        body
    }

    /// 获取格式相关信息 content_type
    fn get_content_info(text: String) -> String {
        let mut content_type = String::new();
        let temp: Vec<&str> = text.split("\r\n").collect();
        let t_len = temp.len();
        'out: for i in 0..t_len {
            let inner: Vec<&str> = temp[i].split(";").collect();
            let i_len = inner.len();
            for j in 0..i_len {
                if inner[j].starts_with("Content-Disposition:") {
                    content_type = inner[j].to_lowercase().trim_start_matches("content-disposition:").trim().to_string();
                    break 'out;
                } else if inner[j].starts_with("Content-Type:") {
                    content_type = inner[j].to_lowercase().trim_start_matches("content-type:").trim().to_string();
                    break 'out;
                }
            }
        }
        content_type
    }

    /// 获取加密方式 encoding
    fn get_encoding(text: String) -> String {
        let mut encoding = String::new();
        let temp: Vec<&str> = text.split("\r\n").collect();
        for item in temp {
            if item.starts_with("Content-Transfer-Encoding:") {
                encoding = item.to_lowercase().trim_start_matches("content-transfer-encoding:").trim().to_string();
            }
        }
        encoding
    }

    /// 获取邮件体里嵌套的boundary
    fn get_inside_boundary(text: String) -> String {
        let mut boundary = String::new();
        let temp: Vec<&str> = text.split(";").collect();
        for item in temp {
            if item.trim().starts_with("boundary=") {
                boundary = item.trim().trim_start_matches("boundary=").trim_start_matches('"').trim_end_matches('"').to_string();
                break;
            }
        }
        boundary
    }

    /// 去除在初始化邮件的时候添加的分隔符
    /// 获取去除boundary后的每小部分邮件体中的content-type相关信息
    /// * 返回值为(包含content_type的字段信息[content-type, charset, encoding, boundary], 切分再拼接的正文部分)
    fn remove_join_str(text: String) -> (Vec<String>, String) {
        // 判断邮件正文中是否有content-type, 如果有的话以数组的形式返回相关参数, 并将其余部分的正文进行拼接
        // println!("text: {}", text.clone());
        let mut temp: Vec<&str> = text.split(JOIN_STR).collect();
        // println!("temp vec: {:#?}", temp.clone());
        let content_type = Mail::get_content_info(temp[0].to_string());
        let encoding = Mail::get_encoding(temp[0].to_string());
        let boundary = Mail::get_inside_boundary(temp[0].to_string());
        let mut char_set = String::new();
        let temp_char = get_charset(temp[0].to_string());
        if temp_char.0 {
            char_set = temp_char.1.to_string();
        }
        if !content_type.is_empty() {
            temp.remove(0);
        }
        let content_info: Vec<String> = Vec::from([content_type, char_set, encoding, boundary]);
        // let data = temp.join("").trim().to_string();
        let data = temp.join(JOIN_STR).trim().to_string();
        // println!("rm join str data: {}", data.clone());
        (content_info, data)
    }

    /// 处理完邮件体时将插入的分割符还原为换行符
    fn last_rm_join_str(data: String) -> String {
        let temp: Vec<&str> = data.split(JOIN_STR).collect();
        let res = temp.join("\r\n").trim().to_string();
        // println!("last rm: {}", res.clone());
        res
    }


    /// 获取邮件附件全名并解析存入attachment中，待解析附件时调用
    fn get_parse_attachment(&mut self) {
        let mut tt: Vec<String> = Vec::new();
        let bou = self.head.boundary.clone();
        let data = self.data.clone();
        let mut slice: Vec<&str> = data.split(bou.as_str()).collect();

        for item in slice.iter_mut() {
            let mut t: Vec<&str> = item.split("\r\n\r\n").collect();

            for u in t.iter_mut() {
                let mut uu: Vec<&str> = u.split("\r\n").collect();
                for uuu in uu.iter_mut() {
                    let mut file_name = String::new();
                    if uuu.contains("filename") {
                        let name_info = urlencoding_decode(uuu);
                        if name_info.contains("?") {
                            let ii: Vec<&str> = name_info.split("?").collect();
                            if ii.len() > 3 {
                                let name = get_decode_method(ii[1], ii[2], ii[3]);
                                file_name = format!("{}{}", file_name, name);
                            }
                        } else if name_info.contains('"') {
                            let x: Vec<&str> = name_info.split('"').collect();
                            file_name = format!("{}{}", file_name, x[1]);
                        } else if name_info.contains("''") {
                            let x: Vec<&str> = name_info.split("''").collect();
                            file_name = format!("{}{}", file_name, x[1]);
                        } else {
                            let mut x: Vec<&str> = name_info.split("=").collect();
                            if x.len() == 1 {
                                x.push("txt.txt");
                            }
                            file_name = format!("{}{}", file_name, x[1]);
                        }
                    }
                    if !file_name.is_empty() {
                        file_name = file_name.replace(";", "");
                        tt.push(file_name.to_string());
                    }
                }
            }
        }
        self.attachment = tt.clone();
    }

    /// 对部分邮件体进行解码, 当输入值没有boundary时进行直接解码判断, 如果有boundary则进行迭代循环判断, 一层一层找出最小单位进行解码
    /// 如果读取到附件部分则先放进attachment_body中
    fn get_part_body(&mut self, text: String) -> Vec<String> {
        let mut alone = object! {};
        let charset = self.head.charset.clone();
        let encoding = self.head.encoding.clone();
        let data = Mail::remove_join_str(text);
        // println!("get part body data: {:#?}", data.clone());
        // println!("charset: {}, encoding: {}", charset.clone(), encoding.clone());
        if data.0[3].is_empty() {
            if data.0[0].is_empty() && (!charset.is_empty() || !encoding.is_empty()) {
                // println!(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>method 1");
                let text = Mail::last_rm_join_str(data.1.clone());
                let temp_text = get_decode_method(charset.as_str(), encoding.as_str(), text.as_str());
                if self.head.content_type.eq("text/html") {
                    self.body_html = temp_text.clone();
                } else {
                    self.body_text = temp_text.clone();
                }
                vec![temp_text]
            } else if !data.0[0].is_empty() {
                if data.0[0].eq("text/plain") {
                    // println!(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>method 2 text");
                    // let temp_text = get_decode_method(data.0[1].as_str(), data.0[2].as_str(), data.1.as_str());
                    let text = Mail::last_rm_join_str(data.1.clone());
                    let temp_text = get_decode_method(data.0[1].as_str(), data.0[2].as_str(), text.as_str());
                    self.body_text = temp_text.clone();
                    vec![temp_text]
                } else if data.0[0].eq("text/html") {
                    // println!(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>method 2 html");
                    // println!(">>>>>data1: {}", data.1.clone());
                    let text = Mail::last_rm_join_str(data.1.clone());
                    let temp_text = get_decode_method(data.0[1].as_str(), data.0[2].as_str(), text.as_str());
                    self.body_html = temp_text.clone();
                    vec![temp_text]
                } else {
                    if !data.1.is_empty() {
                        let text = Mail::last_rm_join_str(data.1.clone());
                        let last_body = text.replace("\r\n", "");
                        if !data.0[2].clone().is_empty() {
                            alone["encoding"] = data.0[2].clone().into();
                        } else {
                            alone["encoding"] = encoding.clone().into();
                        }
                        if !data.0[1].clone().is_empty() {
                            alone["charset"] = data.0[1].clone().into();
                        } else {
                            alone["charset"] = charset.clone().into();
                        }
                        alone["data"] = last_body.into();
                        self.attachment_body.push(alone.clone());
                        alone.clear();
                    }
                    vec!["not body".to_string()]
                }
            } else {
                // println!(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>method 3");
                let text = Mail::last_rm_join_str(data.1.clone());
                self.body_text = text.clone();
                vec![text]
            }
        } else {
            let mut temp = vec![];
            let body = Mail::remove_boundary(data.0[3].clone(), data.1);
            for item in body {
                let back = self.get_part_body(item);
                for t in back {
                    temp.push(t);
                }
            }
            temp
        }
    }

    /// 附件解析完成后存储在attachment中留待外部调用
    /// 附件名用md5加密后保存
    pub fn attachment_parse(&mut self) {
        let mut temp_att: Vec<JsonValue> = vec![];
        let mut temp_att_body: Vec<JsonValue> = vec![];
        let name = self.attachment.clone();
        let mut flag = 0;
        let filename = name.clone();
        for mut i in self.attachment_body.clone() {
            if name.len() > flag {
                i.insert("file_name", filename[flag].clone()).expect("insert file_name err!");
                flag += 1;
                temp_att.push(i);
            } else {
                break;
            }
        }

        self.attachment_body = temp_att;
        let attachment_body = self.attachment_body.clone();
        for all in attachment_body {
            let mut more_info = all.clone();
            let s_filename = all["file_name"].clone().to_string();
            let split_filename: Vec<&str> = s_filename.split('.').collect();
            let hash = u8_to_md5(all["data"].to_string().as_bytes().to_vec().clone());
            more_info["md5"] = hash.clone().into();
            more_info["suffix"] = split_filename[split_filename.len() - 1].clone().into();
            more_info["size"] = all["data"].to_string().as_bytes().len().into();
            temp_att_body.push(more_info);
        }
        self.attachment_body = temp_att_body;
    }

    /// 获取邮件主体
    /// 对邮件进行切分后的数量进行判断, 若只有一个体就直接解析, 有多个的话就进行迭代解析
    pub fn get_body(&mut self) {
        let mut temp_body: Vec<String> = Vec::new();
        let body = Mail::remove_boundary(self.head.boundary.clone(), self.all_body.clone()).clone();
        match body.len() {
            1 => {
                let result = self.get_part_body(body[0].to_string()).clone();
                temp_body = result.clone();
            }
            _ => {
                for item in body {
                    let result = self.get_part_body(item.clone()).clone();
                    if result[0].eq("not body") {
                        continue;
                    } else {
                        temp_body.push(result[0].clone());
                    }
                }
            }
        }
        self.final_body = temp_body.clone();
    }
}

/// 获取解码格式
/// * text: String
/// * 需要传入包含解码格式的字段
/// * 返回值为字符数组(解码格式, 是否可解)
/// * 解码格式other为在判断外的其他格式, none则是未发现解码格式
fn get_charset(text: String) -> (bool, &'static str) {
    let t1 = text.to_lowercase();
    return if t1.contains("utf-8") || t1.contains("utf8") {
        (true, "utf-8")
    } else if t1.contains("gb2312") {
        (true, "gb2312")
    } else if t1.contains("gbk") {
        (true, "gbk")
    } else if t1.contains("gb18030") {
        (true, "gb18030")
    } else if t1.contains("iso-8859-1") {
        (true, "iso-8859-1")
    } else if t1.contains("iso-8859-2") {
        (true, "iso-8859-2")
    } else if t1.contains("iso-8859-3") {
        (true, "iso-8859-3")
    } else if t1.contains("iso-8859-4") {
        (true, "iso-8859-4")
    } else if t1.contains("iso-8859-5") {
        (true, "iso-8859-5")
    } else if t1.contains("iso-8859-6") {
        (true, "iso-8859-6")
    } else if t1.contains("iso-8859-7") {
        (true, "iso-8859-7")
    } else if t1.contains("iso-8859-8") {
        (true, "iso-8859-8")
    } else if t1.contains("iso-8859-9") {
        (true, "iso-8859-9")
    } else if t1.contains("iso-8859-10") {
        (true, "iso-8859-10")
    } else if t1.contains("iso-8859-11") {
        (true, "iso-8859-11")
    } else if t1.contains("iso-8859-13") {
        (true, "iso-8859-13")
    } else if t1.contains("iso-8859-14") {
        (true, "iso-8859-14")
    } else if t1.contains("iso-8859-15") {
        (true, "iso-8859-15")
    } else if t1.contains("iso-8859-16") {
        (true, "iso-8859-16")
    } else {
        if t1.contains("charset") {
            (false, "other")
        } else {
            (false, "none")
        }
    };
}

/// 根据加密方式指定解码某一段文字
/// * charset: String, code: String, body: String
/// * 编码方式, 加密方式, 待解码解密的内容
/// * 返回值为解码后的String类型字符串
pub fn get_decode_method(charset: &str, code: &str, body: &str) -> String {
    let mut final_result = String::new();
    match code.to_lowercase().as_str() {
        "quoted-printable" | "q" => final_result = qp::decode(charset, body),
        "base64" | "b" => {
            let temp: Vec<&str> = body.trim().split("\r\n").collect();
            let mut text = temp.join("");
            text = text.replace(" ", "");
            final_result = base64::decode_code(text.to_string(), charset)
        }
        "" | "7bit" | "8bit" => {
            final_result = body.to_string()
        }
        // _ => println!("can't find decode method!")
        _ => ()
    }
    final_result
    // br_crypto::encoding::code_to_utf8(charset, final_result.as_bytes().to_vec())
}
