<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,viewport-fit=cover">
    <title>汤大画盘 v0.1.5beta</title>
    <link rel="stylesheet" href="https://unpkg.com/layui@2.8.18-rc.2/dist/css/layui.css" media="all">
    <link rel="stylesheet" href="//cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.css" media="all">
    <link rel="stylesheet" href="/css/admin/common/nav.css" media="all">
    <link rel="stylesheet" href="/css/admin/common/side-bar.css" media="all">
    <link rel="stylesheet" href="/css/admin/drawLine/draw-line.css" media="all">
    <style>
    </style>
</head>
<body>

    <div class="nav">
        <div class="nav-logo"><span>汤大画盘</span></div>
        <div class="layui-form" style="margin-left: 10px;">
            <div class="layui-input-inline">
                <input type="text" id="gpCode" name="title" lay-verify="title" autocomplete="off" placeholder="请输入股票代码" class="layui-input" style="position:absolute;z-index:2;background: #eee!important;">
                <select lay-filter="gpSelect" class="layui-select"></select>
            </div>
            <div class="layui-input-inline">
                <input type="checkbox" id="autoFixed" lay-filter="autoFixed" value="on" name="autoFixed" lay-skin="tag" title="画盘自适应" checked>
            </div>
        </div>
        <div class="nav-hidden-btn"><i class="fa fa-fw fa-th-list"></i></div>
        <ul class="nav-main">
            <li class="nav-item">
                <a class="nav-link" aria-current="true" href="javascript:showSideBar(0, true)">
                    <i class="fa fa-fw fa-folder-open nav-icon">
                    </i>
                    工作区
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" aria-current="true" target="_blank" href="/admin/docs">
                    <i class="fa fa-fw fa-question nav-icon">
                    </i>
                    使用文档
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" aria-current="true" href="javascript:showSideBar(1, true)">
                    <i class="fa fa-fw fa-info-circle nav-icon">
                    </i>
                    系统信息
                </a>
            </li>
        </ul>
    </div>
    
    <div class="side-bar-shadow"></div>
    <div class="side-bar" data-index="0" style="padding: 20px">
        <button type="button" class="layui-btn layui-btn-sm" id="load-from-wencai">别点</button>
        <ul class="stock-list">
            <li><span>这里没有完成，不用看了</span><button type="button" class="layui-btn layui-btn-xs">删除</button></li>
            <li><span>宝馨科技 002514</span><button type="button" class="layui-btn layui-btn-xs">删除</button></li>
            <li><span>宝馨科技 002514</span><button type="button" class="layui-btn layui-btn-xs">删除</button></li>
            <li><span>宝馨科技 002514</span><button type="button" class="layui-btn layui-btn-xs">删除</button></li>
            <li><span>宝馨科技 002514</span><button type="button" class="layui-btn layui-btn-xs">删除</button></li>
        </ul>
    </div>
    <div class="side-bar" data-index="1" style="padding: 20px; width: 300px">

    </div>
    <div class="main layui-bg-gray" style="padding:10px">
        <div class="layui-row layui-panel">
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header"><h3><b id="gpName">请输入股票代码后载入数据</b></h3></div>
                    <div class="layui-card-body">
                        <div id="stock-info-large" class="layui-row">
                            <div class="layui-col-xs3">
                                <p class="detail-date" key="dateStr" default="-">-</p>
                                <p class="close" key="close" color="-1,close">0.00</p>
                                <span class="change" key="change" color="0" title="涨跌额(元)">0.00</span>
                                <span class="pct-chg" key="pctChg" unit="%" color="0" title="涨跌幅(除权)" default="0.00%">0.00%</span>
                            </div>
                            <div class="layui-col-xs3">
                                <p class="norm"><label>开</label><span key="open" color="-1,close">0.00</span></p>
                                <p class="norm"><label>高</label><span key="high" color="0,open">0.00</span></p>
                                <p class="norm"><label>低</label><span key="low" color="0,open">0.00</span></p>
                            </div>
                            <div class="layui-col-xs3">
                                <p class="norm"><label>市值</label><span key="totalMv" short="true" ratio="10000" title="元">0.00</span></p>
                                <p class="norm"><label>流通</label><span key="circMv" short="true" ratio="10000" title="元">0.00</span></p>
                                <p class="norm"><label>市盈<sup>TTM</sup></label><span key="peTtm" default="-">-</span></p>
                            </div>
                            <div class="layui-col-xs3">
                                <p class="norm"><label>量</label><span key="vol" short="true" title="手">0.00</span></p>
                                <p class="norm"><label>换</label><span key="turnoverRate" unit="%" default="0.00%">0.00%</span></p>
                                <p class="norm"><label>额</label><span key="amount" ratio="1000" short="true" title="元">0.00</span></p>
                            </div>
                            <div id="range-info-large" class="layui-row layui-col-xs12">
                                <div>选择范围查看统计</div>
                            </div>
                        </div>
                        <div id="stock-chart" class="chart-container">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6 layui-form" style="padding-top:30px">
                <div class="layui-fluid">
                    <table id="anchor-table" lay-filter="anchor-table">
                    </table>
                </div>
            </div>
        </div>
    </div>
    <!-- 画盘配置项 -->
    <div id="draw-rules-layer" class="layui-form draw-rules" lay-filter="draw-rules">
    </div>
    <script type="text/html" id="toolbar">
  <div class="layui-btn-container">
    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" lay-event="drawSettings" title="设置画盘点位"><i class="svg-icon draw-settings"></i>点位设置</button>
    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" lay-event="clearPeriodBlock" title="清除图表上的周期色块"><i class="svg-icon clear-period-block" ></i>清除周期色块</button>
  </div>
	</script>
