use std::fmt::format;

use chrono::Datelike;
use chrono::Timelike;
use serde_json::json;

use crate::myformatiris::structures::*;
use crate::myformatiris::read::*;
use crate::myformatiris::write::*;


 pub fn savecalibratefileIRIS(Gain:serde_json::Value,direction: bool, filepath: String, dndata: serde_json::Value, lampdata: serde_json::Value, devinfo: serde_json::Value) -> String {
    //输出 输入参数
    //println!("Gain: {:?}", Gain);
    // println!("direction: {:?}", direction);
    // println!("Filepath: {:?}", devinfo);
    // println!("DNData: {:?}", dndata);
    // println!("Lampdata: {:?}", lampdata);
    // println!("Devinfo: {:?}", devinfo);
    let mut oneirisdata:OneIRISData = OneIRISData::new();
    let mut spectraldatagain: SpectralData= SpectralData::new();
    spectraldatagain.name= devinfo["name"].as_str().unwrap_or("Unknown").to_string()+&"_".to_string()+&devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string()+&"_gain".to_string();
    spectraldatagain.sensor_id= devinfo["name"].as_str().unwrap_or("Unknown").to_string()+&devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string();
    spectraldatagain.bands= devinfo["bands"].as_u64().unwrap_or(0) as u16;
    spectraldatagain.pixel_size=8;
    spectraldatagain.data_type=DATA_TYPE_FLOAT64;
    spectraldatagain.fiber_id=direction as u8;
    spectraldatagain.exposure=Gain["shutter_time"].as_u64().unwrap_or(0) as f64;
    spectraldatagain.gain=Gain["sensor_gain"].as_f64().unwrap_or(1.0) as f32;
    let datenow = chrono::Local::now();
    let nowtiem= TimeStruct {

        time_zone:50,
        year:datenow.year() as u16,
        month:datenow.month() as u8,
        day:datenow.day() as u8,
        hour:datenow.hour() as u8,
        minute:datenow.minute() as u8,
        second:datenow.second() as u8,
        millisecond:datenow.timestamp_subsec_millis() as u16,
    };
    spectraldatagain.collection_time=nowtiem.clone();
    spectraldatagain.ground_type=Target_Spectral_Type_CaliFile_Gain;
    spectraldatagain.valid_flag=1;
    let spectraldatavec:Vec<f64>=Gain["Data"].as_array().unwrap_or(&vec![]).iter()
        .map(|x| x.as_f64().unwrap_or(0.0))
        .collect::<Vec<f64>>();
    spectraldatagain.Set_Spectral_Data(spectraldatavec, DATA_TYPE_FLOAT64);
        println!("spectraldata.name: {:?}", spectraldatagain.name);
    oneirisdata.spectral_data_section.push(spectraldatagain);
    let mut spectraldata_dn: SpectralData= SpectralData::new();
    spectraldata_dn.name= devinfo["name"].as_str().unwrap_or("Unknown").to_string()+&"_".to_string()+&devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string()+&"_dn".to_string();
    spectraldata_dn.sensor_id= devinfo["name"].as_str().unwrap_or("Unknown").to_string()+&devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string();
    spectraldata_dn.bands= devinfo["bands"].as_u64().unwrap_or(0) as u16;
    spectraldata_dn.pixel_size=8;
    spectraldata_dn.fiber_id=direction as u8;
    spectraldata_dn.exposure=dndata["shutter_time"].as_u64().unwrap_or(0) as f64;
    spectraldata_dn.gain=dndata["gain"].as_f64().unwrap_or(1.0) as f32;
    spectraldata_dn.data_type=DATA_TYPE_FLOAT64;
    spectraldata_dn.collection_time=nowtiem.clone();
    spectraldata_dn.ground_type=Target_Spectral_Type_DN;
    spectraldata_dn.valid_flag=1;
    let spectraldatavec_dn:Vec<f64>=dndata["data"].as_array().unwrap_or(&vec![]).iter()
        .map(|x| x.as_f64().unwrap_or(0.0))
        .collect::<Vec<f64>>();
    spectraldata_dn.Set_Spectral_Data(spectraldatavec_dn, DATA_TYPE_FLOAT64);
    println!("spectraldata_dn.name: {:?}", spectraldata_dn.name);
    oneirisdata.spectral_data_section.push(spectraldata_dn);
    let mut spectraldata_lamp: SpectralData= SpectralData::new();
    let lampvalue= lampdata["value_lable"].as_str().unwrap_or("Unknown");
    let datalabel= lampdata["data_value"].as_str().unwrap_or("Unknown");
    spectraldata_lamp.name= devinfo["name"].as_str().unwrap_or("Unknown").to_string()+&"_".to_string()+&devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string()+&"_lamplable_".to_string()+&lampvalue.to_string()+&"_datalabel_".to_string()+&datalabel.to_string();
    spectraldata_lamp.sensor_id= devinfo["name"].as_str().unwrap_or("Unknown").to_string()+&devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string();
    let lampvalue_f64_vec= lampdata["data"].as_array().unwrap_or(&vec![]).iter()
        .map(|x| x.as_f64().unwrap_or(0.0))
        .collect::<Vec<f64>>();
    spectraldata_lamp.Set_Spectral_Data(lampvalue_f64_vec, DATA_TYPE_FLOAT64);
    spectraldata_lamp.ground_type=Target_LAMP_VALUE_SCALED;
    oneirisdata.spectral_data_section.push(spectraldata_lamp);

    let spectraldata_devinfo= json!(
        {
            "info_type": "devinfo", // 0 for device info
            "sensor_id": devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string(),
            "wave_coeff": { 
                "a1": devinfo["bochangxishu"]["a1"].as_f64().unwrap_or(0.0),
                "a2": devinfo["bochangxishu"]["a2"].as_f64().unwrap_or(0.0),
                "a3": devinfo["bochangxishu"]["a3"].as_f64().unwrap_or(0.0),
                "a4": devinfo["bochangxishu"]["a4"].as_f64().unwrap_or(0.0)
            }

        }
    );
    let environment_info= json!(
        {
            "info_type": "environment", // 1 for environment info
            "date": format!("{}-{:02}-{:02} {:02}:{:02}:{:02}", 
                datenow.year(), 
                datenow.month(), 
                datenow.day(), 
                datenow.hour(), 
                datenow.minute(), 
                datenow.second()
            ),
        
            
        }
    );
     /*
        let spectraldata_devinfo= json!(
        {
           "info_type": "infolist", // 0 for device info
           "info_number":3,
           "info_list": [
                {
                    "info_type": "devinfo", // 0 for device info
                    "sensor_id": "is30002",
                    "bandnum": 2048,
                    "wave_coeff": { 
                        "a1": 0.0,
                        "a2": 0.0,
                        "a3":  400,
                        "a4": 1.0
                    }
                },
                {
                    "info_type": "environment", // 1 for gain info
                    "date": "2000-01-00 00:00:00",
                    //下面可选
                    "humidity":90.0,
                    "temperature":35.0 ,
                    "gps":{
                        "latitude":115.01,
                        "longitude": 39.01,
                        "altitude": 100.0
                    },
                },
                {
                    "info_type": "devinfo", // 0 for device info
                    "sensor_id": "is20001",
                    "bandnum": 512,
                    "wave_coeff": { 
                        "a1": 0,
                        "a2": 0.0,
                        "a3":390,
                        "a4": 4
                    }
                }
            ]

        }
    );
     */
    
    // spectraldata_devinfo.sensor_id=devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string();
    // spectraldata_devinfo.wave_coeff[0]=devinfo["bochangxishu"]["a1"].as_f64().unwrap_or(0.0);
    // spectraldata_devinfo.wave_coeff[1]=devinfo["bochangxishu"]["a2"].as_f64().unwrap_or(0.0);
    // spectraldata_devinfo.wave_coeff[2]=devinfo["bochangxishu"]["a3"].as_f64().unwrap_or(0.0);
    // spectraldata_devinfo.wave_coeff[3]=devinfo["bochangxishu"]["a4"].as_f64().unwrap_or(0.0);

    oneirisdata.spectral_info_section.push(spectraldata_devinfo);
    oneirisdata.spectral_info_section.push(environment_info);

// 修复后的代码
let filesave_date = format!("{}_{:04}{:02}{:02}", 
    filepath, // 如果 filepath 是 String，这里会自动借用
    datenow.year(), 
    datenow.month(), 
    
    datenow.day()
);
let filesavepath=filesave_date.clone()+".iris";

    wirte_iris_data(&oneirisdata, &filesavepath);


    
    








    "ok".to_string()
    
}

