<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>折线图</title>
    <link href="/static/layui/css/layui.css" rel="stylesheet">
</head>

<body>
<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-md12">
            <form class="layui-form" id="queryForm">
                <!-- 产品筛选框 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">筛选框</label>
                    <div class="layui-input-block">
                        <select name="filterOptions" lay-verify="required" multiple>

                        </select>
                    </div>
                </div>

                <!-- 时间筛选框 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">选择日期</label>
                    <div class="layui-input-inline">
                        <div class="layui-input-inline layui-input-wrap">
                            <div class="layui-input-prefix">
                                <i class="layui-icon layui-icon-date"></i>
                            </div>
                            <input type="text" name="startTime" id="date" lay-verify="required|date"
                                   placeholder="请选择查询日期" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <!-- 时长筛选框 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">时长筛选</label>
                    <div class="layui-input-block">
                        <select name="duration">
                            <option value="1">1s</option>
                            <option value="60">1min</option>
                            <option value="300">5min</option>
                            <option value="900">15min</option>
                        </select>
                    </div>
                </div>

                <button class="layui-btn" lay-submit lay-filter="demo-submit">查询</button>
            </form>
        </div>
    </div>

    <div class="layui-row">
        <div class="layui-col-md12">
            <!-- 折线图 -->
            <div id="lineChart" style="width: 100%; height: 700px;"></div>
        </div>
    </div>
</div>

<!-- 引入Layui的JS -->
<script src="/static/layui/layui.js"></script>
<script src="/static/echarts/echarts.js"></script>

