import QtQuick 2.11
//import QtQuick.VirtualKeyboard 2.14
//import QtQuick.VirtualKeyboard.Settings 2.14
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4

import QtQuick.Layouts 1.3
import QtTest 1.14
//import "modbus.js" as ModbusJs
//import "breatheTest.js" as BreatheTestJs
import Qt.labs.platform 1.1


Item{
    id:root

    property var pagetype:rootitem.Page_Type_ValveTest
    //车辆单位
    property  string organize
    //车牌号
    property  string carplate
    //总容积
    property  string total_volume
    //油仓数量
    property  string compartment_num
    //当前油仓ID
    property  int compartment_id
    //当前油仓体积
    property  int volume
    property  int test_direction:0
    //
    property  string state
    property  string pressure:"0.00"

    property int  pressureCnt:0
    property int  current_step:0

    property  var  syskpArray: []
    property  var  valvekpArray: []
    property  var  allArray: []
    property  real m_maxY: 0.0
    property  real m_minY: 0.0
    property  bool bStart: false;
    property  bool test_end: false;



/*
    Loader{
        id:loader
        anchors.fill: parent
        //anchors.margins: 5
        sourceComponent: componet
    }

    */
/*
    function show(){
        if(loader.sourceComponent  === null){
            loader.sourceComponent  = componet
            console.debug("avans 1111")
        }
        loader.item.show()
    }

    function exit(){
        if(loader.sourceComponent  !== null){
            loader.item.exit()
        }
    }
*/

    function update_pressure(pressure_map){
        //textstring += pressure_map.pressure+":"
        //textstring += pressure_map.direction.toString()+":"
        //textstring += pressure_map.stage.toString()+":"
        //textstring += pressure_map.step.toString()+":"
        //console.debug("avans 1111 update_pressure: ", pressure_map.pressure)


        pressure = pressure_map.pressure
        add_record(pressure_map.pressure)

        var data = new Object
        data.step = pressure_map.step
        data.pressure = Number(pressure_map.pressure)

        pressureDisplayInput(data)

        //if(pressure_map.step === 3){  // keep pressure
            if(pressure_map.stage === 0){  //sys test
                //syskpArray.push(Number(pressure_map.pressure))

                syskpArray.push(data)

            }else if(pressure_map.stage === 1){  //valve test
                //valvekpArray.push(Number(pressure_map.pressure))
                valvekpArray.push(data)
            }
        //}

        allArray.push(data)
    }

    function add_record(str){
        var obj={}
        obj.pressure = str
        recordtable.modelData.append(obj)
    }

    function cleardata(){
        recordtable.modelData.clear()
        allArray = []
        syskpArray = []
        valvekpArray = []

        curveDisplay.spline.clear()
        pressureCnt =0
        current_step=0
        curveDisplay.scatter_clear()
        curveDisplay.setRange_X(0, 180)
        curveDisplay.setRange_Y(0, 14)


        resulttable.systemPressure_delta = "  ";
        resulttable.systemPressure_fontcolor="black"
        resulttable.systemPressure_pass = "未知";

        resulttable.valvePressure_delta = "  ";
        resulttable.valvePressure_fontcolor ="black"
        resulttable.valvePressure_pass = "未知";

        statetable.state_str1 = "  ";
        statetable.state_str2 = "  ";
    }

    function pressureDisplayInput(value){
        pressureCnt++
        var number = value.pressure

        m_maxY = (m_maxY < number)? number:m_maxY
        m_minY = (m_minY > number)? number:m_minY

        curveDisplay.setRange_Y(m_minY-1.0, m_maxY+1.0)

        if(pressureCnt <= 180){
            curveDisplay.spline.append(pressureCnt-1,number)
        }
        else{

            curveDisplay.setRange_X(0, pressureCnt-1)
            curveDisplay.spline.append(pressureCnt-1,number)
        }

        if(current_step !== value.step){
            if(2 == current_step){
                curveDisplay.scatter_add(pressureCnt-1,number)
            }
            current_step = value.step

            if(2 == current_step){
                curveDisplay.scatter_add(pressureCnt-1,number)
            }

        }

    }


    function show_systemresult(delta, bPassed)
    {
        if(bPassed){
            resulttable.systemPressure_delta = delta;
            resulttable.systemPressure_fontcolor="green"
            resulttable.systemPressure_pass = "合格";
        }else{
            resulttable.systemPressure_delta = delta;
            resulttable.systemPressure_fontcolor="red"
            resulttable.systemPressure_pass = "超标";
        }

        //console.log("sysTestGeneratePicture")
        //groupbox.sysTestGeneratePicture()
    }

    function show_valveresult(delta, bPassed)
    {
        if(bPassed){
            resulttable.valvePressure_delta = delta;
            resulttable.valvePressure_fontcolor ="green"
            resulttable.valvePressure_pass = "合格";
        }else{
            resulttable.valvePressure_delta = delta;
            resulttable.valvePressure_fontcolor="red"
            resulttable.valvePressure_pass = "超标";
        }

        //console.log("valveTestGeneratePicture")
        //groupbox.valveTestGeneratePicture()

    }

    function update_runstate(str1, str2)
    {
        statetable.state_str1 = str1;
        statetable.state_str2 = str2;
    }

    function test_stoped(){
        startStopButton.running = false;

        console.log("sysTestGeneratePicture")
        groupbox.sysTestGeneratePicture()

        console.log("valveTestGeneratePicture")
        groupbox.valveTestGeneratePicture()

        console.log("allTestGeneratePicture")
        groupbox.allTestGeneratePicture()
    }


   // Component{
   //     id:componet
        DynamicGroupBox{
            id:groupbox
            //x:width
            //x:0
            title: "油气回收系统密封检测  第"+compartment_id+"仓： 容积"+volume+"(L)"
            //width: 1024
            //height: 768
            anchors.centerIn: parent
            anchors.fill: parent

            function show(){
                animationShow.running = true
            }

            function exit(){
                //BreatheTestJs.exit = true
                animationExit.running = true
                //startStopButton.running = false
                //stopTimer.start()
            }

            function allTestGeneratePicture(){
                var filename = root.carplate+"_"+root.compartment_id+"_all"
                reportPicture_all.delayms = 100
                reportPicture_all.generatePicture(filename, allArray)
            }
            function sysTestGeneratePicture(){
                var filename = root.carplate+"_"+root.compartment_id+"_sys"
                reportPicture_sys.delayms = 300
                reportPicture_sys.generatePicture(filename, syskpArray)
            }

            function valveTestGeneratePicture(){
                var filename = root.carplate+"_"+root.compartment_id+"_valve"
                reportPicture_valve.delayms = 500
                reportPicture_valve.generatePicture(filename, valvekpArray)
            }


/*
            //加载任务动画效果
            NumberAnimation {
                id: animationShow
                target: groupbox
                property: "x"
                from: groupbox.x
                to: 0
                duration: 500
            }
            NumberAnimation {
                id: animationExit
                target: groupbox
                property: "x"
                from: groupbox.x
                to: 1024
                duration: 500
            }

*/

            FileDialog {
                id: saveWordDialog
                title: "保存为"
                //nameFilters: [ "Word files (*.doc)"]
                //nameFilters: [ "Word files (*.doc)", "Text files (*.pdf)"]
                nameFilters: ["Text files (*.pdf)"]
                fileMode: FileDialog.SaveFile
                onAccepted: {
                    var savePath = file.toString().substring(8)

                    console.log("saveWordDialog savePath:")
                    console.log(savePath)

                    //reportWord.generateBreatheValveWord(savePath,para,obj1,obj2,obj3)
                    testService.genReport(savePath, "D:/tmp/")
                }
            }


            Column{
                anchors.left: parent.left
                anchors.leftMargin: 3
                anchors.top: parent.top
                anchors.topMargin: 10
                spacing: 0


                Row{
                   x:-10

                   CurveDisplay{
                       id:curveDisplay
                       anchors.verticalCenter: parent.verticalCenter

                       width: 900
                       height: 460
                       axisxMax:180
                       axisxMin:0
                       axisyMax:14
                       axisyMin:0
                       name:"横轴时间（秒） 纵轴压力(kPa)"
                   }



                   Item {
                       id:button_root
                       width: 360
                       height: 460

                       Column{
                           id:button_column
                           spacing: 10

                           Rectangle{
                               id:buttonWindow
                               //anchors.fill: parent
                               width: 350
                               height: 70

                               color: "white"
                               radius: 6
                                border.color: "black"

                               Row{
                                   anchors.verticalCenter: parent.verticalCenter
                                   anchors.horizontalCenter: parent.horizontalCenter
                                   spacing: 50

                                   StartStopButton{
                                       id:startStopButton
                                       width: 50
                                       height: 50
                                       anchors.verticalCenter: parent.verticalCenter
                                       onRunningChanged: {
                                           if(running){
                                               //clearCurveDisplay()
                                               cleardata()
                                              bStart = testService.tstart(compartment_id, test_direction)
                                              if(!bStart){
                                                  running=false;
                                              }
                                           }else{
                                               if(bStart){
                                                    testService.tstop(compartment_id)
                                                   bStart=false
                                               }
                                           }
                                      }
                                   }

                                   ReportButton{
                                       id:reportButton
                                       width: 50
                                       height: 50
                                       anchors.verticalCenter: parent.verticalCenter
                                       onUserClicked:{

                                           //if(allArray.length > 0){
                                               //console.log("allTestGeneratePicture")
                                               //groupbox.allTestGeneratePicture()
                                          // }

                                           //if(syskpArray.length > 0){
                                               //console.log("sysTestGeneratePicture")
                                               //groupbox.sysTestGeneratePicture()
                                          // }

                                          // if(valvekpArray.length > 0){
                                          //     console.log("valveTestGeneratePicture")
                                          //     groupbox.valveTestGeneratePicture()
                                          // }


                                           //testService.reportpic_Ready(compartment_id);


                                           if(testService.check_alltest_ok(1)){
                                               var fileName = root.carplate
                                               var text = getWordSaveFileName(fileName)
                                               console.log(text)

                                               saveWordDialog.currentFile = getWordSaveFileName(fileName)
                                               saveWordDialog.open()
                                           }


                                       }
                                   }

                                }

                            }

                           Rectangle{
                               id:test_selrect
                               //anchors.fill: parent
                               anchors.margins: 10
                               width: 350
                               height: 50
                               color: "white"
                               radius: 6
                               border.color: "black"
                               UserComboBox{
                                  id:test_comboBox
                                  //anchors.fill:parent
                                  implicitWidth:350
                                  implicitHeight:50
                                  bgColor:"#D2D5D9"
                                  model: ["正压密闭性检测","负压密闭性检测"]
                                  onCurrentTextChanged: {
                                      //root.standard_name = currentText
                                      test_direction = currentIndex
                                      console.log("choose test direction : "+test_direction)
                                      if(0 == currentIndex){
                                          resulttable.titlestr = currentText

                                      }else{
                                          resulttable.titlestr = currentText

                                      }
                                  }

                               }

                           }

                           Rectangle{
                               id:pressureWindow
                               //anchors.fill: parent
                               anchors.margins: 10
                               width: 350
                               height: 100
                               color: "white"
                               radius: 6
                               border.color: "black"


                               Text {
                                   id: pressurekpa
                                   anchors.right: pressureWindow.right
                                   anchors.verticalCenter: parent.verticalCenter
                                   text: qsTr("kPa ")
                                   //font: 40
                                   font.bold: true
                                   font.pixelSize: 35

                               }

                               Rectangle{
                                   id:pressure_rect

                                   anchors.verticalCenter: parent.verticalCenter
                                   anchors.right: pressurekpa.left;

                                   width: 250
                                   height: 80
                                   LCDNumber{
                                        id:lcd_pressure
                                        anchors.centerIn: parent
                                        text: root.pressure
                                   }
                               }


                           }

                           Rectangle{
                               id:resultWindow
                               //anchors.fill: parent
                               anchors.margins: 5
                               width: 350
                               height: 100
                               color: "white"
                               radius: 6
                               border.color: "black"

                               ResultTable{
                                id:resulttable
                                anchors.fill: parent
                               }

                             }

                           Rectangle{
                               id:stateWindow
                               //anchors.fill: parent
                               anchors.margins: 5
                               width: 350
                               height: 100
                               color: "white"
                               radius: 6
                               border.color: "black"

                               StateTable{
                                id:statetable
                                anchors.fill: parent
                               }

                             }
                       }

                   }

                }

                Row{
                    id: records
                    spacing: 10

                    function dataRandomSet(modelData,max){
                        for(var i=0;i<max; i++){
                            //var number= Math.round(Math.random()*10)
                            var number= Math.random()*10
                            //number *= 10

                            var obj={}
                            obj.pressure= 0 - number.toFixed(3)
                            modelData.append(obj)
                        }
                    }

                    Rectangle{
                        width: 1250
                        height: 240
                        color: "white"
                        radius: 6

                        GroupBox{
                            id:groupboxrecord
                             //x:width
                            //x:0
                            title: "历史数据"
                            anchors.fill: parent
                            anchors.margins: 0

                            RecordTable{
                                id:recordtable
                                Component.onCompleted: {
                                    //records.dataRandomSet(modelData,500)
                                }
                            }

                        }
                    }

                }


            }

        }

   // }


        ReportPicture{
            id:reportPicture_sys
        }

        ReportPicture{
            id:reportPicture_valve
        }

        ReportPicture{
            id:reportPicture_all
        }


        function pad_with_zeroes(number, length) {
            var my_string = '' + number;
            while (my_string.length < length) {
                my_string = '0' + my_string;
            }
            return my_string;
        }

        function getWordSaveFileName( para){
            var date = new Date;
            var year = date.getFullYear()
            var month = pad_with_zeroes(date.getMonth()+1,2)
            var day = pad_with_zeroes(date.getDate(),2)
            var hour = pad_with_zeroes(date.getHours(),2)
            var minute = pad_with_zeroes(date.getMinutes(),2)
            var second = pad_with_zeroes(date.getSeconds(),2)

            var time = year+month+day+hour+minute+second
            return "file:///"+time+"_"+para
        }


        Timer {
            id: timer;
            interval: 1000;//设置定时器定时时间为500ms,默认1000ms
            repeat: false //是否重复定时,默认为false
            running: false //是否开启定时，默认是false，当为true的时候，进入此界面就开始定时
            triggeredOnStart: false // 是否开启定时就触发onTriggered，一些特殊用户可以用来设置初始值。
            onTriggered: {
                //qreal y = 12/2 + (12/2.0)*sin(pressureCnt)
                pressureDisplayInput(12/2 + (12/2.0)*Math.sin(Math.PI*pressureCnt/60))
            }
            //restart ,start,stop,定时器的调用方式，顾名思义

        }

        Component.onCompleted: {
            //timer.start()

        }

}