pub fn save_reflectance_to_iris(reflectance_data: serde_json::Value, devinfo: serde_json::Value, filepath: String) -> String {
    let mut oneirisdata: OneIRISData = OneIRISData::new();
    let mut spectraldata_reflectance: SpectralData = SpectralData::new();
    
    let fileName = reflectance_data["fileName"].as_str().unwrap_or("Unknown").to_string();
    //将filename中的.替换为_ 并保存到新的变量里
    let fileName1 = fileName.replace(".", "_");
    spectraldata_reflectance.name = fileName1+&devinfo["name"].as_str().unwrap_or("Unknown").to_string()  ;
    spectraldata_reflectance.sensor_id = devinfo["sensor_id"].as_str().unwrap_or("Unknown").to_string() ;
        // + &devinfo["serialnumber"].as_str().unwrap_or("Unknown").to_string();
    
    let reflectance_values: Vec<f64> = reflectance_data["data"]
        .as_array()
        .unwrap_or(&vec![])
        .iter()
        .map(|x| x.as_f64().unwrap_or(0.0))
        .collect::<Vec<f64>>();
    
    spectraldata_reflectance.bands = reflectance_values.len() as u16;
    spectraldata_reflectance.pixel_size = 8;
    spectraldata_reflectance.data_type = DATA_TYPE_FLOAT64;
    spectraldata_reflectance.fiber_id = 0;
    spectraldata_reflectance.exposure = 0.0;
    spectraldata_reflectance.gain = 0.0;
    
    let datenow = chrono::Local::now();
    let nowtime = TimeStruct {
        time_zone: 50,
        year: datenow.year() as u16,
        month: datenow.month() as u8,
        day: datenow.day() as u8,
        hour: datenow.hour() as u8,
        minute: datenow.minute() as u8,
        second: datenow.second() as u8,
        millisecond: datenow.timestamp_subsec_millis() as u16,
    };
    spectraldata_reflectance.collection_time = nowtime.clone();
    spectraldata_reflectance.ground_type = Target_Spectral_Type_FlatRef;
    spectraldata_reflectance.valid_flag = 1;
    
    spectraldata_reflectance.Set_Spectral_Data(reflectance_values, DATA_TYPE_FLOAT64);
    oneirisdata.spectral_data_section.push(spectraldata_reflectance);
    
    let spectraldata_devinfo = json!({
        "info_type": "devinfo",
        "sensor_id": devinfo["sensor_id"].as_str().unwrap_or("Unknown").to_string(),
        "wave_coeff": {
            "a1": devinfo["bochangxishu"]["a0"].as_f64().unwrap_or(0.0),
            "a2": devinfo["bochangxishu"]["a1"].as_f64().unwrap_or(0.0),
            "a3": devinfo["bochangxishu"]["a2"].as_f64().unwrap_or(0.0),
            "a4": devinfo["bochangxishu"]["a3"].as_f64().unwrap_or(0.0)
        }
    });
    println!("spectraldata_devinfo: {:?}", spectraldata_devinfo);
    
    let environment_info = json!({
        "info_type": "environment",
        "date": format!("{}-{:02}-{:02} {:02}:{:02}:{:02}", 
            datenow.year(), 
            datenow.month(), 
            datenow.day(), 
            datenow.hour(), 
            datenow.minute(), 
            datenow.second()
        )
    });
    
    oneirisdata.spectral_info_section.push(spectraldata_devinfo);
    oneirisdata.spectral_info_section.push(environment_info);
    
    match wirte_iris_data(&oneirisdata, &filepath) {
        Ok(_) => "ok".to_string(),
        Err(e) => format!("保存失败: {}", e)
    }
}