<script type="text/javascript" src="/js/echarts/5.4.0/echarts.min.js"></script>
<script type="text/javascript" src="/js/common/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/layui@2.8.18-rc.2/dist/layui.js"></script>
<script type="text/javascript" src="/js/common/indicators.js"></script>
<script type="text/javascript" src="/js/common/cookies.js"></script>
<script type="text/javascript" src="/js/admin/common/side-bar.js"></script>
<script type="text/javascript" src="/js/admin/drawLine/drawLine.js"></script>
<script type="text/javascript" src="/js/admin/drawLine/customs.js"></script>
<script>
// 配置项
let cciCnt = 20, tableIns = null, allAnchorIndexes = [];
layui.use(['table', 'slider', 'element', 'form'], function() {
	
	if (!Cookies.get("closeAlert20230817")) {
		layer.confirm(
		'由于 2024-01-08 万得挂了，导致 tushare 也挂了，数据不全，待恢复后会更新。', 
		{
			title: '2024-01-08',
			end: () => {
				Cookies.set('closeAlert20240108', 1);
			}
		});
	}
	
	
    let table = layui.table, slider = layui.slider, form = layui.form;
    
    // autoFixed
    if (Cookies.get('autoFixed') != 'true') {
        $('#autoFixed').prop('checked', false);
    	Cookies.set('autoFixed', false);
    }
    else {
    	$('#autoFixed').prop('checked', true);
    }
    form.render();
    form.on('checkbox(autoFixed)', function(value){
    	Cookies.set('autoFixed', value.elem.checked);
    	if ($('#gpCode').val()) {
    		loadData($('#gpCode').val());
    	}
    });
    
    
    tableIns = table.render({
        elem: '#anchor-table',
        page: true,
        toolbar: '#toolbar',
        text: {none: '请输入股票代码查询数据'},
        cols: [ (function() {
        	let a = [ {
	            field: 'dateStr',
	            title: '锚点变更日',
	            templet: (d) => {
	            	return '<a href="javascript:toGraphicsIndex(' + d.anchorDateIndex + ',' + d.period + ')" class="jump-to-stock">' + d.dateStr + '</a>';
	            }
	        },
            /*{
                field: 'priceHolderTop',
                title: '股东顶',
                templet: (d) => {
                    return d.priceHolderTop.toFixed(2);
                }
            },*/
	        {
	            field: 'period',
	            title: '能量(标准化)',
	            templet: (d) => {
	                return `<div title="${d.originalPeriod}">${d.period.toFixed(3)}</div>`;
	            }
	        },
	        {
	            field: 'anchorTypes',
	            title: '锚点类型',
	            templet: (d) => {
	            	let u = (t) => {
	            		let b = t == '向上突破';
	            		return `<b class="${(b?'red':'green')}" title="${t}">${(b?'↑':'↓')}</b>`;
	            	}
	            	if (d.anchorType1 && d.anchorType2) {
	            		return d.anchorType1 + u(d.anchorType2);
	            	}
	                if (d.anchorType1) {
	                    return d.anchorType1;
	                }
	                if (d.anchorType2) {
	                    return u(d.anchorType2);
	                }
	            }
	        }], i = 1;
            customs.getAnchorOptionToGridCols().forEach((col) => {
            	a.splice(i++, 0, col);
            });
            return a;
        })()],
        data: [],
        height: 'full-180'
    });
    table.on('toolbar(anchor-table)', function (param) {
        switch (param.event) {
        case 'drawSettings':
	        let cols = customs.getAnchorOption(), drawLayer = $('#draw-rules-layer').empty().prop('optionChanged', false),
	        getOption = (div) => {
                return {
                    title: div.children('[name="title"]').val(),
                    ratio: Number(div.children('[name="ratio"]').val()),
                    chart: div.children('[name="chart"]').next().hasClass('layui-form-checked'),
                    grid: div.children('[name="grid"]').next().hasClass('layui-form-checked')
                }
            },
            setOption = (div, option) => {
                div.children('[name="title"]').val(option.title);
                div.children('[name="ratio"]').val(option.ratio);
                div.children('[name="chart"]').prop('checked', option.chart);
                div.children('[name="grid"]').prop('checked', option.grid);
            }, templet = (col) => `<div class="draw-rule">
                <input class="layui-inline layui-input layui-input-inline" style="width: 100px" placeholder="名称" name="title" value="${col.title}"></input>
                <input class="layui-inline layui-input layui-input-inline" style="width: 100px" placeholder="系数" name="ratio" type="number" step="0.001" value="${col.ratio}"></input>
                <input type="checkbox" name="chart" title="图表" ${col.chart?'checked':''}>
                <input type="checkbox" name="grid" title="表格" ${col.grid?'checked':''}>
                <button type="button" class="layui-btn layui-btn-sm ${!col.first ? 'layui-btn-normal':'layui-btn-disabled'}" title="上移"><i class="fa fa-fw fa-arrow-up"></i></button>
                <button type="button" class="layui-btn layui-btn-sm ${!col.last  ? 'layui-btn-normal':''}" title="${col.last? '添加':'下移'}"><i class="fa fa-fw ${col.last?'fa-plus':'fa-arrow-down'}"></i></button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" title="删除该条画盘点位"><i class="fa fa-fw fa-trash"></i></button></div>`,
            genDiv = (col) => {
                return $(templet(col)).on('click', '.layui-btn:not(.layui-btn-disabled)', (e) => {
                    let target = $(e.currentTarget), curr = target.parent();
                    if (target.find('i.fa-arrow-up').length) {
                        let prev = target.parent().prev(),
                        prevOption = getOption(prev), currOption = getOption(curr);
                        if (prev.find('.layui-btn-disabled').length) {
                            target.removeClass('layui-btn-normal').addClass('layui-btn-disabled');
                            prev.children('.layui-btn-disabled').removeClass('layui-btn-disabled').addClass('layui-btn-normal');
                        }
                        if (curr.find('i.fa-plus').length) {
                            curr.find('i.fa-plus').removeClass('fa-plus').addClass('fa-arrow-down')
                            .parent().addClass('layui-btn-normal').attr('title', '下移');
                            prev.find('i.fa-arrow-down').removeClass('fa-arrow-down').addClass('fa-plus')
                            .parent().removeClass('layui-btn-normal').attr('title', '添加');
                        }
                        let temp = prev.html();
                        prev.html(curr.html());
                        curr.html(temp);
                        setOption(prev, currOption); setOption(curr, prevOption);
                        drawLayer.prop('optionChanged', true);
                    }
                    else if (target.find('i.fa-arrow-down').length) {
                        let next = target.parent().next(),
                        nextOption = getOption(next), currOption = getOption(curr);
                        if (curr.find('.layui-btn-disabled').length) {
                            target.prev().removeClass('layui-btn-disabled').addClass('layui-btn-normal');
                            next.children('.layui-btn:first').addClass('layui-btn-disabled').removeClass('layui-btn-normal');
                        }
                        if (next.find('i.fa-plus').length) {
                            next.find('i.fa-plus').removeClass('fa-plus').addClass('fa-arrow-down')
                            .parent().addClass('layui-btn-normal').attr('title', '下移');
                            curr.find('i.fa-arrow-down').removeClass('fa-arrow-down').addClass('fa-plus')
                            .parent().removeClass('layui-btn-normal').attr('title', '添加');
                        }
                        let temp = next.html();
                        next.html(curr.html());
                        curr.html(temp);
                        setOption(next, currOption); setOption(curr, nextOption);
                        drawLayer.prop('optionChanged', true);
                    }
                    else if (target.find('i.fa-trash').length) {
                        let prev = curr.prev(), next = curr.next();
                        if (!prev.length && !next.length) {
                            layer.alert('至少留一个画盘点位！', {icon:2});
                            return;
                        }
                        if (curr.find('.layui-btn-disabled').length && next.length) {
                            next.find('.layui-btn:first').removeClass('layui-btn-normal').addClass('layui-btn-disabled');
                        }
                        if (curr.find('.fa-plus').length && prev.length) {
                            prev.find('.fa-arrow-down').removeClass('fa-arrow-down').addClass('fa-plus')
                            .parent().removeClass('layui-btn-normal').attr('title', '添加');
                        }
                        curr.remove();
                        drawLayer.prop('optionChanged', true);
                    }
                    else if (target.find('i.fa-plus').length) {
                        curr.find('i.fa-plus').removeClass('fa-plus').addClass('fa-arrow-down')
                        .parent().addClass('layui-btn-normal').attr('title', '下移');
                        drawLayer.append(genDiv({title:'', ratio:0, grid: true, chart: true, first:false, last:true}));
                        drawLayer.prop('optionChanged', true);
                    }
                    form.render(null, 'draw-rules');
                }).on('change', 'input', (e) => {
                    drawLayer.prop('optionChanged', true);
                }).on('click', '.layui-form-checkbox', (e) => {
                    drawLayer.prop('optionChanged', true);
                });
            };
	        cols.forEach((col, i) => {
	        	col.first = i == 0, col.last = i == cols.length - 1;
	            drawLayer.append(genDiv(col));
	        });
	   		//drawLayer.html();
	   		form.render(null, 'draw-rules');
	    	layer.open({
	    		title: '设置画盘点位',
	   	        type: 1,
	   	        btn: ['确定', '取消', '恢复默认'],
		   	    success: function(layero, index){
		   	        layero.find('.layui-layer-content:first').css('overflow-x', 'hidden');
		   	    },
	   	        yes: (index, layero) => {
	   	        	if (drawLayer.prop('optionChanged')) {
                        let anchorOption = [];
                        $.each(drawLayer.find('.draw-rule'), (i, div) => {
                            anchorOption.push(getOption($(div)));
                        });
                        customs.setAnchorOption(anchorOption);
                        layer.alert('刷新页面后生效', {icon: 1});
                    }
                    layer.close(index);
	   	        },
	   	        btn2: (index, layero) => {
                    if (drawLayer.prop('optionChanged')) {
                        layer.confirm('设置已变更，确定放弃更改？', (i) => {
                            layer.close(index);
                            layer.close(i);
                        });
                    }
                    else {
                        layer.close(index);
                    }
                    return false; 
                },
                btn3: (index, layero) => {
                    layer.confirm('确认要恢复默认吗？已有的设置将丢失', (i) => {
                        Cookies.setObj('anchorOption', null, -1);
                        layer.alert('已恢复默认，刷新页面后生效', {icon: 1});
                        layer.close(index);
                        layer.close(i);
                    });
                    return false;
                },
                cancel: (index, layero) => {
                    if (drawLayer.prop('optionChanged')) {
                        layer.confirm('设置已变更，确定放弃更改？', (i) => {
                            layer.close(index);
                            layer.close(i);
                        });
                    }
                    else {
                        layer.close(index);
                    }
                    return false; 
                },
	   	        btnAlign: 'c',
	   	        shadeClose: true,
	   	        resizing: (el) => {
	   	        	el.width(drawLayer[0].clientWidth);
	   	        },
	   	        content: drawLayer
	   	    });
	   	    break;
   	    case 'clearPeriodBlock':
            myChart.setOption({series: [ {
                markArea: {data: undefined}}]});
        }
    });
    form.on('select(gpSelect)', (data) => {
        loadData(data.value);
        // location.hash = data.value;
        document.getElementById('gpCode').value = data.value;
    });
});
let addCurr = (index, layero) => {
    
};
$('#load-from-wencai').on('click', (e) =>{
    layer.open({
        type: 2,
        area: ['700px', '450px'],
        fixed: false, //不固定
        maxmin: true,
        content: 'http://www.iwencai.com/',
        btn: ['添加当前页', '取消'],
        yes: (index, layero) => {
            addCurr(index, layero);
        }
    });
})
let myChart = echarts.init(document.getElementById('stock-chart'), 'white', {
    renderer: 'canvas'
});
myChart.on('legendselectchanged', function (param) {
    Cookies.setObj('legendSelected', param.selected);
});
let autoCompleteIndex = 0;
let autoComplete = (e) => {
    autoCompleteIndex++;
	let input = document.getElementById('gpCode').value.trim(), thisIndex = autoCompleteIndex;
    if (input == '') return;
    let url = 'https://searchapi.eastmoney.com/api/suggest/get';
    $.ajax({
        url: url,
        jsonp: 'cb',
        data: {
            input: input,
            type: 14,
            securitytype: '1,2,25',
            token: 'D43BF722C8E33BDC906FB84D85E326E8',
            count: 5,
            _: new Date().getTime()
        },
        crossDomain: true,
        dataType: 'jsonp',
        success: (data) => {
            let gpSelect = $('[lay-filter=gpSelect]').empty();
            data = data.QuotationCodeTable.Data;
            if (!data) return;
            if (autoCompleteIndex > thisIndex) return;
            data.forEach((i) => {
                let html = [];
                i.QuoteID = i.QuoteID.substr(-6);
                html.push('<option value="' + i.QuoteID + '">');
                html.push(i.Name + '(' + i.QuoteID + ')' + '</option>');
                gpSelect.append(html.join(''));
            });
            layui.form.render();
            gpSelect.siblings('.layui-form-select').addClass('layui-form-selected');
        }
    });
};

