import {dialog, fs} from "@tauri-apps/api";
import {invoke} from "@tauri-apps/api/tauri";
import * as echarts from "echarts";
import {exit} from "@tauri-apps/api/process";
import EventBus from "../eventBus.js";
import eventBus from "../eventBus.js";
import { en } from "element-plus/es/locales.mjs";

export default {

    async saveconfig(){
        var configdata=await  fs.readTextFile("./config.json");
        configdata=JSON.parse(configdata);
        configdata.Filename=this.Filename;
        configdata.pathofsave=this.pathofdir;
        configdata.caijiavgNumber=this.caijiavgNumber;
        configdata.useSG=this.dataprocessconfig.useSG;
        configdata.usehighpass=this.dataprocessconfig.usehighpass;
        configdata.Dispatcher=this.Dispatcher;
        configdata.sensor_typeforset=this.sensor_typeforset;
        fs.writeFile("config.json", JSON.stringify(configdata));
        EventBus.emit('showbox', {title: "系统", body: "保存配置成功",interval:10});
        this.isSpecialmodeshow=true;
    },
    async filenamechange(){
        var maxn=await this.findmaxNinpath(this.pathofdir);
        this.Pathtosave=this.pathofdir+"/"+this.Filename+this.nowNumber+".csv";
    },
    async choosesavepath(){
        // var path = require('path');
        // var dialog = require('@electron/remote').dialog;
        // this.pathofdir= dialog.showOpenDialogSync({
        //     title: "请选择保存路径",
        //     properties: ['openDirectory'],
        // })[0];
        var options= {
            defaultPath: "../",
            directory: true,
            title: "请选择保存路径",
        }
        this.pathofdir=await dialog.open(options);
        var configdata=await  fs.readTextFile("./config.json");
        configdata=JSON.parse(configdata);
        configdata.Filename=this.Filename;
        configdata.pathofsave=this.pathofdir;
        fs.writeFile("config.json", JSON.stringify(configdata));
        var maxn=await this.findmaxNinpath(this.pathofdir);
        this.Pathtosave=this.pathofdir+"/"+this.Filename+this.nowNumber+".csv";
    },
    createAndDownloadFile(fileName, content) {
    // 创建一个 a 标签
    var aTag = document.createElement('a');
    // 创建一个 Blob 对象
    var blob = new Blob([content]);
    // 设置下载的文件名
    aTag.download = fileName;
    // 创建一个临时的 URL 指向 Blob 对象
    aTag.href = URL.createObjectURL(blob);
    // 模拟 a 标签的点击事件，触发下载
    aTag.click();
    // 释放创建的临时 URL 资源
    URL.revokeObjectURL(blob);
},
    async ContinueCelect(times){
        if(times==-1) {
            this.continuecaiji=!this.continuecaiji;
            if (this.continuecaiji==false)
                {
                    EventBus.emit('showbox', {title: "系统", body: "采集将在当前数据采集完成后停止",interval:10});
                    return
                }
        }

        if (this.continuecaiji) {
            while (this.continuecaiji) {

                //获取当前时间
                let isuseDispatcher=this.Dispatcher.isenable;
                if (isuseDispatcher)
                {

                    let datenow=new Date();
                    let hour=datenow.getHours();
                    let datanownumber=hour*60+datenow.getMinutes();
                    let begintimestr=this.Dispatcher.begin;
                    let endtimestr=this.Dispatcher.end;
                    let begintime=Number(begintimestr.split(":")[0])*60+Number(begintimestr.split(":")[1]);
                    let endtime=Number(endtimestr.split(":")[0])*60+Number(endtimestr.split(":")[1]);
                    
                    if (datanownumber>endtime||datanownumber<begintime)
                    {
                 
           
                                await delay(1000);
                                let dataforprocess={
                                    percent:100,
                                    info:"不在采集时间段内"
                                }
                                EventBus.emit('setprogressbar',dataforprocess);
                         
                            
                        continue;
                    }


                }


                
                


                await  this.GetoneData("",Number(this.caijiavgNumber));
                var aa={code:"Space"}
                if(this.continuessave)
                {                await this.handlekeydown(aa);
                    await delay(50);
                }

                // if (this.cajitimesjiange>0)
                //     await delay(this.cajitimesjiange*1000-50);
                //等待期间每一秒检查一次是否停止
                let temp=0;
                this.iscollecting=true;
                while(temp<this.cajitimesjiange&&this.continuecaiji)
                {
                    await delay(1000);
                    let dataforprocess={
                        percent:temp/this.cajitimesjiange*100,
                        info:"等待下次采集"
                    }
                    EventBus.emit('setprogressbar',dataforprocess);
                    temp++;
                }
                this.iscollecting=false;

            }

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

            return;

        }

        for (var i=0;i<times;i++)
        {

            await  this.GetoneData("",Number(this.caijiavgNumber));
            var aa={
                code:"Space"

            }
           await this.handlekeydown(aa);
            await delay(50);
            // if (this.cajitimesjiange>0)
            // await delay(this.cajitimesjiange*1000-50);
            let temp=0;
            while(temp<this.cajitimesjiange)
            {
                await delay(1000);
                let dataforprocess={
                    percent:temp/this.cajitimesjiange*100,
                    info:"等待下次采集"
                }
                EventBus.emit('setprogressbar',dataforprocess);
                temp++;
            }
        }
        EventBus.emit('showbox', {title: "系统", body: "采集"+times+"次数据完成",interval:10});

    },
    async handlekeydown(event){
       // console.log(event.code)

        if (event.code=="Space"){
            if(this.iscollecting) {
                eventBus.emit('showbox', {title: "系统", body: "正在采集数据，请稍后再试",interval:10});
                return
            }
            //datatosave 保存
            console.log(this.datatosave)
            var data={};
            if (this.caijidirection=="UP"||this.caijidirection=="DARK"||this.caijidirection=="RAD_UP")
            {
                data =this.dataup;
            }else {
                data =this.datadown;
            }
            var lenthofdataup=data.data.length;

            let coeffweave1=this.Devinfo.bochangxishu.a0;
            let coeffweave2=this.Devinfo.bochangxishu.a1;
            let coeffweave3=this.Devinfo.bochangxishu.a2;
            let coeffweave4=this.Devinfo.bochangxishu.a3;
            var strcsv=""
            var strchogncaiyang="";
            var xValues = []





            for (var i=0;i<lenthofdataup;i++)
            {
                var weave=coeffweave1*i*i*i+coeffweave2*i*i+coeffweave3*i+coeffweave4;
                xValues.push(weave);

            }



            var lenth=xValues.length;
            var yValues = []
            var yvalues2=[];
            if (this.Devinfo.work_mode!="advanced_mode"||this.caijidirection=="ALL")
            {
                var dataup=this.dataup;
                var datadown=this.datadown;
                var dateup=(this.dataup.year+2000)+"-"+this.dataup.month+"-"+this.dataup.day+" "+this.dataup.hour+":"+this.dataup.minute+":"+this.dataup.second;
                strcsv+="Date_up,"+dateup+"\r\n";
                
                
                var date=(this.datadown.year+2000)+"-"+this.datadown.month+"-"+this.datadown.day+" "+this.datadown.hour+":"+this.datadown.minute+":"+this.datadown.second;
                strcsv+="Date_down,"+date+"\r\n";
                if(typeof this.dataup.temprature!="undefined")
                {
                    let temperaturestrup="Temperature_up,"
                    +this.dataup.temprature[0]+","+this.dataup.temprature[1]+","
                    +this.dataup.temprature[2]+","+this.dataup.temprature[3]+","
                    +this.dataup.temprature[4]+","+this.dataup.temprature[5]+","
                    +this.dataup.temprature[6]+","+this.dataup.temprature[7]+"\r\n";
                    strcsv+=temperaturestrup;
                }
                if(typeof this.datadown.temprature!="undefined")
                {
                    let temperaturesdown="Temperature_down,"
                    +this.datadown.temprature[0]+","+this.datadown.temprature[1]+","
                    +this.datadown.temprature[2]+","+this.datadown.temprature[3]+","
                    +this.datadown.temprature[4]+","+this.datadown.temprature[5]+","
                    +this.datadown.temprature[6]+","+this.datadown.temprature[7]+"\r\n";
                    strcsv+=temperaturesdown;
                    let datatype="DataType,"+this.dataup.datatype+"\r\n";
                }
      






                strcsv+="Weavelenth,upDN,downDN,upshutter,"+dataup.shutter_time
                    +",downshutter,"+datadown.shutter_time+",index,"+dataup.index+"\r\n";
                strchogncaiyang="Weavelenth,upDN,downDN,upshutter,"+dataup.shutter_time+",downshutter,"+datadown.shutter_time+",index,"+dataup.index+"\r\n";
                var lenthofdataup=dataup.data.length;
                for (var i=0;i<lenthofdataup;i++)
                {

                        
                  
                    

                    if(this.Devinfo.name=="IRIS-IS11")
                        {
                    yValues.push(dataup.data[lenthofdataup-i-1]);
                    yvalues2.push(datadown.data[lenthofdataup-i-1]);
                }
                else{
                    yValues.push(dataup.data[i]);
                    yvalues2.push(datadown.data[i]);
                }
                }
                if (this.outputconfig.isChongCaiyang)
                {
                    let aaa= await  invoke("interpolate_spline",{x:xValues,y:yValues,step:this.outputconfig.ChongCaiyanginterval})
                    let bbb= await  invoke("interpolate_spline",{x:xValues,y:yvalues2,step:this.outputconfig.ChongCaiyanginterval})

                    var lenthofdataup=aaa.length;
                    for (var i=0;i<lenthofdataup;i++)
                    {
                        strchogncaiyang+=aaa[i]+","+bbb[i][1]+"\r\n";
                    }
                }

                for (var i=0;i<lenth;i++)
                {
                    strcsv+=xValues[i]+","+yValues[i]+","+yvalues2[i]+"\r\n";
                }
            }
            else
            {
                var datatosave={};
                if (this.caijidirection=="UP"||this.caijidirection=="RAD_UP")
                {

                    datatosave=this.dataup;
                    if (this.Devinfo.sensor_type=="IRIS-IS11")
                    strcsv+="Weavelenth,upDN,upshutter,"+this.dataup.shutter_time+",index,"+this.dataup.index+"\r\n";
                    else
                    strcsv+="Weavelenth,"+this.UPStr+",upshutter,"+this.dataup.shutter_time+",index,"+this.dataup.index+"\r\n";;
                    strchogncaiyang=strcsv;

                }else if (this.caijidirection=="DOWN") {
                    datatosave=this.datadown;
                    strcsv+="Weavelenth,downDN,downshutter,"+this.datadown.shutter_time+",index,"+this.datadown.index+"\r\n";
                    strchogncaiyang=strcsv;

                } else if (this.caijidirection=="DARK") {
                    datatosave=this.dataup;
                    strcsv+="Weavelenth,darkDN,darkshutter,"+this.dataup.shutter_time+",index,"+this.dataup.index+"\r\n";
                    strchogncaiyang=strcsv;
                }
                let date=(datatosave.year+2000)+"-"+datatosave.month+"-"+datatosave.day+" "+datatosave.hour+":"+datatosave.minute+":"+datatosave.second;
                let strcsv1="Date,"+date+"\r\n";
                if (typeof datatosave.temprature!="undefined")
                {
                    let temperaturestr="Temperature,"
                    +datatosave.temprature[0]+","+datatosave.temprature[1]+","
                    +datatosave.temprature[2]+","+datatosave.temprature[3]+","
                    +datatosave.temprature[4]+","+datatosave.temprature[5]+","
                    +datatosave.temprature[6]+","+datatosave.temprature[7]+"\r\n";
                    strcsv1+=temperaturestr;
                }
                strcsv=strcsv1+strcsv;
                strchogncaiyang=strcsv1+strchogncaiyang;




                var lenthofdataup=datatosave.data.length;
                for (var i=0;i<lenthofdataup;i++)
                {
                    if(this.Devinfo.sensor_type=="IRIS-IS11")
                    {
                        yValues.push(datatosave.data[lenthofdataup-i-1]);
                    }else {
                        yValues.push(datatosave.data[i]);
                    }
                    
                }
                var yValuesofchongcaiyang = []
                if (this.outputconfig.isChongCaiyang)
                {
                    let aaa= await  invoke("interpolate_spline",{x:xValues,y:yValues,step:this.outputconfig.ChongCaiyanginterval})

                    var lenthofdataup=aaa.length;
                    for (var i=0;i<lenthofdataup;i++)
                    {
                        strchogncaiyang+=aaa[i]+"\r\n";
                    }


                }
                for (var i=0;i<lenth;i++)
                {
                    strcsv+=xValues[i]+","+yValues[i]+"\r\n";
                }








            }

            if(this.Devinfo.work_mode=="advanced_mode")
            {
                let filepath="";
                if (this.outputconfig.isChongCaiyang)
                {
                    await  fs.writeFile(this.pathofdir+"/"+this.Filename+this.nowNumber+"_"+this.caijidirection+"_chongcaiyang.csv", strchogncaiyang)
                }
                if(this.Devinfo.sensor_type=="IRIS-IS11")
                {
                    filepath=this.pathofdir+"/"+this.Filename+this.nowNumber+"_"+this.caijidirection+".csv";
                }else{
                    filepath=this.Pathtosave;
                }
                filepath=this.pathofdir+"/"+this.Filename+this.nowNumber+"_"+this.caijidirection+".csv";
                  await fs.writeFile( filepath, strcsv);
                eventBus.emit('showbox', {title: "系统", body: "保存数据 "+  filepath+" OK",interval:10});
            }else
            {
                await fs.writeFile(this.Pathtosave, strcsv);
                eventBus.emit('showbox', {title: "系统", body: "保存数据 "+  this.Pathtosave+" OK",interval:10});
            }

            // fs.writeFileSync(this.Pathtosave, strcsv);



            this.nowNumber++;
            this.Pathtosave=this.pathofdir+"/"+this.Filename+this.nowNumber+".csv";



        }

        if (event.ctrlKey&&event.code=="KeyG")
        {
            this.dataprocessconfig.useSG=!this.dataprocessconfig.useSG;
            EventBus.emit('showbox', {title: "系统", body: (this.dataprocessconfig.useSG?"Go":"G"),interval:10});
            event.preventDefault();
        }
        if (event.ctrlKey&&event.code=="ArrowUp")
        {
            this.caijiavgNumber++;
            EventBus.emit('showbox', {title: "系统", body: this.caijiavgNumber,interval:100});

        }
        if (event.ctrlKey&&event.code=="ArrowDown") {

            if (this.caijiavgNumber>1) {
                this.caijiavgNumber--;
                EventBus.emit('showbox', {title: "系统", body: this.caijiavgNumber,interval:100});
            }else {
                EventBus.emit('showbox', {title: "系统", body: "must > 1",interval:100});
            }

        }
        if (event.ctrlKey&&event.altKey&&event.code=="KeyS") {
            EventBus.emit('showbox', {title: "系统", body: "保存配置",interval:10});
        }
        if (event.ctrlKey&&event.code=="KeyH") {
           this.dataprocessconfig.usehighpass=!this.dataprocessconfig.usehighpass;
            EventBus.emit('showbox', {title: "系统", body: (this.dataprocessconfig.usehighpass?"Ho":"H"),interval:10});
            event.preventDefault();
        }




    },


    async findmaxNinpath(directoryPath){
        if(directoryPath=="") return
       
        //判断文件夹是否存在
        let isexits=await  fs.exists(directoryPath);
        if (!isexits) {
            // 如果不存在则创建文件夹
            await fs.createDir(directoryPath);

        }
        let fileName = this.Filename;
        // 以同步模式读取目录下的所有文件名
        const files = await fs.readDir(directoryPath);

        // 过滤出以"aaabbb"开头并且以".csv"结尾的文件
        const filteredFiles = files.filter(file => {

                // console.log(file)
                var aa = file.path.startsWith(directoryPath + "\\" + fileName);
                var bb = file.path.endsWith('.csv');
                return aa && bb;
            }
           //  file.path.startsWith(directoryPath+"\\"+this.Filename) && file.path.endsWith('.csv')}

        );



        // 提取文件名中的N值
        const NValues = filteredFiles.map(file => {
            // const match = file.name.match(new RegExp(`^${ fileName}(\\d+)\\.csv$`));
            const match = file.name.match(new RegExp(`^${fileName}(\\d+)(_(UP|DOWN))?\\.csv$`));

            return match ? parseInt(match[1]) : null;
        }).filter(value => value !== null);

        var maxN = Math.max(...NValues);
        this.nowNumber=maxN+1;
   
        if (NValues.length === 0) {
            // 如果没有匹配的文件，则返回-1
            maxN=0;
            this.nowNumber=maxN;

        }
        // 找到最大的N值
 
        this.Pathtosave=this.pathofdir+"\\"+this.Filename+this.nowNumber+".csv";
        return new Promise((resolve, reject) => {return maxN});
    },
    initChart() {
        const chartDom = this.$refs.chart;
        // chartDom.style.width = '100%';
        // chartDom.style.height = '100%';
        let chart = echarts.init(chartDom);

        this.option = {
            // ECharts 配置选项
            xAxis: {
                type: 'value',
                boundaryGap: false,// 显示连续的刻度
                min: 0,
                max: 510,
                dataZoom: [
                    {
                        type: 'inside', // 内置数据区域缩放
                        start: 0, // 初始缩放范围的起始位置（0%）
                        end: 100 // 初始缩放范围的结束位置（100%）
                    }
                ]
            },
            animation: false,
            yAxis: {
                type: 'value',
                //min:0,
            },
            dataZoom: [
                {
                    type: 'inside', // 内置数据区域缩放，包括滚轮缩放
                    xAxisIndex: [0], // 对应 x 轴
                    filterMode: 'none' // 不过滤数据
                },
                {
                    type: 'inside', // 内置数据区域缩放，包括滚轮缩放
                    yAxisIndex: [0], // 对应 y 轴
                    filterMode: 'none' // 不过滤数据
                }
            ],


            // legend: {
            //   data: ['曲线'], // 图例名称
            //   show: true ,// 显示图例
            //   //selectedMode: 'multiple', // 图例的选择模式。默认开启图例开关，可选single，multiple
            // },
            series: [
                {
                    data: [[1, 150], [2, 230], [3, 224], [4, 218], [5, 135], [6, 147], [7, 260]], // 使用二维数组表示数据点的坐标
                    type: 'line',
                    symbol: 'none', // 不显示数据点
                    smooth: false, // 不使用平滑处理
                    step: 'start' // 设置 step 类型的起始位置
                }
            ]
        };

        chart.setOption(this.option);
    },
    comboxchange() {
        //   console.log(this.Comname);

    },
    onConfirm(){
        this.options.push({value:this.optionName,label:this.optionName,index:this.options.length})

    },

    async closemain(){
        await exit(0);
    },
    async setspectralmode(){
        this.isSpecialmodeshow=true
    },
    get_dev_info(){
        return this.Devinfo
    }


}
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