<script>
    layui.use(['form', 'laydate', 'jquery'], function () {
        var form = layui.form;
        var laydate = layui.laydate;
        var $ = layui.jquery;


        $.get("API/GetNames", function (data) {
            // 获取select元素
            const $select = $('select[name="filterOptions"]');

            // 清空现有选项（可选，根据需求决定是否保留原有选项）
            // $select.empty();

            // 遍历数据数组，添加子项
            if (Array.isArray(data)) {  // 确保data是数组
                data.forEach(function (item) {
                    // 创建option元素，value和text都使用数组项的值
                    const $option = $('<option></option>')
                        .val(item)  // 设置option的value
                        .text(item); // 设置显示文本

                    // 添加到select中
                    $select.append($option);
                    form.render('select');
                });
            }
        }).fail(function () {
            console.error("获取选项数据失败");
        });

        // 日期
        laydate.render({
            elem: '#date',
            format: 'yyyy-MM-dd'
        });

        // 监听表单提交事件
        form.on('submit(demo-submit)', function (data) {
            let field = data.field; // 获取表单字段值
            // layer.alert(JSON.stringify(field));
            // console.log(field);

            $.ajax({
                url: '/API/GetData',
                type: 'POST',
                contentType: 'application/json', // 必须设置为JSON
                data: JSON.stringify(field), // 序列化为JSON字符串
                success: function (res) {
                    // console.log(res);
                    if (res.length == 0) {
                        layer.alert("未查找到相关数据");
                    } else {

                        let myChart = echarts.init(document.getElementById('lineChart'));
                        const upColor = '#ec0000';
                        const upBorderColor = '#8A0000';
                        const downColor = '#00da3c';
                        const downBorderColor = '#008F28';
                        let timeDate = new Array();
                        let data = new Array();
                        let option;


                        for (let i = 0; i < res.length; i++) {


                            // const date = new Date(res[i].low.registrationTime);

                            const datetimeStr = res[i].open.RegistrationTime;
                            const timePart = datetimeStr.split('T')[1].split('.')[0]; // 获取 "01:52:08.39"

                            // timeDate.push(time);
                            data.push([timePart, res[i].open.BasisSpread, res[i].close.BasisSpread, res[i].low.BasisSpread, res[i].high.BasisSpread]);
                        }
                        let data0 = splitData(data);


                        //内部函数
                        function splitData(rawData) {
                            const categoryData = [];
                            const values = [];
                            for (var i = 0; i < rawData.length; i++) {
                                categoryData.push(rawData[i].splice(0, 1)[0]);
                                values.push(rawData[i]);
                            }
                            return {
                                categoryData: categoryData,
                                values: values
                            };
                        }

                        function calculateMA(dayCount) {
                            var result = [];
                            for (var i = 0, len = data0.values.length; i < len; i++) {
                                if (i < dayCount) {
                                    result.push('-');
                                    continue;
                                }
                                var sum = 0;
                                for (var j = 0; j < dayCount; j++) {
                                    sum += +data0.values[i - j][1];
                                }
                                result.push(parseFloat((sum / dayCount).toFixed(2)));
                            }
                            return result;
                        }


                        option = {
                            title: {
                                text: '金融图示',
                                left: 0
                            },
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'cross'
                                }
                            },
                            legend: {
                                data: ['数据', 'MIN5']
                            },
                            grid: {
                                left: '10%',
                                right: '10%',
                                bottom: '15%'
                            },
                            xAxis: {
                                type: 'category',
                                data: data0.categoryData,
                                boundaryGap: false,
                                axisLine: {show: false},
                                min: 'dataMin',
                                max: 'dataMax'
                            },
                            yAxis: {
                                scale: true,
                                asplitArea: {
                                    show: true
                                }
                            },
                            dataZoom: [
                                {
                                    type: 'inside',
                                    start: 50,
                                    end: 100
                                },
                                {
                                    show: true,
                                    type: 'slider',
                                    top: '90%',
                                    start: 50,
                                    end: 100
                                }
                            ],
                            series: [
                                {
                                    name: '数据',
                                    type: 'candlestick',
                                    data: data0.values,
                                    itemStyle: {
                                        color: upColor,
                                        color0: downColor,
                                        borderColor: upBorderColor,
                                        borderColor0: downBorderColor
                                    },
                                    markPoint: {
                                        markPoint: {
                                            label: {
                                                formatter: function (param) {
                                                    return param != null ? Math.round(param.value) + '' : '';
                                                }
                                            },
                                            data: [
                                                {
                                                    name: 'Mark',
                                                    coord: ['2013/5/31', 2300],
                                                    value: 2300,
                                                    itemStyle: {
                                                        color: 'rgb(41,60,85)'
                                                    }
                                                },
                                                {
                                                    name: 'highest value',
                                                    type: 'max',
                                                    valueDim: 'highest'
                                                },
                                                {
                                                    name: 'lowest value',
                                                    type: 'min',
                                                    valueDim: 'lowest'
                                                },
                                                {
                                                    name: 'average value on close',
                                                    type: 'average',
                                                    valueDim: 'close'
                                                }
                                            ],
                                            tooltip: {
                                                formatter: function (param) {
                                                    return param.name + '<br>' + (param.data.coord || '');
                                                }
                                            }
                                        },
                                        markLine: {
                                            symbol: ['none', 'none'],
                                            data: [
                                                [
                                                    {
                                                        name: 'from lowest to highest',
                                                        type: 'min',
                                                        valueDim: 'lowest',
                                                        symbol: 'circle',
                                                        symbolSize: 10,
                                                        label: {
                                                            show: false
                                                        },
                                                        emphasis: {
                                                            label: {
                                                                show: false
                                                            }
                                                        }
                                                    },
                                                    {
                                                        type: 'max',
                                                        valueDim: 'highest',
                                                        symbol: 'circle',
                                                        symbolSize: 10,
                                                        label: {
                                                            show: false
                                                        },
                                                        emphasis: {
                                                            label: {
                                                                show: false
                                                            }
                                                        }
                                                    }
                                                ],
                                                {
                                                    name: 'min line on close',
                                                    type: 'min',
                                                    valueDim: 'close'
                                                },
                                                {
                                                    name: 'max line on close',
                                                    type: 'max',
                                                    valueDim: 'close'
                                                }
                                            ]
                                        }
                                    }
                                },
                                {
                                    name: 'MIN5',
                                    type: 'line',
                                    data: calculateMA(5),
                                    smooth: true,
                                    lineStyle: {
                                        opacity: 0.5
                                    }
                                }
                            ]
                        };
                        option && myChart.setOption(option);
                    }

                },
                error: function (err) {
                    layer.alert(err);
                }
            });

            return false;
        });
    });
</script>
</body>
</html>