$('#gpCode').on('keyup', (e) => {
    let gpCodeInput = $('#gpCode'),
        dropdown = gpCodeInput.siblings('.layui-form-selected').find('dd.layui-this');
    if (e.keyCode == 13) {
        // 如果下拉框有内容且选中内容
        if (dropdown.length)
            dropdown.click();
        else
            //location.hash = $('#gpCode').val().trim();
            loadData($('#gpCode').val().trim());
    }
    else if (e.keyCode == 38 || e.keyCode == 40) {
        let dropdownList = gpCodeInput.siblings('.layui-form-selected').find('dd');
        if (dropdownList.length) {
            $.each(dropdownList, (i, v) => {
                v = $(v);
                if (v.hasClass('layui-this')) {
                    let target = i + e.keyCode - 39;
                    if (target >= 0 && target < dropdownList.length) {
                        $(dropdownList[target]).addClass('layui-this');
                        v.removeClass('layui-this');
                    }
                    return false;
                }
            });
        }
    }
    /*else {
    	autoComplete(e);
    }*/
}).on('input', (e) => {autoComplete(e);}).on('click', (e) => {autoComplete(e);});

//echart 的 data 顺序: 开 收 低 高
let convertData = (resp) =>{
    // categoryData: 日期
    // values: 股价
    // volume: 成交量
    allAnchorIndexes = {};
    let categoryData = [], values = [], bases = [], volumes = [], holderTops = [],
        powers = [], energys = [], anchorEnergys = [], energyRatios = [],
        customAnchors = customs.getAnchorOptionForChart(),
        anchorIndex = -1, anchorStarted = false, anchors = resp.anchors,
        anchorIndexes = [], baseTypes = ['新高量', '基本'],
        latestMaxVolIndex = -1,
        updateAnchor = (index, i) => {
        	if (index == -1) {
                customAnchors.forEach((col) =>{
                	col.data.push('-');
                })
                holderTops.push('-');
                anchorEnergys.push('-');
                energyRatios.push('-');
        	}
        	else {
                let anchor = anchors[index], energyRatio = '-';
                if (i != undefined && baseTypes.indexOf(anchor.anchorType1) != -1 && anchorIndexes.indexOf(i) == -1) {
                    anchorIndexes.push(i);
                    latestMaxVolIndex = i;
                }
                customAnchors.forEach((col) =>{
                    col.data.push((col.ratio * anchor.priceUnit + anchor.priceBase).toFixed(2));
                })
                holderTops.push(anchor.priceHolderTop != null ? anchor.priceHolderTop.toFixed(2) : '-');
                anchorEnergys.push(anchor.originalPeriod);
                energyRatio = energys[anchorEnergys.length - 1] / anchor.originalPeriod;
                // 正则化 energyRatio 到 [1, 10)
                if (energyRatio < 1) {
                    while (energyRatio < 1) {
                        energyRatio *= 10;
                    }
                }
                else if (energyRatio >= 10) {
                    while (energyRatio >= 10) {
                        energyRatio /= 10;
                    }
                }
                energyRatios.push(energyRatio);
        	}
        };
    for (let i = 0; i < resp.stockValueExList.length; i++) {
        let v = resp.stockValueExList[i], dateStr = v.dateStr, value = [v.open, v.close, v.low, v.high, v], limit = v.updownLimit,
        upDownJudge = 0, sideways = false;
        if (v.close < v.open) upDownJudge = -1;
        else if (v.close > v.open) upDownJudge = 1;
        else {
            sideways = true;
        	if (i != 0) {
	            let prev = resp.stockValueExList[i - 1];
	            if (v.close > prev.close) upDownJudge = 1;
	            else if (v.close < prev.close) upDownJudge = -1;
	        }
        }
        if (i < resp.powers[0].index) {
            powers.push('-');
        }
        else {
            powers.push(resp.powers[i - resp.powers[0].index].power);
        }
        energys.push(v.energy);
        categoryData.push(dateStr);
        values.push(limit === undefined ? !sideways ? value : {
            value: value, itemStyle: {
                color: middleColor,
                color0: middleColor,
                borderColor: middleColor,
                borderColor0: middleColor
            }
        } : {
            value: value, itemStyle: {
                color: limit == 1 ? upLimitColor : downLimitColor,
                color0: limit == 1 ? upLimitColor : downLimitColor,
                borderColor: limit == 1 ? upLimitColor : downLimitColor,
                borderColor0: limit == 1 ? upLimitColor : downLimitColor
            }
        });
        if (anchors && anchors.length) {
        	if (anchorIndex == anchors.length - 1 || anchors[anchorIndex + 1].dateStr != dateStr) {
        		updateAnchor(anchorIndex);
        	}
        	else {
                if (baseTypes.indexOf(anchors[++anchorIndex].anchorType1) != -1) upDownJudge *= 2;
        		updateAnchor(anchorIndex, i);
        	}
        }
        volumes.push([i, v.vol, upDownJudge]);
    }
    
    for (let i = 0; i < anchorIndexes.length - 1; i++) {
    	allAnchorIndexes[anchorIndexes[i]+''] = anchorIndexes[i+1];
    }
    allAnchorIndexes[anchorIndexes[anchorIndexes.length - 1] + ''] = null;
    window._values = values;
    return {
        categoryData: categoryData,
        values: values,
        volumes: volumes,
        powers: powers,
        energys: energys, anchorEnergys: anchorEnergys, energyRatios: energyRatios,
        customAnchors: customAnchors,
        latestMaxVolIndex: latestMaxVolIndex,
        holderTops: holderTops
    };
}
let prevHash = '';
let hashes = () => {
    let hash = location.hash.slice(1);
    if (hash !== undefined && hash != null && hash.trim() != '' && hash != prevHash) {
        $('#gpCode').val(hash);
        loadData(hash);
    }
}
hashes(location.hash.slice(1));
window.addEventListener('hashchange', hashes);
function loadData(stockCode) {
    prevHash = stockCode;
	if (location.hash.slice(1) != stockCode)
	    location.hash = stockCode;
	let loading = layer.load(2, {
        shade: [0.8, '#fff'],
        content:'正在加载，请耐心等待......',
        success: function (layerContentStyle) {
            $('#gpCode,#gpQueryBtn').attr('disabled', '').addClass('layui-disabled');
            layerContentStyle.find('.layui-layer-content').css({
                'padding-left': '45px',
                'text-align': 'left',
                'width': '175px',
                'line-height':'30px'
            });
        }
    });
    let url = `/admin/drawLine/priceAnchor?stockCode=${(!!stockCode ? stockCode: document.getElementById('gpCode').value)}&autoFixed=${$('#autoFixed').prop('checked')}`;
    $.ajax({
        type: 'GET',
        url: url,
        timeout: 20000,
        success: (resp) =>{
        	if (resp.code != 200) {
                if (resp.code == -10000) {
                    // Need relogin
                    layer.alert(resp.data, {icon: 2}, () => {
                        location.href = '/admin';
                    });
                }
                else layer.alert(resp.data, {icon: 2});
        		return;
        	}
            drawCharts(resp.data);
        },
        error: (XMLHttpRequest, textStatus, errorThrown) => {
            layer.alert('查询超时，请重试', {icon: 2});
        },
        complete: () => {
            layer.close(loading);
            $('#gpCode,#gpQueryBtn').removeAttr('disabled').removeClass('layui-disabled');
        }
    });
}

