<template>
	<view>
		<!-- 顶部导航 -->
		<fa-navbar :title="vuex_table_title || 'K线训练'"></fa-navbar>
		
		<view >
			<HQChartControl ref="HQChartCtrl" DefaultChart="{Type:'KLine'}" DefaultSymbol="000001.sz"> </HQChartControl>
		</view>

		<!--   控制图1 !-->
		<view class="button-sp-area">
			<button class="mini-btn" type="default" size="mini" @click="ChangeMinutePeriod(1)">分时</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeMinutePeriod(5)">5日</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeKLinePeriod(0)">日K</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeKLinePeriod(1)">周K</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeKLinePeriod(4)">1K</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeKLinePeriod(5)">5K</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeKLinePeriod(6)">15K</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeKLinePeriod(7)">30K</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeKLinePeriod(8)">60K</button>
			<!-- <button class="mini-btn" type="default" size="mini" @click="ChangeSymbol('600999.sh')">招商证券</button>
			<button class="mini-btn" type="default" size="mini" @click="ChangeSymbol('000002.sz')">万科A</button> -->

			<button class="mini-btn" type="default" size="mini" @click="MoveNextKLine()">Next</button>
			<button class="mini-btn" type="default" size="mini" @click="Buy()">Buy</button>
			<button class="mini-btn" type="default" size="mini" @click="Sell()">Sell</button>
		</view>
		<view>
			{{tradeinfo}}
		</view>
		<!-- 底部导航 -->
		<fa-tabbar></fa-tabbar>
	</view>
</template>

