// use crate::MyError;
use crate::{IResult, JsonV};
use reqwest::header::{HeaderMap, HeaderValue};
// use reqwest::Method;
use serde::de::DeserializeOwned;
use std::time::Duration;

fn get_haeders() -> Result<HeaderMap, String> {
    let mut haeders = HeaderMap::new();
    haeders.insert(
        "User-Agent",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0"
            .parse::<HeaderValue>()
            .map_err(|e| e.to_string())?,
    );
    haeders.insert("Accept",
                   "text/html,application/xhtml+xml,application/xml;application/json;q=0.9,image/webp,*/*;q=0.8".parse::<HeaderValue>().map_err(|e|e.to_string())?);
    haeders.insert(
        "Accept-Language",
        "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2"
            .parse::<HeaderValue>()
            .map_err(|e| e.to_string())?,
    );
    // haeders.insert("Connection", "Close".parse()?);
    haeders.insert(
        "Cache-Control",
        "no-cache"
            .parse::<HeaderValue>()
            .map_err(|e| e.to_string())?,
    );
    Ok(haeders)
}

#[allow(dead_code)]
fn get_haeders2(body: &str) -> IResult<HeaderMap> {
    let mut haeders = get_haeders()?;
    haeders.insert("Content-Length", body.len().to_string().parse()?);
    Ok(haeders)
}

pub async fn post_json<T: DeserializeOwned>(url: String, json_v: JsonV) -> Result<T, String> {
    let res = reqwest::Client::new()
        .post(url.as_str())
        .json(&json_v)
        .headers(get_haeders()?)
        .timeout(Duration::from_secs(15))
        .send()
        .await
        .map_err(|e| e.to_string())?
        .json::<T>()
        .await
        .map_err(|e| e.to_string())?;
    Ok(res)
}

pub fn post_json_sync<T: DeserializeOwned>(url: String, json_v: JsonV) -> Result<T, String> {
    let head = get_haeders()?;
    let res = reqwest::blocking::Client::new()
        .post(url.as_str())
        .json(&json_v)
        .headers(head)
        .timeout(Duration::from_secs(15))
        .send()
        .map_err(|e| e.to_string())?
        .json::<T>()
        .map_err(|e| e.to_string())?;
    Ok(res)
}

pub async fn get_json<T: DeserializeOwned>(url: String) -> Result<T, String> {
    let head = get_haeders()?;
    let res = reqwest::Client::new()
        .get(url.as_str())
        .headers(head)
        .timeout(Duration::from_secs(15))
        .send()
        .await
        .map_err(|e| e.to_string())?
        .json::<T>()
        .await
        .map_err(|e| e.to_string())?;
    Ok(res)
}
pub fn get_json_sync<T: DeserializeOwned>(url: String) -> Result<T, String> {
    let res = reqwest::blocking::Client::new()
        .get(url.as_str())
        .headers(get_haeders()?)
        .timeout(Duration::from_secs(15))
        .send()
        .map_err(|e| e.to_string())?
        .json::<T>()
        .map_err(|e| e.to_string())?;
    Ok(res)
}

pub fn post_sync(url: String, body_str: String) -> crate::IResult<String> {
    let r = reqwest::blocking::Client::new()
        .post(url.as_str())
        .json(&serde_json::from_str::<JsonV>(&body_str).unwrap_or_default())
        .headers(get_haeders()?)
        .timeout(Duration::from_secs(15))
        .send()?
        .text()?;
    Ok(r)
}

/*#[test]
pub fn test_post_vec() {
    let body = r##"{"error_info":null,"data":{"data_id":null,"account_id":"96693efe7f3840e7b5c34cc90c33a9df","now_id":660,"type_title":"登录","created_datetime":"2020-12-23 12:08:59","error_info":null,"created_data":1608696539,"start_date":null,"end_date":null,"json_data":"正常"},"account":{"account_id":"96693efe7f3840e7b5c34cc90c33a9df","user_id":null,"company_name":null,"account_name":"91430105MA4LJQY047","account_password":"cszj131419","status":"帐户正常","last_get_data":null,"run_time":1608696509,"updated_time":1608696539,"created_time":1608696539}}"##;
    let r = post_json(
        "https://dsp.zgaic.com/fas/Tax/TaxpayerInformation".to_owned(),
        serde_json::from_str(body).unwrap(),
    )
    .await;
    println!("test_post_vec: {:?}", r);
}*/

pub async fn get(url: String) -> IResult<String> {
    let r = reqwest::Client::new()
        .get(&url)
        .headers(get_haeders()?)
        .send()
        .await?
        .text()
        .await?;
    Ok(r)
}

pub async fn get_vec(url: String) -> IResult<Vec<u8>> {
    let r = reqwest::Client::new()
        .get(&url)
        .headers(get_haeders()?)
        .send()
        .await?
        .bytes()
        .await?
        .to_vec();
    Ok(r)
}

pub fn get_vec_sync(url: String) -> IResult<Vec<u8>> {
    let r = reqwest::blocking::Client::new()
        .get(&url)
        .headers(get_haeders()?)
        .send()?
        .bytes()?
        .to_vec();
    Ok(r)
}

/*#[test]
fn test_get_vec() -> IResult<()> {
    use std::fs::File;
    use std::io::Write;
    let bytes =
        get_vec("https://necaptcha.nosdn.127.net/d0cee769c8fa476b957af7f222972f6c.jpg".to_owned())
            .await;
    let mut file = File::create("测试.jpg").map_err(|e| format!("新建图片错误: {:?}", e))?;
    file.write_all(bytes.as_slice())
        .map_err(|e| format!("下载图片[write_all]错误: {:?}", e))?;
    Ok(())
}*/