let drawCharts = (resp) => {
    document.getElementById('gpName').innerText = resp.stockInfo.name;
    
    $.each($('#stock-info-large [key]'), (i, el) => {
        el = $(el).removeClass('green').removeClass('red');
        let _default = el.attr('default');
        
        if (_default != undefined) {
            el.text(_default);
        }
        else {
            el.text('0.00');
        }
    });
    tableIns.reload({
    	data: JSON.parse(JSON.stringify(resp.anchors)).reverse(),
    	page: {
            curr: 1 //重新从第 1 页开始
        }
    });
    let option = myChart.getOption();
    if (option && option.series[0]) {
        option.series[0].markArea = {data: undefined};
    }
    // 首次载入完成，加载配置
    myChart.on('finished', function () {
        // 图例载入情况
        customs.dispatchSelected(myChart);
        myChart.off('finished');
    });
    window.finalOption = generateOption({
        data: resp,
        name: resp.stockInfo.name,
        cciRange: cciCnt,
        option: option,
        tooltipCallback: function (param) {
            let els = $('#stock-info-large [key]'), 
            p = param.find(o => o.seriesIndex == 0), 
            v = p.value[5], _data = window.finalOption.series[0].data,
            getV = (index) => {
                let iV = _data[index];
                return (iV).__proto__.constructor.name == 'Array' ? iV[4] : iV.value[4];
            }, changeColor = (el, o, ct) => {
                if (o > ct) {
                    el.addClass('red');
                }
                else if (o < ct) {
                    el.addClass('green');
                }
            };
            $.each(els, (i, el) => {
                try {
                    el = $(el).removeClass('green').removeClass('red');
                    let o = v[el.attr('key')],
                        color = el.attr('color'),
                        short = el.attr('short') == 'true',
                        ratio = el.attr('ratio') == undefined ? undefined : Number(el.attr('ratio')),
                        unit = el.attr('unit') == undefined ? '' : el.attr('unit'),
                        fixed = el.attr('fixed') == undefined ? undefined : Number(el.attr('fixed'));
                    if (o == undefined || o == null || o == '-') {
                        el.text('-');
                        return true;
                    }
                    if (color != undefined) {
                        if (color.indexOf(',') != -1) {
                            let ck = color.split(',')[1],
                                ci = Number(color.split(',')[0]);
                            if (ci == 0) {
                                changeColor(el, o, v[ck]);
                            }
                            else if (p.dataIndex > 0) {
                                changeColor(el, o, getV(p.dataIndex + ci)[ck]);
                            }
                        }
                        else changeColor(el, o, Number(color));
                    }
                    if (ratio != undefined) {
                        o *= ratio;
                    }
                    let u = undefined;
                    if (short) {
                        // 万，亿
                        if (o >= 100000000) {
                            o /= 100000000;
                            u = '亿';
                        }
                        else if (o >= 10000) {
                            o /= 10000; u = '万';
                        }
                    }
                    if (typeof o === 'number') {
                        fixed = fixed == undefined ? 2 : fixed;
                        o = o.toFixed(fixed);
                    }
                    if (u != undefined) {
                        o += u;
                    }
                    if (unit != undefined) {
                        o += unit;
                    }
                    el.text(o);
                }
                catch (ex) {
                    console.log(ex);
                }
            });
        }
    });
    myChart.setOption(finalOption, true);
    
    myChart.off('brushselected');
    myChart.on ('brushselected', (param) => {
        let rangeInfoEl =  $('#range-info-large'), getStockValueEx = (i) => {
            let value = finalOption.series[0].data[i];
            if (value.__proto__.constructor.name === 'Array') {
                return value[4];
            }
            else {
                return value.value[4];
            }
        }, cols = [
            (start, end) => {
                return `<span><b>${finalOption.xAxis[0].data[start]} - ${finalOption.xAxis[0].data[end]}(${end - start + 1})</b></span>`;
            },
            (start, end) => {
                let sum = 0, sumF = 0, i = start;
                while (i <= end){
                    let sv = getStockValueEx(i++);
                    sum += sv.turnoverRate;
                    sumF += sv.turnoverRateF;
                }
                let anchors = resp.anchors.filter(a => new Date(a.dateStr) <= new Date(getStockValueEx(start).dateStr) && ['新高量', '基本'].indexOf(a.anchorType1) != -1),
                    anchor = anchors.length ? anchors[anchors.length - 1] : undefined,
                    powerRatio = (turnoverSum) => {
                        if (!anchor) return '';
                        return `(${(turnoverSum/anchor.period).toFixed(0)})`;
                    };

                if (start == end) {
                    start = Math.max(0, start - 1);
                }
                let startClose = getStockValueEx(start).close,
                    endClose = getStockValueEx(end).close,
                    pctChg = (endClose - startClose) / startClose * 100,
                    color = pctChg > 0 ? 'red' : pctChg < 0 ? 'green' : '',
                    rangeEnergy = Math.pow(pctChg/100+1, 2) * sum / 100,
                    originalRangeEnergy = rangeEnergy;
                while (rangeEnergy < 1) rangeEnergy *= 10;
                while (rangeEnergy >= 10) rangeEnergy /= 10;
                return `<span><b>涨跌幅(除权)</b>: <font class="${color}">${pctChg.toFixed(2)}%</font></span>
                 <span title="累计换手，以及对再此之前最近一个锚点能量的倍率">
                     <b>累计换手(能量倍率)</b>: 
                    	 ${sum.toFixed(2)}%${powerRatio(sum)}
                 </span>
                 <span><b title="范围区间内涨跌幅、换手计算出的能量">累计能量</b>:
                	 <font title="${originalRangeEnergy}">${rangeEnergy.toFixed(2)}</font>
                 </span>`;
            }
        ];
        if (param.batch[0].areas.length) {
            let coordRange = param.batch[0].areas[0].coordRange,
            start = coordRange[0], end = coordRange[1];
            while (rangeInfoEl.children('div').length < cols.length) {
            	rangeInfoEl.append('<div></div>');
            }
            $.each(rangeInfoEl.children('div'), (i, el) => {
                $(el).html(cols[i](start, end));
            });
        }
        else {
            // 清除范围选择
            rangeInfoEl.children('div').empty();
            rangeInfoEl.children('div:first').text('选择范围查看统计');
        }
    });
}

