<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.1.0/css/bootstrap.min.css">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

    <!-- popper.min.js 用于弹窗、提示、下拉菜单 -->
    <script src="https://cdn.bootcss.com/popper.js/1.12.5/umd/popper.min.js"></script>

    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcss.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <!--
    <script src="../static/js/sign_in.js"></script>

    <link rel="stylesheet" href="../static/css/sign_in.css">
    -->
    <!--引入 echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>

    <script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js'></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/0.3.0/Chart.Zoom.min.js"></script>

    <script language="JavaScript">
        var tank = '{{tank}}';
        var sensor_name = '{{sensor_name}}';
        var tid = '{{tid}}';
        $(document).ready(function(){
            $("#coffee_title").text(tank + tid + ' 發酵出料儲豆槽感測器圖表');
        });
    </script>
</head>

<body>
    <div id="wrapper">
        <div id="coffee_header">
            <!-- 匯入共同使用的 header.html 內容 -->
            {% include 'header.html' %}
        </div>
        <!--
        <a href="/ferment">返回發酵槽介面</a>
        <div style="text-align: center; margin-top:0px; font-size: 24px;">
            Smart Coffee
        </div>
        -->
        <!--
        <form action="/chart/SHT11_Temp/{{tid}}" method="post">
            <div class="form-group" style="margin-top: 30px; text-align: center;">
        -->
        <table style="margin: auto; border:3px gray solid; width: 80%; text-align: center;" cellpadding="6" rules='ALL'>
            <tr>
                <td>
                    {% if tid == '2'%}
                    <select id="tank_num">
                        <option value="FO1">發酵出料儲豆槽_1</option>
                        <option value="FO2" selected>發酵出料儲豆槽_2</option>
                    </select>
                    {% else %}
                    <select id="tank_num">
                        <option value="FO1" selected>發酵出料儲豆槽_1</option>
                        <option value="FO2">發酵出料儲豆槽_2</option>
                    </select>
                    {% endif %}

                    <select id="sensors">
                        <option value="UltraSonic">發酵出料儲豆槽咖啡生豆高度</option>
                    </select>

                </td>
            </tr>
            <tr>
                <td>
                    時間間隔:
                    <select name="time-interval" class="text-right">
                        <option value="month">逐月</option>
                        <option value="day">逐日</option>
                        <option value="hour">逐時</option>
                    </select>
                    &nbsp;
                    <!--
                            從&nbsp;
                            <input type="datetime-local" name="sensor_starttime" id="sensor_starttime" value={{starttime}}>
                            &nbsp;到&nbsp;
                            <input type="datetime-local" name="sensor_endtime" id="sensor_endtime" value={{endtime}}>
                            &nbsp;為止
                        -->
                    <span>從</span>
                    <label for="querydate-start"></label><input id="querydate-start" type="date">
                    <span>到</span>
                    <label for="querydate-end"></label><input id="querydate-end" type="date">
                    <span>為止</span>
                </td>

            </tr>
            <tr>
                <td>
                    資料類型:
                    <label><input type="checkbox" name="data-type" value="max">最大值</label>
                    <label><input type="checkbox" name="data-type" value="avg">平均值</label>
                    <label><input type="checkbox" name="data-type" value="min">最小值</label>
                    <br>

                </td>
            </tr>
            <tr>
                <td>
                    <!--
                            <button type="submit" name="charting">繪製圖表</button>
                            <button type="submit" onclick="" id="btn_save_chart" style="display: none;">儲存圖表</button>
                            -->
                    <input type="button" value="查詢" onclick="ShowInfo()">
                    <input type="button" value="匯出" onclick="downloadFile()">
                    <input type="button" value="刪除" onclick="">

                    <script>
                        function ShowInfo() {
                            // 取得桶號、感測器名稱
                            tid = document.getElementById("tank_num").value
                            console.log('tid: ' + tid)
                            sensor_name = document.getElementById("sensors").value
                            console.log('sensor_name: ' + sensor_name)

                            // 數據整理
                            Echart(sensor_name, tid)
                            // 顯示圖表
                        };

                        function downloadFile() {
                            tid = document.getElementById("tank_num").value
                            sensor_name = document.getElementById("sensors").value

                            //藉型別陣列建構的 blob 來建立 URL
                            let fileName = "ChartData_" + tid + "_" + sensor_name + ".csv";
                            //"\ufeff"解決打開CSV中文亂碼問題
                            const data = "\ufeff" + getData();
                            let blob = new Blob([data], {
                                type: 'text/csv,charset=UTF-8'
                            });
                            var href = URL.createObjectURL(blob);
                            // 從 Blob 取出資料
                            var link = document.createElement("a");
                            document.body.appendChild(link);
                            link.href = href;
                            link.download = fileName;
                            link.click();
                        };

                        //所有資料函數
                        function getData() {
                            var header = "日期," + data_name + "\n";
                            var data = "";
                            var length = all_datetime.length;

                            for (var i = 0; i < length; i++) {
                                data = data + all_datetime[i] + ',' + all_data[i] + '\n';
                            };

                            return header + data;
                        };

                        //最大最小平均資料函數
                        function getData() {
                            var header = data_name + "\n日期,";
                            if (max_data) {
                                console.log(max_data);
                                header = header + "最大值,";
                            };
                            if (avg_data) {
                                header = header + "平均值,";
                            };
                            if (min_data) {
                                header = header + "最小值,";
                            };
                            header = header + "\n";
                            var data = "";
                            var length = xAxis_data.length;

                            for (var i = 0; i < length; i++) {
                                data = data + xAxis_data[i] + ',';
                                if (max_data) {
                                    data = data + max_data[i] + ',';
                                };
                                if (avg_data) {
                                    data = data + avg_data[i] + ',';
                                };
                                if (min_data) {
                                    data = data + min_data[i] + ',';
                                };
                                data = data + '\n';
                            };

                            return header + data;
                        };

                    </script>
                </td>
            </tr>
            <tr>
                <td>
                    <!--
                            <img src={{ url }}>
                        -->
                    <div id="" class="show-info" style="text-align: center;">
                        <center>
                            <div class="show-chart" style="height: 420px; width: 100%; text-align: center;">
                                圖表
                            </div>
                        </center>
                    </div>
                </td>
            </tr>
        </table>

        <!--
            </div>
        </form>
        -->

        <div id="coffee_footer">
            <!-- 匯入共同使用的 footer.html 內容 -->
            {% include 'footer.html' %}
        </div>
    </div>

