$(function() {
    // 1. 资金流向/融资融券/恐贪指数
    function fetchNorth() {
        $.get('/api/hsgt/northbound', function(res) {
            if(res.status === 'success') {
                renderNorthChart(res.data);
            } else {
                $('#northChart').html('<div style="color:#888;text-align:center;padding-top:40px;">交易日9点20采集，暂无数据或数据未更新</div>');
            }
        }).fail(function() {
            $('#northChart').html('<div style="color:#888;text-align:center;padding-top:40px;">交易日9点20采集，暂无数据或数据未更新</div>');
        });
    }
    function fetchSouth() {
        $.get('/api/hsgt/southbound', function(res) {
            if(res.status === 'success') {
                renderSouthChart(res.data);
            } else {
                $('#southChart').html('<div style="color:#888;text-align:center;padding-top:40px;">交易日9点20采集，暂无数据或数据未更新</div>');
            }
        }).fail(function() {
            $('#southChart').html('<div style="color:#888;text-align:center;padding-top:40px;">交易日9点20采集，暂无数据或数据未更新</div>');
        });
    }
    fetchNorth();
    fetchSouth();
    setInterval(fetchNorth, 2 * 60 * 1000);
    setInterval(fetchSouth, 2 * 60 * 1000);

    $.get('/api/rzrq/chart_data?days=90', function(res) {
        if(res.status === 'success') renderRzrqChart(res.data);
    });
    $.get('/api/fear_greed/data?limit=180', function(res) {
        if(res.status === 'success') renderFearGreedChart(res.data);
    });

    // 2. 概念PE和拥挤度
    const concepts = [
        {name: "先进封装", peId: "peChart_xjfz", crowdId: "crowdChart_xjfz"},
        {name: "芯片", peId: "peChart_xp", crowdId: "crowdChart_xp"},
        {name: "消费电子概念", peId: "peChart_xfdz", crowdId: "crowdChart_xfdz"},
        {name: "机器人概念", peId: "peChart_jqr", crowdId: "crowdChart_jqr"}
    ];
    concepts.forEach(c => {
        $.get(`/api/industry/analysis?concept_name=${encodeURIComponent(c.name)}&metric=pe`, function(res) {
            if(res.status === 'success') {
                renderPEChart(c.peId, res.data);
                renderCrowdChart(c.crowdId, res.data.crowding);
            }
        });
    });

    // --- 渲染函数 ---
    const chartInstances = {};
    function renderNorthChart(data) {
        if(!data || !data.data || !data.times) return;
        const dom = document.getElementById('northChart');
        const chart = echarts.init(dom);
        chartInstances['northChart'] = chart;
        chart.setOption({
            title: {text: '', show: false},
            tooltip: {trigger: 'axis'},
            legend: {data: ['北向资金','沪股通','深股通'], top: 5, textStyle: {color:'#333'}},
            grid: {left: '5%', right: '5%', top: 30, bottom: 20, containLabel: true},
            xAxis: {type: 'category', data: data.times, axisLabel: {rotate: 0, color:'#666', interval: 'auto'}},
            yAxis: {type: 'value', name: '亿元', axisLabel: {color:'#666'}},
            series: [
                {name: '北向资金', type: 'line', data: data.data.total, symbol: 'none', lineStyle:{width:2}},
                {name: '沪股通', type: 'line', data: data.data.sh, symbol: 'none'},
                {name: '深股通', type: 'line', data: data.data.sz, symbol: 'none'}
            ]
        });
        // 只绑定容器的原生点击事件
        dom.onclick = function() {
            for(const k in chartInstances) {
                if(k !== 'northChart' && chartInstances[k]) {
                    chartInstances[k].dispatchAction({ type: 'hideTip' });
                }
            }
        };
    }
    function renderSouthChart(data) {
        if(!data || !data.data || !data.times) return;
        const dom = document.getElementById('southChart');
        const chart = echarts.init(dom);
        chartInstances['southChart'] = chart;
        chart.setOption({
            title: {text: '', show: false},
            tooltip: {trigger: 'axis'},
            legend: {data: ['南向资金','沪市港股通','深市港股通'], top: 5, textStyle: {color:'#333'}},
            grid: {left: '5%', right: '5%', top: 30, bottom: 20, containLabel: true},
            xAxis: {type: 'category', data: data.times, axisLabel: {rotate: 0, color:'#666', interval: 'auto'}},
            yAxis: {type: 'value', name: '亿元', axisLabel: {color:'#666'}},
            series: [
                {name: '南向资金', type: 'line', data: data.data.total, symbol: 'none', lineStyle:{width:2}},
                {name: '沪市港股通', type: 'line', data: data.data.hk_sh, symbol: 'none'},
                {name: '深市港股通', type: 'line', data: data.data.hk_sz, symbol: 'none'}
            ]
        });
        dom.onclick = function() {
            for(const k in chartInstances) {
                if(k !== 'southChart' && chartInstances[k]) {
                    chartInstances[k].dispatchAction({ type: 'hideTip' });
                }
            }
        };
    }
    function renderRzrqChart(data) {
        if(!data || !data.dates || !data.series) return;
        const dom = document.getElementById('rzrqChart');
        const chart = echarts.init(dom);
        chartInstances['rzrqChart'] = chart;
        const s = data.series[0];
        let min = Math.min(...s.data.filter(v => v !== null && v !== undefined));
        min = Math.floor(min * 0.98);
        chart.setOption({
            title: {text: '', show: false},
            tooltip: {trigger: 'axis'},
            legend: {data: [s.name], top: 5, textStyle: {color:'#333'}},
            grid: {left: '5%', right: '5%', top: 30, bottom: 20, containLabel: true},
            xAxis: {type: 'category', data: data.dates, axisLabel: {rotate: 0, color:'#666', interval: 'auto'}},
            yAxis: {type: 'value', name: s.unit, axisLabel: {color:'#666'}, min: min},
            series: [{name: s.name, type: 'line', data: s.data, symbol: 'none', lineStyle:{width:2}}]
        });
        dom.onclick = function() {
            for(const k in chartInstances) {
                if(k !== 'rzrqChart' && chartInstances[k]) {
                    chartInstances[k].dispatchAction({ type: 'hideTip' });
                }
            }
        };
    }
    function renderFearGreedChart(data) {
        if(!data || !data.dates || !data.values) return;
        const dom = document.getElementById('fearGreedChart');
        const chart = echarts.init(dom);
        chartInstances['fearGreedChart'] = chart;
        let min = Math.min(...data.values.filter(v => v !== null && v !== undefined));
        min = Math.floor(min * 0.98);
        chart.setOption({
            title: {text: '', show: false},
            tooltip: {trigger: 'axis'},
            legend: {data: ['恐贪指数'], top: 5, textStyle: {color:'#333'}},
            grid: {left: '5%', right: '5%', top: 30, bottom: 20, containLabel: true},
            xAxis: {type: 'category', data: data.dates, axisLabel: {rotate: 0, color:'#666', interval: 'auto'}},
            yAxis: {type: 'value', min: min, max: 100, axisLabel: {color:'#666'}},
            series: [{name: '恐贪指数', type: 'line', data: data.values, symbol: 'none', lineStyle:{width:2, color:'#f0ad4e'}}]
        });
        dom.onclick = function() {
            for(const k in chartInstances) {
                if(k !== 'fearGreedChart' && chartInstances[k]) {
                    chartInstances[k].dispatchAction({ type: 'hideTip' });
                }
            }
        };
    }
    function renderPEChart(domId, data) {
        if(!data || !data.series || !data.xAxis || !data.xAxis[0] || !data.xAxis[0].data) return;
        const dom = document.getElementById(domId);
        const chart = echarts.init(dom);
        chartInstances[domId] = chart;
        const mainSeries = data.series.filter(s => s.name.indexOf('平均PE') !== -1 || s.name.indexOf('PE') !== -1);
        mainSeries.forEach(s => { s.symbol = 'none'; });
        let allValues = [];
        mainSeries.forEach(s => allValues = allValues.concat(s.data.filter(v => v !== null && v !== undefined)));
        let min = Math.min(...allValues);
        min = Math.floor(min * 0.98);
        chart.setOption({
            title: {text: '', show: false},
            tooltip: {trigger: 'axis'},
            legend: {show: false},
            grid: {left: '5%', right: '5%', top: 30, bottom: 20, containLabel: true},
            xAxis: {type: 'category', data: data.xAxis[0].data, axisLabel: {rotate: 0, color:'#666', interval: 'auto'}},
            yAxis: {type: 'value', name: data.yAxis[0].name, axisLabel: {color:'#666'}, min: min},
            series: mainSeries,
            dataZoom: [
                {type: 'inside', start: 0, end: 100, zoomOnTouch: true, moveOnMouseWheel: true}
            ]
        });
        dom.onclick = function() {
            for(const k in chartInstances) {
                if(k !== domId && chartInstances[k]) {
                    chartInstances[k].dispatchAction({ type: 'hideTip' });
                }
            }
        };
    }
    function renderCrowdChart(domId, crowding) {
        if(!crowding || !crowding.dates || !crowding.percentiles) return;
        // 展示近一年（240天）数据
        let dates = crowding.dates;
        let percentiles = crowding.percentiles;
        if(dates.length > 240) {
            dates = dates.slice(-240);
            percentiles = percentiles.slice(-240);
        }
        const dom = document.getElementById(domId);
        const chart = echarts.init(dom);
        chartInstances[domId] = chart;
        let min = Math.min(...percentiles.filter(v => v !== null && v !== undefined));
        min = Math.floor(min * 0.98);
        // 检查最后一个点是否需要高亮
        let markPoint = undefined;
        const lastVal = percentiles[percentiles.length-1];
        if(lastVal !== undefined && (lastVal > 80 || lastVal < 20)) {
            markPoint = {
                data: [{
                    coord: [dates[dates.length-1], lastVal],
                    symbol: 'circle',
                    symbolSize: 16,
                    itemStyle: {
                        color: lastVal > 80 ? '#ff3333' : '#33cc33',
                        shadowBlur: 20,
                        shadowColor: lastVal > 80 ? '#ff3333' : '#33cc33',
                        opacity: 1
                    },
                    label: {show: false},
                    animation: true,
                    animationDuration: 500,
                    animationEasing: 'bounceOut',
                    animationDurationUpdate: 500,
                    animationEasingUpdate: 'bounceOut',
                    effect: {
                        show: true,
                        period: 1,
                        scaleSize: 2,
                        color: lastVal > 80 ? '#ff3333' : '#33cc33',
                        shadowBlur: 10
                    }
                }]
            };
        }
        chart.setOption({
            title: {text: '', show: false},
            tooltip: {trigger: 'axis'},
            legend: {data: ['拥挤度历史百分位'], top: 5, textStyle: {color:'#333'}},
            grid: {left: '5%', right: '5%', top: 30, bottom: 20, containLabel: true},
            xAxis: {type: 'category', data: dates, axisLabel: {rotate: 0, color:'#666', interval: 'auto'}},
            yAxis: {type: 'value', min: min, max: 100, name: '百分位(%)', axisLabel: {color:'#666'}},
            series: [{
                name: '拥挤度历史百分位',
                type: 'line',
                data: percentiles,
                symbol: 'none',
                lineStyle:{width:2, color:'#ff7f50'},
                markPoint: markPoint
            }],
            dataZoom: [
                {type: 'inside', start: 0, end: 100, zoomOnTouch: true, moveOnMouseWheel: true}
            ]
        });
        dom.onclick = function() {
            for(const k in chartInstances) {
                if(k !== domId && chartInstances[k]) {
                    chartInstances[k].dispatchAction({ type: 'hideTip' });
                }
            }
        };
    }

    // 统一resize自适应
    $(window).on('resize', function() {
        for(const key in chartInstances) {
            if(chartInstances[key] && chartInstances[key].resize) {
                chartInstances[key].resize();
            }
        }
    });
});
