import QtQuick 2.15
import QtQuick.Layouts 1.3
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.4
import Qt.labs.qmlmodels 1.0
import QtQuick.LocalStorage 2.0
//import io.qt.DataBaseModel 1.0
import Qt.labs.platform 1.1

import TService 1.0
import "selftest_db.js" as SelfDB


Item {
    id: selftest_root
    property  string title_str:"系统自测"

    property string background: "#d7e3bc"
    property string alterBackground: "white"
    property string highlight: "#e4f7d6"
    property string headerBkgnd: "#F0F0F0"

    property  var  allArray: []
    //property  string state
    property  string pressure:"0.00"
    property int  pressureCnt:0
    property  int current_step:0
    property  int test_direction:0
    property  bool bStart: false
    property  real m_maxY: 0.0
    property  real m_minY: 0.0

    property  string report_record_str:"null"
    property  string test_state_str:"未开始"
    property  string test_result_str:"未知"

    //var selftest_info = new Object

    property var normalG: Gradient {
            GradientStop { position: 0.0; color: "#c7d3ac" }
            GradientStop { position: 1.0; color: "#F0F0F0" }
    }
    property var hoverG: Gradient {
            GradientStop { position: 0.0; color: "white"; }
            GradientStop { position: 1.0; color: "#d7e3bc"; }
    }
    property var pressG: Gradient {
            GradientStop { position: 0.0; color: "#d7e3bc"; }
            GradientStop { position: 1.0; color: "white"; }
    }

    function qmlProcessState(id, str1, str2){
        if(id === 0){

            test_state_str = str1
        }
    }

    function qmlProcessResult(id, str, bPassed){
        if(id === 0){
            if(bPassed){
                test_result_str = "合格"
            }else{
                test_result_str = "超标"
            }

            var selftest_info = new Object
            var jsontmp = testService.get_selftest_info()

            selftest_info.target = jsontmp.target
            selftest_info.interval = jsontmp.interval
            selftest_info.threshold = jsontmp.threshold
            selftest_info.begin = jsontmp.begin
            selftest_info.end = jsontmp.end
            selftest_info.delta = jsontmp.delta
            selftest_info.passed = jsontmp.pass

            //pagetest.show_selftestDetail(str)
        }

    }

    function qmlProcessStop(id){
        if(id === 0){
            //pagetest.selftestStop()
            startStopButton.running = false;
            database_add()
            tableview_refresh()
            //console.log("qmlProcessStop pagetest ",id )
        }
    }

    function database_add(){

        //var record = new Object
        //record.target = selftest_info.target
        //record.interval = selftest_info.interval
        //record.threshold = selftest_info.threshold
        //record.begin = selftest_info.begin
        //record.end = selftest_info.end
        //record.passed = selftest_info.passed

        var selftest_info = new Object
        var jsontmp = testService.get_selftest_info()

        selftest_info.target = jsontmp.target
        selftest_info.interval = jsontmp.interval
        selftest_info.threshold = jsontmp.threshold
        selftest_info.begin = jsontmp.begin
        selftest_info.end = jsontmp.end
        selftest_info.delta = jsontmp.delta
        selftest_info.passed = jsontmp.passed

        SelfDB.insertRecord(selftest_info)
        SelfDB.insertData(allArray)

    }

    function curveDisplay_refresh(date){
        curveDisplay.spline.clear()
        curveDisplay.scatter_clear()
        curveDisplay.setRange_X(0, 180)
        curveDisplay.setRange_Y(0, 14)

        pressureCnt =0
        current_step = 0;

        let table_name = 'data_'+date
        var records = SelfDB.readData(table_name)

        if(records){

            if(records.rows.length > 0){
                var index = 0
                while(index < records.rows.length){

                    var item = records.rows.item(index)
                    curveDisplay_show(item)

                    index++;
                }
            }

        }else{
            console.log("tableview_refresh records is null:" )
        }

    }

    function tableview_refresh(){
       selttest_Model.clear()
       var records = SelfDB.readData("test_table")

       if(records){

           console.log("tableview_refresh records.rows.length:"+records.rows.length )

           if(records.rows.length > 0){
               var index = records.rows.length-1
               var tmp_id = 0;
               while(index >= 0){
                   var item = records.rows.item(index)
                   /*
                   selttest_Model.append({
                                             "idx":tmp_id,
                                             "date":item.dt,
                                             "time":item.time,
                                             "target":item.target.toString(),
                                             "interval":item.interval.toString(),
                                             "threshold":item.threshold.toString(),
                                             "start":item.begin.toString(),
                                             "end":item.end.toString(),
                                             "delta":item.delta.toString(),
                                             "result":item.passed === 1? "合格":"超标" })
                   */

                   selttest_Model.append({
                                             "idx":tmp_id,
                                             "date":item.dt,
                                             "time":item.time,
                                             //"target":item.target,
                                             "interval":item.interval,
                                             "threshold":item.threshold,
                                             "start":item.begin,
                                             "end":item.end,
                                             "delta":item.delta.toFixed(2),
                                             //"delta":item.delta,
                                             "result":item.passed === 1? "合格":"超标" })
                   index--
                   tmp_id++
               }
           }

       }else{
        console.log("tableview_refresh records is null:" )
       }

    }

    function qmlProcessReportProgress_self(str){

        console.log("main.qml tservice qmlProcessReportProgress:", str )

        if(str === "close"){
            genreportprogress_self.exit()
        }else{
            genreportprogress_self.show(str)
        }

    }

    function qmlProcessPressure(id, map){
        //console.log("main.qml qmlProcessPressure ",id )
        //log.show2(str)
        //var textstring = ''
        //var varmap = map
        //textstring += map.pressure+":"
        //textstring += map.direction.toString()+":"
        //textstring += map.stage.toString()+":"
        //textstring += map.step.toString()+":"

        //console.log("main.qml qmlProcessPressure :",textstring.toString() )
        if(id === 0){
            pressure = map.pressure
            //pressureDisplayInput(Number(pressure_map.pressure))

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

            curveDisplay_show(data)

            allArray.push(data)
        }

    }

    function curveDisplay_show(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+2.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 cleardata(){

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


        pressure = "0.00"

        test_state_str="未开始"
        test_result_str="未知"
    }

    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
    }


    DynamicGroupBox{
        id:groupbox_all
        anchors.centerIn: parent
        anchors.fill: parent

        title: title_str

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

            FileDialog {
                id: saveWordDialog
                title: "保存为"
                //nameFilters: [ "Word files (*.doc)"]
                //nameFilters: [ "Word files (*.doc)", "Text files (*.pdf)"]
                nameFilters: ["Text files (*.pdf)"]
                fileMode: FileDialog.SaveFile
                onAccepted: {

                    var fileName = "D:/tmp/selftest.jpg"

                    rect_display.grabToImage(function(result) {
                        result.saveToFile(fileName);
                    });


                    var savePath = file.toString().substring(8)

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

                    if("null" == report_record_str){
                        testService.genReport_Self(savePath, "D:/tmp/")
                    }else{
                        testService.genReport_Self2(report_record_str, savePath, "D:/tmp/")
                    }

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




            Row{
               //x:-10
                y:-10
                //width: 900
                //height: parent.height

               Rectangle{
                   id:rect_display
                   //anchors.verticalCenter: parent.verticalCenter
                   width: 900
                   height: 460

                   CurveDisplay{
                       id:curveDisplay
                       anchors.fill: parent

                       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(0, 0)
                                          if(!bStart){
                                              running=false;
                                          }
                                       }else{
                                           if(bStart){
                                                testService.tstop(0)
                                               bStart=false
                                           }
                                       }

                                  }
                               }

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

                                       //database_add()
                                       //tableview_refresh()


                                       if(false == startStopButton.running){

                                           //var fileName = "D:/tmp/selftest.jpg"

                                           //rect_display.grabToImage(function(result) {
                                           //    result.saveToFile(fileName);
                                           //});

                                           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 time = year+month+day
                                           saveWordDialog.currentFile = "file:///"+time+"_VRST2000"

                                           report_record_str = "null"

                                           saveWordDialog.open()
                                       }


                                   }
                               }

                               ReturnButton{
                                    id: return_button
                                    width: 50
                                    height: 50
                                    anchors.verticalCenter: parent.verticalCenter
                                    onUserClicked: {
                                        if(false == startStopButton.running){
                                            selftest_root.destroy()
                                        }
                                    }
                               }

                            }

                        }

                       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)

                              }

                           }

                       }

                       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: selftest_root.pressure
                               }
                           }


                       }

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

                           Column{
                               anchors.margins: 10
                               anchors.fill: parent
                               spacing: 5

                               ResultDisplayText{
                                   id: result_title
                                   width: parent.width
                                   height: 25
                                   color: "white"
                                   //paraName_fontColor:"red"
                                   paraName: "自身密闭性检测："
                                   paraResult:""
                                   paraUnit:""
                               }

                               ResultDisplayText{
                                   id:result_dis
                                   width: parent.width
                                   height: 25
                                   color: "#D2D5D9"
                                   paraName_fontColor:"green"
                                   paraName: "检测结果："
                                   paraResult_fontColor:"#272727"
                                   paraResult:test_result_str
                                   paraUnit:""
                               }

                           }

                         }

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

                           Column{
                               anchors.margins: 10
                               anchors.fill: parent
                               spacing: 5

                               ResultDisplayText{
                                   id: state_title
                                   width: parent.width
                                   height: 25
                                   color: "white"
                                   //paraName_fontColor:"red"
                                   paraName: "检测进度："
                                   paraResult:""
                                   paraUnit:""
                               }

                               /*
                               TNormalProgress {
                                   id:test_progress
                                   width: parent.width
                                   backgroundColor: "#D2D5D9"
                                   //barType: TNormalProgress.BarType.SucceedOrFailed

                                   percent: 100
                                   //NumberAnimation on percent { from: 0; to: 100; duration: 5000; running: true; loops: Animation.Infinite}
                               }
                               */

                               ResultDisplayText{
                                   id:state_dis
                                   width: parent.width
                                   height: 25
                                   color: "#D2D5D9"
                                   paraName_fontColor:"green"
                                   paraName: "检测状态："
                                   paraResult_fontColor:"#272727"
                                   paraResult:test_state_str
                                   paraUnit:""
                               }

                           }



                         }


                   }

               }


            }

            Rectangle{
                id:records_rect
                //x:-10
                width: 1250
                height: 240
                color: "white"
                radius: 6
                border.color: "black"

                Text{
                    id:text_title
                    anchors.top: parent.top
                    anchors.topMargin: 10
                    anchors.horizontalCenter: parent.horizontalCenter
                    font.bold: true
                    font.pixelSize: 24
                    text: "系统自测历史记录"

                }

                Component{
                            id:itemDelegateText
                            Text {
                                anchors.verticalCenter: parent.verticalCenter
                                color: styleData.selected?"#1E90FF":"#000000"
                                elide: styleData.elideMode
                                text: styleData.value
                                font.pointSize: 10
                                //font.pixelSize: 24
                                //font.bold: true
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                                anchors.fill: parent
                            }
                        }

                Component{
                            id:itemDelegateButton
                            Row{
                                anchors.fill: parent
                                anchors.centerIn: parent
                                spacing: 10

                                Button {
                                    anchors.verticalCenter: parent.verticalCenter
                                    //color: styleData.selected?"#1E90FF":"#000000"
                                    //elide: styleData.elideMode
                                    //anchors.centerIn: parent
                                    text: "报告"
                                    width: 60
                                    onClicked: {

                                        console.log("index ==="+styleData.row);
                                        console.log("tableView.currentRow ==="+tableView.currentRow);
                                        console.log("select date:"+selttest_Model.get(styleData.row).date);

                                        var today = new Date(selttest_Model.get(styleData.row).date);
                                        var DD = String(today.getDate()).padStart(2, '0'); // 获取日
                                        var MM = String(today.getMonth()+1).padStart(2, '0'); //获取月份，1 月为 0
                                        var yyyy = today.getFullYear(); // 获取年

                                        let date = yyyy + MM  + DD;
                                        curveDisplay_refresh(date)

                                        //var fileName = "D:/tmp/selftest.jpg"

                                        //rect_display.grabToImage(function(result) {
                                        //    result.saveToFile(fileName);
                                        //});



                                        //生成测试结果 JSON 字符串
                                        var recordJson={}

                                        //recordJson.target = Number(selttest_Model.get(styleData.row).target)
                                        recordJson.interval = Number(selttest_Model.get(styleData.row).interval)
                                        recordJson.threshold = Number(selttest_Model.get(styleData.row).threshold)
                                        recordJson.begin = Number(selttest_Model.get(styleData.row).start)
                                        recordJson.end = Number(selttest_Model.get(styleData.row).end)
                                        recordJson.delta = Number(selttest_Model.get(styleData.row).delta)

                                        if("合格" === selttest_Model.get(styleData.row).result){
                                            recordJson.passed = 1
                                        }else{
                                            recordJson.passed = 0
                                        }


                                        report_record_str = JSON.stringify(recordJson)

                                        saveWordDialog.currentFile = "file:///"+date+"_VRST2000"
                                        saveWordDialog.open()


                                    }
                                }

                                Button {
                                    anchors.verticalCenter: parent.verticalCenter
                                    //color: styleData.selected?"#1E90FF":"#000000"
                                    //elide: styleData.elideMode
                                    //anchors.centerIn: parent
                                    text: "删除"
                                    width: 60

                                    onClicked: {

                                        //curveDisplay.spline.clear()
                                       // pressureCnt =0

                                        SelfDB.deleteRecord(selttest_Model.get(styleData.row).date)
                                        tableview_refresh()

                                    }
                                }

                            }

                        }

                TableView{
                    id:tableView
                    //frameVisible: true
                    width: parent.width
                    focus: true
                    //height: parent.height - 50
                    anchors.top: text_title.bottom
                    anchors.bottom: parent.bottom
                    anchors.topMargin: 10

                    TableViewColumn{role: "idx"; title: "ID"; width: 40;delegate: itemDelegateText}
                    TableViewColumn{role: "date"; title: "自检日期"; width: 120;delegate: itemDelegateText}
                    TableViewColumn{role: "time"; title: "完成时间"; width: 120;delegate: itemDelegateText}
                    //TableViewColumn{role: "target"; title: "目标压力(kPa)"; width: 120;delegate: itemDelegateText}
                    TableViewColumn{role: "interval"; title: "检测时间(秒)"; width: 120;delegate: itemDelegateText}
                    TableViewColumn{role: "threshold"; title: "变化限值(kPa)"; width: 120;delegate: itemDelegateText}
                    TableViewColumn{role: "start"; title: "开始压力(kPa)"; width: 120;delegate: itemDelegateText}
                    TableViewColumn{role: "end"; title: "结束压力(kPa)"; width: 120;delegate: itemDelegateText}
                    TableViewColumn{role: "delta"; title: "压力变化(kPa)"; width: 120;delegate: itemDelegateText}
                    TableViewColumn{role: "result"; title: "自测结果"; width: 80;delegate: itemDelegateText}
                    TableViewColumn{role: "detail"; title: "操作"; width: 130;delegate: itemDelegateButton}

                    //model: modelItems

                    headerDelegate: Rectangle{
                        implicitWidth: 16
                        implicitHeight: 24

                        gradient: styleData.pressed ? selftest_root.pressG : (styleData.containsMouse ? selftest_root.hoverG: selftest_root.normalG)

                        border.color: "gray"
                        border.width: 1
                        Text{
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.left: parent.left
                            anchors.leftMargin: 4
                            anchors.right: parent.right
                            anchors.rightMargin: 4
                            text: styleData.value
                            color: styleData.pressed ?"red" : "blue"
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                            font.bold: true
                        }
                    }
                    rowDelegate: Rectangle{
                        height: 28
                        //border.color: "gray"
                        //color: styleData.selected?"#f0b0b0af":(styleData.alternate?"#c3c3c0":"#c0c0c3")
                        color: styleData.selected ? selftest_root.highlight : selftest_root.alterBackground

                    }

                    itemDelegate: Rectangle {
                        height: 24
                        //border.color: "gray"
                        color: "transparent"
                        Text {
                            //anchors.centerIn: parent
                            //anchors.left: parent.left
                            anchors.leftMargin: 6
                            anchors.verticalCenter: parent.verticalCenter
                            //color: styleData.textColor
                            color: styleData.selected ? "red" : styleData.textColor
                            text: styleData.value
                            verticalAlignment: Text.AlignVCenter
                            font.pointSize: 13
                        }
                    }

                    onClicked:{
                        console.log("onClicked index ==="+ row);
                        console.log("select date:"+selttest_Model.get(row).date);

                        var today = new Date(selttest_Model.get(row).date);
                        var DD = String(today.getDate()).padStart(2, '0'); // 获取日
                        var MM = String(today.getMonth()+1).padStart(2, '0'); //获取月份，1 月为 0
                        var yyyy = today.getFullYear(); // 获取年

                        let date = yyyy + MM  + DD;
                        curveDisplay_refresh(date)

                    }


                    model:ListModel{
                         id: selttest_Model
                    }
                }


            }

        }



    }

    Log{
        id:genreportprogress_self
        z:30
        width: 300
        height: 50
        //anchors.centerIn: parent
        anchors.top: parent.top
        anchors.topMargin: 100
        anchors.left: parent.left
        anchors.leftMargin: 480
    }

    Component.onCompleted: {

        testService.sigPressure.connect(qmlProcessPressure);

        testService.sigState.connect(qmlProcessState);
        //testService.sigSystemResult.connect(qmlProcessSystemResult);
        //testService.sigValveResult.connect(qmlProcessValveResult);
        testService.sigSelfTestResult.connect(qmlProcessResult);
        testService.onGenreportProgress.connect(qmlProcessReportProgress_self);

        testService.sigStop.connect(qmlProcessStop);

        SelfDB.initDatabase()

        tableview_refresh()

    }
}

/*##^##
Designer {
    D{i:0;autoSize:true;height:480;width:640}
}
##^##*/