</body>

<script>
    var all_datetime = 0;   // 所有資料時間 ?
    var all_data = 0;       // 所有感測器數據 ?
    var data_name = 0;      // 感測器名稱       // "溫溼度"
    var xAxis_data = 0;     // x 軸資料
    var max_data = 0;       // 
    var min_data = 0;       // 
    var avg_data = 0;       // 

    function Echart(sensor_name, tid) {
        // Echart(sensor_name, tid)

        //將echarts圖形銷毀
        $(".show-chart").removeAttr("_echarts_instance_").empty();

        // Rita：sensor 與 data_name 重複
        // var sensor = evt.substring(2);

        if (!$("input[value=avg]").prop('checked') && !$("input[value=min]").prop('checked') && !$("input[value=max]").prop('checked')) {
            alert("請至少選擇一種資料類型!");
            return false;
        };

        if ($("#querydate-start").val() == '' || $("#querydate-end").val() == '') {
            alert("請選擇日期範圍!");
            return false;
        };
        //基於準備好的dom，初始化echarts例項
        var myChart = echarts.init(document.getElementsByClassName('show-chart')[0]);  // class="col-10 show-chart"

        var date_start = $("#querydate-start").val();
        var date_end = $("#querydate-end").val();
        var avg = 0;
        var max = 0;
        var min = 0;
        var time_interval = $("select[name=time-interval]").val();
        var legend = new Array();
        var color = new Array();
        var series = new Array();

        if ($("input[value=max]").prop('checked')) {
            max = 1;
            legend.push("最大值");
            color.push("#1e88e5");      // 水藍色
        };

        if ($("input[value=avg]").prop('checked')) {
            avg = 1;
            legend.push("平均值");
            color.push("#43a047");      // 草綠色
        };

        if ($("input[value=min]").prop('checked')) {
            min = 1;
            legend.push("最小值");
            color.push("#e64a19");      // 橘紅色
        };

        var json = {
            'tid': tid,
            'sensor_name': sensor_name,
            'avg': avg,
            'max': max,
            'min': min,
            'time-interval': time_interval,
            'date-start': date_start,
            'date-end': date_end
        };

        console.log('json___' + 
            'tid: ' + tid +
            'sensor_name: ' + sensor_name +
            'avg: ' + avg +
            'max: ' + max +
            'min: ' + min +
            'time-interval: ' + time_interval +
            'date-start: ' + date_start +
            'date-end: ' + date_end
        )


        $.get('/history_data_new', json, function (resText) {
            if (resText.max) {
                var max_series = {
                    'name': '最大值',
                    'type': 'scatter',
                    'data': resText.max.map(function (item) { return item[1]; }),
                    'itemStyle': { 'normal': { 'lineStyle': { 'color': '#1e88e5' } } },
                };
                series.push(max_series);        // 把上面的 dict 加入 series array 內
                xAxis_data = resText.max.map(function (item) { return item[0]; });
                max_data = resText.max.map(function (item) { return item[1]; });
            };
            if (resText.avg) {
                var avg_series = { 'name': '平均值', 'type': 'scatter', 'data': resText.avg.map(function (item) { return item[1]; }), 'itemStyle': { 'normal': { 'lineStyle': { 'color': '#43a047' } } }, };
                series.push(avg_series);
                xAxis_data = resText.avg.map(function (item) { return item[0]; });
                console.log('xAxis_data: ' + xAxis_data)                               // 2021-07-09 10:00:00,2021-07-20 09:00:00,2021-07-22 15:00:00,2021-07-26 15:00:00,2021-07-26 16:00:00
                avg_data = resText.avg.map(function (item) { return item[1]; });
                console.log('avg_data: ' + avg_data)                                   // 91.0,98.0,11.0,15.2,30.5
            };
            if (resText.min) {
                var min_series = { 'name': '最小值', 'type': 'scatter', 'data': resText.min.map(function (item) { return item[1]; }), 'itemStyle': { 'normal': { 'lineStyle': { 'color': '#e64a19' } } }, };
                series.push(min_series);
                xAxis_data = resText.min.map(function (item) { return item[0]; });      // all
                min_data = resText.min.map(function (item) { return item[1]; });        // min
            };

            //獲取日期內所有數據
            all_datetime = resText.all.map(function (item) { return item[0]; });        // all
            all_data = resText.all.map(function (item) { return item[1]; });

            //指定圖表的配置項和資料

            option = {
                title: {
                    text: '', // 'Data History'
                    left: '1%'
                },
                tooltip: {
                    trigger: 'axis'
                },
                color: color,
                legend: {
                    data: legend,
                },
                xAxis: {
                    data: xAxis_data,
                },
                yAxis: {
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: ''
                        }
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                dataZoom: [{
                    startValue: '2021-01-01'
                }, {
                    type: 'inside'
                }],
                series: series,
                /*
                series: [
                    {
                        name: '最大值',
                        type: 'line',
                        data: resText.max.map(function (item) {
                            return item[1];
                        }),
                        itemStyle: {
                            normal: {
                                lineStyle: {
                                    color: '#1e88e5'
                                }
                            }
                        },
                    },
                    {
                        name: '平均值',
                        type: 'line',
                        data: [20.0, 20.0, 20.0, 20.0, 20.0, 20.0],
                        itemStyle: {
                            normal: {
                                lineStyle: {
                                    color: '#43a047'
                                }
                            }
                        },
                    },
                    {
                        name: '最小值',
                        type: 'line',
                        data: [15.0, 15.0, 15.0, 15.0, 15.0, 15.0],
                        itemStyle: {
                            normal: {
                                lineStyle: {
                                    color: '#e64a19'
                                }
                            }
                        }
                    },
                ]
                */

            };
            console.log('SHOW myChart')
            //使用剛指定的配置項和資料顯示圖表
            myChart.setOption(option);
        }, 'json');

    } // Echart(sensor_name, tid)


</script>

</html>