import {invoke} from "@tauri-apps/api/tauri";
import {ref} from "vue";
import CommanDeffine from "./serportdefine.js";
import EventBus from "../eventBus.js";
import SerialportMethod  from "./SerialPort/SerialportMethod.js";
import { tr } from "element-plus/es/locales.mjs";
import { type } from "vue3-json-editor/dist/vue3-json-editor.cjs.js";
let sensorinfo={};
export  default {

    async onDevchange(){
        console.log(this.sensor_typeforset)

        SerialportMethod.Set_Dev_Type(this.sensor_typeforset);
        this.saveconfig();
        
    },

    async onshuttimechange(time){
        
        if(time ==this.lastshuttime&&this.caijiavgNumber==this.lastcaijiavgNumber) return;
        this.lastshuttime = time;
        this.lastcaijiavgNumber = this.caijiavgNumber;
        console.log(time);

       if(!this.SerialInfo.isopen)
       {
        console.log("串口未打开");
        return;
       }
         var Command={command:"set_shutter_time",shutter_time:Number(time)};
        let data={
            data:Command,
            datatype:"json"
        }
        let message=await invoke("sendtoport_andgetreturn",data);

        EventBus.emit('SetMenubutton', {name:"WR",state:"fail"});
        EventBus.emit('SetMenubutton', {name:"DC",state:"fail"});
        if (this.Devinfo.sensor_type!="IRIS-IS11")
            {
                this.UPStr="DN";
                EventBus.emit('setplotname',{up:"DN"});
            }

    },

    async showdataasup(datatoshow){
        let coeffweave1=this.Devinfo.bochangxishu.a0;
        let coeffweave2=this.Devinfo.bochangxishu.a1;
        let coeffweave3=this.Devinfo.bochangxishu.a2;
        let coeffweave4=this.Devinfo.bochangxishu.a3;
        let lenthofdata=datatoshow.data.length;
        let dataforshow=[];
        for (var i=0;i<lenthofdata;i++)
        {
            var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
            dataforshow.push([weave,datatoshow.data[i]]);
        }

        this.dataup=datatoshow;
        this.datainfoup.infolist=[];
        this.datainfoup.hasrecive=true;
        this.datainfoup.infolist.push({key:"intertime",value:datatoshow.shutter_time});
        //this.datainfoup.infolist.push({key:"序号",value:datatoshow.index});
       // this.datainfoup.infolist.push({key:"方向",value:datatoshow.direction});
        this.Senddatatoother(dataforshow,0);
    },
    async letmedosomething(Command){

        if (Command=="OPT")
        {
            await this.Dingbiao_OPT();
            this.GetoneData();
        }


        if(this.Devinfo.sensor_type=="IRIS-IS11")
        {
            return;
        }
        if (Command=="DC")
        {
            let r=true
            let has_shutter=false;
            if (typeof(this.Devinfo.has_shutter)!="undefined") 
            {
                has_shutter=this.Devinfo.has_shutter;
            }
               
            if (!has_shutter)
            {r= await confirm(' 请扣上遮光罩--》再点击确定');}
            
            if (r)
            {
                this.iscollecting=true;
           
                let datatoshow=await SerialportMethod.Get_Dark_Data("UP",this.ShutterTime[0],10);
                this.iscollecting=false;
               // this.showdataasup(datatoshow);
               this.GetoneData();
         
            }
           
        }
        if (Command=="WR")
        {
            this.iscollecting=true;
                    //获取波长系数
        
        let datatoshow=  await SerialportMethod.Get_Flat_Data("UP",this.ShutterTime[0],this.caijiavgNumber);
        // this.showdataasup(datatoshow)
        this.iscollecting=false;
        if (this.Devinfo.sensor_type!="IRIS-IS11")
        {
            this.UPStr="REF";
            EventBus.emit('setplotname',{up:"REF"});
        }
        this.GetoneData();





        }
        if (Command=="Save")
        {
            // if ( this.iscollecting) return;
            // await  this.GetoneData("",Number(this.caijiavgNumber));
            // var aa={
            //     code:"Space"

            // }
        //    await this.handlekeydown(aa);
        this.ContinueCelect(this.cajitimes);



        }
       
    },

    async listSerialPorts() {

        let that=this;
        var i=0;
        //var aa=await invoke("getportnames");
        invoke("getportnames").then((message) => {
            message.forEach(function (port) {
                console.log(port.path);
                that.options.push({value:port,label:port,index:i++})
            })

        });





    },
    async initserialport() {
        if (this.Comname == "请选择") {
            alert("请选择串口");
            return
        }
        var selectitem = document.getElementById("selectitem");
        var btn = document.getElementById("opencom");

        //禁用
        selectitem.disabled = true;
        var btnn = document.getElementById("closecomeside");
        btnn.disabled = false;
        this.cssme.comportvariant = "success";

        // let buffer = Buffer.alloc(0);
        let portinfo ={
            portname: this.Comname,
            // baudrate: 115200,
            baudrate: 921600,
        }
        let ret= await invoke("opencom",portinfo);
        if (ret!="Port is open")
        {
            EventBus.emit('showbox',{title:"设备",body:"打开串口失败"});
            return
        }


       var isopen=await this.GetSenSorInfo();
        this.SerialInfo.isopen=isopen;
        if (isopen)
        {
            btn.disabled = true;
            this.buttoncolor.opencombutton="success";
            EventBus.emit('showbox',{title:"设备",body:"打开串口成功"});
            this.$globalState.isDevOpen=true;
        }else
        {
            btn.disabled = false;
            EventBus.emit('showbox',{title:"设备",body:"打开串口失败,请更换串口 或者检查设备是否连接"});
        }



       // alert("打开串口成功");
    },
    async closecomport() {
        var btn = document.getElementById("opencom");
        btn.disabled = false;
        this.buttoncolor.opencombutton="light";
        var btnn = document.getElementById("closecomeside");
        btnn.disabled = true;
        alert(await invoke("closecome"));
        this.SerialInfo.isopen=false;
        this.$globalState.isDevOpen=false;
      


    },
    async Dingbiao_OPT(){


        this.iscollecting=true;

        this.ShutterTime[0]=await SerialportMethod.Dev_Opt();
        this.ShutterTime[1]=this.ShutterTime[0];
        this.iscollecting=false;
        EventBus.emit('SetMenubutton', {name:"WR",state:"fail"});
        EventBus.emit('SetMenubutton', {name:"DC",state:"fail"});

    },
    async GetoneData(event,caijiavgNumber=1){
        let caijimoshi=this.Devinfo.work_mode;
        if (caijimoshi=="manual_mode") {
            await this.GetoneDataall();
        }
        if (caijimoshi=="advanced_mode")
        {
            if (this.caijidirection=="UP")
            {
                await this.GetDataDrection("UP",caijiavgNumber);
                await  delay(100)

            }
            if (this.caijidirection=="DOWN")
               { await this.GetDataDrection("DOWN",caijiavgNumber);
                await  delay(100)
               }
            
            if (this.caijidirection=="ALL")
            {
                await this.GetDataDrection("UP",caijiavgNumber);
                await  delay(100)
                await this.GetDataDrection("DOWN",caijiavgNumber);
                await  delay(100)
            }
            if(this.caijidirection=="DARK")
            {
                await this.GetDataDrection("DARK",caijiavgNumber);
                await  delay(100)
            }
            if(this.caijidirection=="RAD_UP")
            {
                await this.GetDataDrection("RAD_UP",caijiavgNumber);
                await  delay(100)
            }
            if(this.caijidirection=="RAD_DOWN")
            {
                await this.GetDataDrection("RAD_DOWN",caijiavgNumber);
                await  delay(100)
            }
            if(this.caijidirection=="REF")
            {
                await SerialportMethod.Get_Date_on_Derction("UP",this.ShutterTime[0],this.autoremovedark,caijiavgNumber);
                await SerialportMethod.Get_Date_on_Derction("DOWN",this.ShutterTime[1],this.autoremovedark,caijiavgNumber);
                let  dataforshowup=await SerialportMethod.Get_Data_from_dev("REF");
                this.showdataasup(dataforshowup);

            }


        }


    },
    async GetDataDrection(drection,avgnumber=1){
        this.iscollecting=true;
        var shuttertimes=1;
        if (drection=="UP"|| drection == "RAD_UP")
        {
            shuttertimes=Number(this.ShutterTime[0]);
        }else if (drection=="DOWN" || drection == "RAD_DOWN")
        {
            shuttertimes=Number(this.ShutterTime[1]);

        }else if(drection=="DARK")
        {
            shuttertimes=Number(this.ShutterTime[0]);
        }



        //获取波长系数
        let coeffweave1=this.Devinfo.bochangxishu.a0;
        let coeffweave2=this.Devinfo.bochangxishu.a1;
        let coeffweave3=this.Devinfo.bochangxishu.a2;
        let coeffweave4=this.Devinfo.bochangxishu.a3;
        //获取数据 UPDN


        let datatoshow=await SerialportMethod.Get_Date_on_Derction(drection,shuttertimes,this.autoremovedark,avgnumber);
       
        if (this.dataprocessconfig.useSG)
        {
           datatoshow.data= await invoke("sg_smooth",{data:datatoshow.data,window:31,order:7});
          // console.log(smooth);
        }
        if (this.dataprocessconfig.usehighpass)
        {
            datatoshow.data=await invoke("gaussian_filter_high",{data:datatoshow.data,sigma:30});
            //console.log(aaa);
        }



        let lenthofdata=datatoshow.data.length;
        var temp=[];
        // for (var i=0;i<lenthofdata;i++)
        // {
        //     temp.push(datatoshow.data[2047-i])
        // }
        // datatoshow.data=temp;



        let dataforshow=[];
        for (var i=0;i<lenthofdata;i++)
        {
            var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
            dataforshow.push([weave,datatoshow.data[i]]);
        }
        if (drection=="UP" || drection == "RAD_UP")
        {
            this.dataup=datatoshow;
            this.datainfoup.infolist=[];
            this.datainfoup.hasrecive=true;
            this.datainfoup.infolist.push({key:"intertime",value:datatoshow.shutter_time});
           // this.datainfoup.infolist.push({key:"序号",value:datatoshow.index});
           // this.datainfoup.infolist.push({key:"方向",value:datatoshow.direction});
            this.Senddatatoother(dataforshow,0);
        }else if (drection=="DOWN" || drection == "RAD_DOWN"){
            this.datadown=datatoshow;
            this.datainfodown.hasrecive=true;
            this.datainfodown.infolist=[];
            this.datainfodown.infolist.push({key:"intertime",value:datatoshow.shutter_time});
           // this.datainfodown.infolist.push({key:"序号",value:datatoshow.index});
           // this.datainfodown.infolist.push({key:"方向",value:datatoshow.direction});
            this.Senddatatoother(dataforshow,1);
        }
        if (drection=="DARK"){
            this.dataup=datatoshow;
            this.datainfoup.infolist=[];
            this.datainfoup.hasrecive=true;
            this.datainfoup.infolist.push({key:"intertime",value:datatoshow.shutter_time});
            //this.datainfoup.infolist.push({key:"序号",value:datatoshow.index});
           // this.datainfoup.infolist.push({key:"方向",value:datatoshow.direction});
            this.Senddatatoother(dataforshow,0);
        }


        this.iscollecting=false;




    },
    async EnsureNotWorking(){
        let data={
            data:{
                command:"get_caiji_state"
            },
            datatype:"json"
        }
        let message=await invoke("sendtoport_andgetreturn",data);
        let ret=JSON.parse(message.content);

        while (ret.caiji_state!="finish")
        {

            //发送进度信息
            let dataforprocess={
                percent:ret.percent,
                info:ret.info
            }
            EventBus.emit('setprogressbar',dataforprocess);
            await delay(100);
            message=await invoke("sendtoport_andgetreturn",data);

            if (message.content=="g time no data retrun")
            {
                alert("长时间没有数据返回");
                return;
            }
            ret=JSON.parse(message.content);

        }
        let dataforprocess={
            percent:100,
            info:""
        }
        EventBus.emit('setprogressbar',dataforprocess);

    },
    async GetoneDataall(){
        this.iscollecting=true;
        var Command={command:"take_one_job"};
        let data={
            data:Command,
            datatype:"json"
        }
        if (1)
        {
            /////////////////////////////////////////////
            let message =await invoke("sendtoport",data);
            let data2={
                commanid:0x00,
                waitTimeJson:1
            }
            let message2=await invoke("readformport",data2);
            await delay(500);
            await this.EnsureNotWorking();
            await invoke("clearportbuff");

        }

        //获取波长系数
        let coeffweave1=this.Devinfo.bochangxishu.a0;
        let coeffweave2=this.Devinfo.bochangxishu.a1;
        let coeffweave3=this.Devinfo.bochangxishu.a2;
        let coeffweave4=this.Devinfo.bochangxishu.a3;
        let bandnum=this.Devinfo.bandnum;
        //获取数据 UPDN
        data = {
            data: {
                command: "get_data",
                return_data_type: CommanDeffine.DataTypeforSend.UpDN
            },
            datatype: "json"
        }
       let message1=await invoke("sendtoport_andgetreturn",data);
        while (message1.datatype!=0x02)
        {
            message1=await invoke("sendtoport_andgetreturn",data);
        }

        let datatoshowup=message1.data;
        this.dataup=datatoshowup;
        let lenthofdataup=datatoshowup.data.length;
        let dataforshowup=[];
        
        for (var i=0;i<lenthofdataup;i++)
        {
            var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
            dataforshowup.push([weave,datatoshowup.data[bandnum-i-1]]);
        }
        this.datainfoup.infolist=[];
        this.datainfoup.hasrecive=true;

        this.datainfoup.infolist.push({key:"intertime",value:datatoshowup.shutter_time});
       // this.datainfoup.infolist.push({key:"序号",value:datatoshowup.index});
       // this.datainfoup.infolist.push({key:"方向",value:datatoshowup.direction});
        //this.datainfoup.data.push({key:"温度",value:dataforshowup.temperature[0]});

        // this.datainfoup.data.push("序号",dataforshowup.index);

        // this.datainfoup.data.push("方向",dataforshowup.direction);
       // this.datainfoup.data.push("温度",dataforshowup.temperature[0]);



        this.Senddatatoother(dataforshowup,0);

        data = {
            data: {
                command: "get_data",
                return_data_type: CommanDeffine.DataTypeforSend.DOWNDN
            },
            datatype: "json"
        }
        let messagedown=await invoke("sendtoport_andgetreturn",data);
        while (messagedown.datatype!=0x02)
        {
            messagedown=await invoke("sendtoport_andgetreturn",data);
        }
        let datatoshowdown=messagedown.data;
        this.datadown=datatoshowdown;
        let lenthofdatadown=datatoshowdown.data.length;
        let dataforshowdown=[];
        for (var i=0;i<lenthofdatadown;i++)
        {
            var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
            dataforshowdown.push([weave,datatoshowdown.data[bandnum-i-1]]);
        }
        this.datainfodown.hasrecive=true;
        this.datainfodown.infolist=[];
        this.datainfodown.infolist.push({key:"intertime",value:datatoshowdown.shutter_time});
       // this.datainfodown.infolist.push({key:"序号",value:datatoshowdown.index});
       // this.datainfodown.infolist.push({key:"方向",value:datatoshowdown.direction});
        //this.datainfodown.data.push("序号",datatoshowdown.index);
        //this.datainfodown.data.push("方向",datatoshowdown.direction);
        //this.datainfodown.data.push("温度",datatoshowdown.temperature[0]);
        this.Senddatatoother(dataforshowdown,1);

        this.iscollecting=false;



        //获取数据






    },
    Senddatatoother( data,index){
        let methodslist = this.methodslist;
        if (methodslist.length == 0) {
            return;
        }
        for (var i=0;i<methodslist.length;i++)
        {
            methodslist[i](data,index);
        }


        // foteach(methodslist, function (index, item) {
        //         item.method(data);
        // });
    },
    async GetSenSorInfo(){
        var Command={command:"get_sensor_info"};
        let data={
            data:Command,
            datatype:"json"
        }
        let that = this;
        // let message=await invoke("sendtoport_andgetreturn",data);
        // if (message.datatype==108)
        // {
        //     return false;
        // }
        // let json=JSON.parse(message.content);
        let json = await SerialportMethod.Get_Device_Info();
        this.Devinfo=json;
        let aaa=typeof(this.Devinfo.sensor_type);
        if (aaa=="undefined")
        {
            this.Devinfo.sensor_type="IRIS-IS11";
            this.Devinfo.fiber_type="Dual";
        }

        if (this.Devinfo.sensor_type=="IRIS-Sensor")
        {
            this.UPStr="DN"
            EventBus.emit('setplotname',{up:"DN"});
            if(typeof(this.Devinfo.fiber_type)=="undefined")
            {
                this.Devinfo.fiber_type="Single";
            }

           

        }else
        {
            EventBus.emit('setplotname',{up:"UP",down:"DOWN"});
        }
        this.datainfoup.header=this.UPStr

        //获取波长系数
        let coeffweave1=this.Devinfo.bochangxishu.a0;
        let coeffweave2=this.Devinfo.bochangxishu.a1;
        let coeffweave3=this.Devinfo.bochangxishu.a2;
        let coeffweave4=this.Devinfo.bochangxishu.a3;
        let BANDNUM=this.Devinfo.bandnum;
        var wevaconfig={
            min:coeffweave1*0*0*0+coeffweave2*0*0+coeffweave3*0+coeffweave4,
            max:coeffweave1*(BANDNUM-1)*(BANDNUM-1)*(BANDNUM-1)+coeffweave2*(BANDNUM-1)*(BANDNUM-1)+coeffweave3*(BANDNUM-1)+coeffweave4

        }
        EventBus.emit('plotsetwavelength',wevaconfig);

        this.Devinfo.SerilNumber=json.serialnumber;
        if (json.caiji_mode==1) {
            this.Devinfo.Caji_mode = "连续采集";
        }else{
            this.Devinfo.Caji_mode = "单次采集";
        }
        this.Devinfo.name=json.name;
        this.Devinfo.Version=json.version;
        switch (json.return_data_type) {
            case 0x10:
                this.Devinfo.Datatype="DN/Dark";
                break;
            case 0x00:
                this.Devinfo.Datatype="DN";
                break;
            case 0x01:
                this.Devinfo.Datatype="Radiance";
                break;
            case 0x11:
                this.Devinfo.Datatype="Radiance/Dark";
                break;
            case 0x30:
                this.Devinfo.Datatype="Dark";
                break;
            default:
                this.Devinfo.Datatype="未知";
                break;
        }
        this.devinfoshow.infolist=[];
        this.devinfoshow.infolist.push({key:"设备名称",value:this.Devinfo.name});
      //  this.devinfoshow.infolist.push({key:"设备序列号",value:this.Devinfo.SerilNumber});
        //this.devinfoshow.infolist.push({key:"采集模式",value:this.Devinfo.Caji_mode});
       // this.devinfoshow.infolist.push({key:"数据类型",value:this.Devinfo.Datatype});
        return true;
    }
}
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