let hexToRgb = (h, a) => {
    if (h.substr(0, 1) == "#")
        h = h.substring(1);
    let len = h.length;
    if (len != 6 && len != 3 || /[^0-9a-f]/i.test(h))
        return 'rgba(0, 0, 0, 0)';
    h = h.toLowerCase();
    let b = new Array();
    for (x = 0; x < 3; x++) {
        b[0] = len == 6 ? h.substr(x * 2, 2) : h.substr(x * 1, 1) + h.substr(x * 1, 1);
        b[3] = "0123456789abcdef";
        b[1] = b[0].substr(0, 1);
        b[2] = b[0].substr(1, 1);
        b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2])
    }
    return 'rgba(' + b[20] + ',' + b[21] + ',' + b[22] + ',' + (a === undefined ? '1' : a) + ')';
}
const macarons = [
    '#f5dce7',    // PINKO
    '#f1ccb8',    // マカロンオレンジ
    '#f1f1b8',    // マカロンイエロー
    '#b8f1cc',    // マカロングリーン
    '#b8f1ed',    // マカロンオーシャンブルー
    '#b8d4ea',    // BLUE
    '#e7dac9',    // マカロン メープル?ヴァニーユ
    '#d9b8f1',    // マカロンパープル
    '#9370db',
    '#cccccc'
];
// 定位锚点且画周期
let toGraphicsIndex = (i, period) => {
	// 先确认当前 dataZoom 的位置，根据情况进行定位
	let option = myChart.getOption(), zoom = option.dataZoom[0],
	    startValue = zoom.startValue, endValue = zoom.endValue,
	    categories = option.xAxis[0].data, totalLength = categories.length;
	if (i < startValue || i > endValue) {
		// 此时需要进行缩放
	    let halfRange = Number(((endValue - startValue) / 2).toFixed(0));
		startValue = Math.max(0, i - halfRange);
		endValue = Math.min(totalLength - 1, i + halfRange);
	    myChart.dispatchAction({
	        type: 'dataZoom',
	        startValue: startValue,
	        endValue:   endValue
	    });
	}
	myChart.dispatchAction({
		type: 'showTip',
        seriesIndex: 0,
	    dataIndex: i
	});
	let data = [];
	if (allAnchorIndexes[i+''] !== undefined) {
    	// 处理周期
    	let s = i, a = allAnchorIndexes[i+''], e = a?a:totalLength; i = 0;
    	
    	while (true) {
    		let s1 = s + Math.ceil(i * period),
    		    s2 = s + Math.ceil(++i * period),
    		    s3 = s + Math.ceil((i + 1) * period),
    		    sd = Math.min(s2, e - 1),
    		    name = i < 10 || i % 5 == 0 || s3 > e ? i : '';
    		    name += (s2 >= e && s3 > e) ? ('(' + (sd - s2 + 1) + ')'):'';
    		
            if (s1 > sd) break;
    		data.push([
    			{
    				name: name,
    				xAxis: categories[s1],
    				itemStyle: {
    					color: hexToRgb(macarons[ (i - 1) % macarons.length], .6)
    				}
    			}, {
    				xAxis: categories[sd]
    			}
    		]);
    		if (s2 >= e) break;
    	}
	}
	
	myChart.setOption({series: [ {
	data: window._values,
	markArea: {data: data}}]});
}
</script>
</body>
</html>