<script>
	import HQChartControl from '@/uni_modules/jones-hqchart2/js_sdk/HQChartControl.vue'
	import JSHQData from "./hq.data.js"

	// #ifdef H5
	import HQChart from '@/uni_modules/jones-hqchart2/js_sdk/umychart.uniapp.h5.js'

	//HQChart.MARKET_SUFFIX_NAME.GetMarketStatus = (symbol) => { return 2; }

	HQChart.JSChart.GetMinuteTimeStringData().CreateSHSZData = () => {
		return JSHQData.HQData.CreateSHSZData(HQChart.JSChart.GetMinuteTimeStringData());
	} //替换交易时间段
	HQChart.JSChart.GetMinuteCoordinateData().GetSHSZData = (upperSymbol, width) => {
		return JSHQData.HQData.GetSHSZData(upperSymbol, width);
	} //替换X轴刻度信息

	// #endif

	// #ifndef H5
	import {
		JSCommon
	} from '@/uni_modules/jones-hqchart2/js_sdk/umychart.wechat.3.0.js'
	import {
		JSConsole
	} from '@/uni_modules/jones-hqchart2/js_sdk/umychart.console.wechat.js'
	import {
		JSCommonCoordinateData
	} from '@/uni_modules/jones-hqchart2/js_sdk/umychart.coordinatedata.wechat.js'

	JSCommonCoordinateData.MinuteTimeStringData.CreateSHSZData = () => {
		return JSHQData.HQData.CreateSHSZData(JSCommonCoordinateData.MinuteTimeStringData);
	}
	JSCommonCoordinateData.MinuteCoordinateData.GetSHSZData = (upperSymbol, width) => {
		return JSHQData.HQData.GetSHSZData(upperSymbol, width);
	}

	//JSCommon.MARKET_SUFFIX_NAME.GetMarketStatus = (symbol) => { return 2; }
	//禁用日志
	JSConsole.Complier.Log = () => {};
	JSConsole.Chart.Log = () => {};
	// #endif

	export default {
		components: {
			HQChartControl
		},

		data() {
			let data = {
				Symbol: '600000.sh',
				ChartWidth: 350,
				ChartHeight: 350,
				LatestKData: null,
				LatestTrade: null,
				AryTrade: [],
				OrderID: 10,
				tradeinfo: ''
			};

			return data;
		},

		onShow() {
			uni.getSystemInfo({
				success: (res) => {
					var width = res.windowWidth;
					var height = res.windowHeight;
					this.ChartWidth = width;
					this.ChartHeight = height - 170;
					this.$nextTick(() => {
						this.CreateHQChart();
					})
				}
			});
		},

		onHide() {
			this.ClearHQChart();
		},

		onUnload() {
			this.ClearHQChart();
		},

		methods: {
			CreateHQChart() {
				var chartHeight = this.ChartHeight;
				let hqchartCtrl = this.$refs.HQChartCtrl;
				hqchartCtrl.NetworkFilter = this.NetworkFilter; //绑定数据回调
				hqchartCtrl.KLine.Option.Type = 'K线训练';
				hqchartCtrl.KLine.IsShowMaxMinPrice=true;
				hqchartCtrl.KLine.Option.IsApiPeriod = true; //周期使用api数据
				hqchartCtrl.KLine.Option.IsClickShowCorssCursor = true;
				hqchartCtrl.KLine.Option.IsAutoUpdate = true; //自动更新
				hqchartCtrl.KLine.Option.AutoUpdateFrequency = 10000; //更新频率 ms
				hqchartCtrl.KLine.Option.KLineTitle = {
					IsShowName: false,
					IsShowSettingInfo: false,
					IsShowDateTime: true
				}; //标题设置
				
				hqchartCtrl.KLineTrain = {
				 Font:'bold 14px arial',
				  LastDataIcon: {Color:'rgb(0,0,205)',Text:'⬇'},
				  BuyIcon: {Color:'rgb(0,205,102 )',Text:'B'},
				  SellIcon: {Color:'rgb(255,127,36 )',Text:'S'},
				}


				hqchartCtrl.KLine.Option.Train = {
						DataCount: 200, //训练数据
						StartDate: {
							Date: 20180201
						}
						
					},
					hqchartCtrl.KLine.Option.ExtendChart = [{
						Name: 'KLineTooltip'
					}, {
						Name: '背景图',
						FrameID: 0
					}];

				hqchartCtrl.Minute.Option.IsAutoUpdate = true;
				hqchartCtrl.Minute.Option.AutoUpdateFrequency = 10000; //更新频率 ms

				hqchartCtrl.SetSize(this.ChartWidth, chartHeight);
				hqchartCtrl.OnSize();


				hqchartCtrl.CreateHQChart();
				hqchartCtrl.KLine.AddEventCallback({
					event: 4,
					callback: (event, data, obj) => {
						this.OnKLineMove(event, data, obj);
					}
				});
				
				
				
				

			},
			MoveNextKLine() {
				
				let hqchartCtrl = this.$refs.HQChartCtrl;			
				hqchartCtrl.JSChartContainer.MoveNextKLineData();
			},
			Run() {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				hqchartCtrl.JSChartContainer.Run();
			},
			Stop() {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				hqchartCtrl.JSChartContainer.Stop();
			},
			OnKLineMove(event, data, obj) {
				console.log("[KLineChart::OnKLineMove] data", data);

				this.LatestKData = data.LastShowData;

				var dateTime = `日期:${this.LatestKData.Date}`;
				if (this.LatestKData.Time) dateTime = `日期:${this.LatestKData.Date} 时间:${this.LatestKData.Time}`;

				//更新界面显示信息
				var message =
					`状态:${data.Description} ${dateTime} 最新价格: ${this.LatestKData.Close.toFixed(2)} 剩余数据:${data.TrainDataCount}`;

				//$("#traininfo")[0].innerText = message;
				this.tradeinfo = message;

				if (data.TrainDataCount <= 0) this.LatestKData = null;
			},
			Sell() {
				if (!this.LatestKData) return;

				++this.OrderID;
				//以最新价格卖出
				var data = {
					Price: this.LatestKData.Close,
					Vol: 10,
					Op: 1,
					ID: this.OrderID
				}; //{ Price:价格, Vol:数量, Op: 买/卖 0=buy 1=sell, ID:单号 }
				this.LatestTrade = data;
				var tradeItem = this.AryTrade[this.AryTrade.length - 1];
				tradeItem.Sell = {
					Price: data.Price,
					ID: data.ID,
					Date: this.LatestKData.Date,
					Time: this.LatestKData.Time
				};
				this.CalulateScore();



				let hqchartCtrl = this.$refs.HQChartCtrl;
				let chart=hqchartCtrl.GetJSChart();

				chart.JSChartContainer.BuyOrSell(data, false);
				chart.JSChartContainer.MoveNextKLineData();
			},
			MoveNextKLine() {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				let chart=hqchartCtrl.GetJSChart();
				
				chart.JSChartContainer.MoveNextKLineData();
			},
			Buy() {
				if (!this.LatestKData) return;

				++this.OrderID;
				//以最新价格买入
				var data = {
					Price: this.LatestKData.Close,
					Vol: 10,
					Op: 0,
					ID: this.OrderID
				}; //{ Price:价格, Vol:数量, Op: 买/卖 0=buy 1=sell, ID:单号 }
				this.LatestTrade = data;

				var tradeItem = {
					Buy: {
						Price: data.Price,
						ID: data.ID,
						Date: this.LatestKData.Date,
						Time: this.LatestKData.Time
					}
				};
				this.AryTrade.push(tradeItem);

				let hqchartCtrl = this.$refs.HQChartCtrl;
				let chart=hqchartCtrl.GetJSChart();

				chart.JSChartContainer.BuyOrSell(data, false);
				chart.JSChartContainer.MoveNextKLineData();

				this.CalulateScore();
			},
			CalulateScore() {
				var count = 0,
					success = 0;
				var aryBGData = []; //背景颜色
				for (var i in this.AryTrade) {
					var item = this.AryTrade[i];
					if (!item.Buy || !item.Sell) continue;

					var bgItem = {
						Start: {
							Date: item.Buy.Date,
							Time: item.Buy.Time
						},
						End: {
							Date: item.Sell.Date,
							Time: item.Sell.Time
						}
					};
					if (item.Buy.Price < item.Sell.Price) {
						++success;
						bgItem.Color = 'rgba(250,128,114,0.5)';
					} else {
						bgItem.Color = 'rgba(152,251,152,0.5)';
					}

					aryBGData.push(bgItem);
					++count;
				}

				var result = 0;
				if (count > 0) result = success / count;
				var message = `成绩:交易次数${count} 成功次数${success} 胜率:${result.toFixed(2)}`;
				//$("#traininfo2")[0].innerText = message;
				this.tradeinfo = message;

				var bgPaint = this.GetBGChartPaint();
				if (bgPaint) bgPaint.Data = aryBGData;
			},
			GetBGChartPaint() {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				let chart=hqchartCtrl.GetJSChart();
				for (var i in chart.JSChartContainer.ExtendChartPaint) {
					var item = chart.JSChartContainer.ExtendChartPaint[i];
					if (item.ClassName == 'BackgroundPaint') return item;
				}

				return null;
			},
			RestartTrain() {
				this.AryTrade = [];
				this.LatestKData = null;
				this.LatestTrade = null;

				// $("#traininfo2")[0].innerText = '成绩:';
				// $("#traininfo")[0].innerText = '加载中......';
				// $("#buy").show();
				// $("#sell").hide();

				var bgPaint = this.GetBGChartPaint();
				if (bgPaint) bgPaint.Data = null;

				var option = {
					Symbol: "000001.sz",
					Train: {
						DataCount: 30,
						DateTime: {
							Date: 20190301
						}
					},
					Period: 0, //周期
					Right: 1, //复权
				}
				let hqchartCtrl = this.$refs.HQChartCtrl;
				hqchartCtrl.JSChartContainer.RestartTrain(option);
			},


			ClearHQChart() {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				if (hqchartCtrl) hqchartCtrl.ClearChart();
			},

			ChangeMinutePeriod(days) {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				hqchartCtrl.ChangeMinutePeriod(days);
			},

			ChangeKLinePeriod(period) {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				hqchartCtrl.ChangeKLinePeriod(period);
			},

			ChangeSymbol(symbol) {
				let hqchartCtrl = this.$refs.HQChartCtrl;
				hqchartCtrl.ChangeSymbol(symbol);
			},

			NetworkFilter(data, callback) {
				console.log(`[App:NetworkFilter] Name=${data.Name} Explain=${data.Explain}`);
				JSHQData.HQData.NetworkFilter(data, callback);
			},
		}
	}
</script>

<style lang="scss">
page {
	background-color: #f4f6f8;
}
</style>
