<template>
	<view>
		<!-- 顶部导航 -->
		<fa-navbar :title="pagetitle || '编程工具'"></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>
		</view> -->
		
		
		<view class="ptip" v-if="showtip">点此按钮重新打开编程框</view>
		<!-- 底部导航 -->
		
		<u-popup v-model="showtool" mode="bottom" height="300px" :mask="false" z-index="996">	
		<view style="background-color: rgb(55, 68, 134); height: 35px;padding: 5px;">
			<u-icon name="edit-pen" color="#ffffff" size="48" style="float: left;margin-right: 5px;" @click="editcode()"></u-icon>
			<u-tag :text="scripttype?'主图':'副图'" shape="circle" style="float: left;margin-right: 5px;" :mode="scripttype?'light':'dark'" @click="changsctype()"/>	
			
			<u-icon name="checkbox-mark" color="#ffffff" size="48" style="float: right;" @click="checkcode()"></u-icon>
			<u-tag text="教程" shape="circle" style="float: right;margin-right: 5px;" v-if="studyid>0" @click="openstudy()"/>
			<u-action-sheet :list="downoption" @click="downclick" v-model="showdown"></u-action-sheet>
					
			<u-tag  type="success" text="下载源码" shape="circle" @click="showdown=!showdown" style="float: right;margin-right: 5px;"/>			
		</view>
		<scroll-view scroll-y="true" :style="viewstyle">
					<u-input v-model="mycode" type="textarea" :maxlength="1024" :border="false" v-if="editmode" height="100%" @input="vinInput"/>
					<mp-html :content="myhtml" ref="article" width="100%" height="90%" :editable="false" v-if="!editmode"/>
					
					
		</scroll-view>
		<view :style="'height: 50px;background-color: #2d2d2d; color: '+errColor+'; padding-left: 20px;'" v-if="!editmode">{{codeError}}</view>
		</u-popup>
		
		<fa-tabbar></fa-tabbar>
	</view>
</template>

<script>


	
	import mpHtml  from '@/node_modules/mp-html/dist/uni-app/components/mp-html/mp-html'
	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'
import {JSCommonComplier} from "@/uni_modules/jones-hqchart2/js_sdk/umychart.complier.wechat.js"
import { } from "@/uni_modules/jones-hqchart2/js_sdk/umychart.explainer.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
let that;		
export default 
{
	components: { HQChartControl,mpHtml },
	
	data()
	{   
		let data=
		{   
			Symbol:'600000.sh',
			ChartWidth:350,
			ChartHeight:500,
			showtool: true,
			showtip:true,			
			mycode:"JX1:=MA(CLOSE,13);\nJX2:=MA(CLOSE,49);\nDRAWICON(CROSS(JX1,JX2),L,1);\nDRAWICON(CROSS(JX2,JX1),H,2);",
			myhtml:"",
			scripts:'',
			editmode:false,
			scripttype:true,
			codeError:'',
			errColor:'#ff0000',
			viewstyle:"height: 200px; background-color: #2d2d2d;",
			pagetitle:'',
			codeloaded:false,
			productid:0,
			studyid:0,
			downtype:0,
			showdown:false,
			downoption:[{
						text: '复制到剪贴板',
						color: 'blue',
						fontSize: 28
						
					},
					{
						text: '下载到电脑安装',
						color: 'blue',
						fontSize: 28
					}
				]
			
			
		};
		
		return data;
	},
	watch:{
	    showtool:function(val){
			if(!val){
				
							 this.showtip=true;
							 let that=this;
							 setTimeout(function(){
								 
								 that.showtip=false;
							 },1000);
			}
	         
	    }
    },
	onLoad(option){
		uni.$on("centerButtonClick",(rel)=>{
		        this.switchtab(rel);
		});
		
		if(option.productid){
			console.log(option.productid);
			this.productid=option.productid;
		}
	},
	
	onShow()
	{   console.log('onshow');
		uni.getSystemInfo({
			success: (res) => {
				var width = res.windowWidth;
				var height = res.windowHeight;
				this.ChartWidth = width;
				this.ChartHeight = height - 100;
				this.$nextTick(() => {
					console.log('createchart');
					let that=this;
					setTimeout(function(					 
					){
						that.CreateHQChart();						
						that.codeloaded=false;
						that.checkcode();
					
					},1000);
					
				})
			}
		});
		
		
		
		
		
		
	},
	
	onHide()
	{
		this.ClearHQChart();
	},
	
	onUnload()
	{
		this.ClearHQChart();
	},
	
	
	methods:
	{   switchtab(index){
		 console.log('switch');
		 console.log(index);
		 let that=this;
		 if (index==2){
			 this.showtool=!this.showtool;
			 if (this.showtool){
				 this.checkcode();
				 
			 }
			 
			 return false;
			 
		 }
		return true;
	    },
		CreateHQChart()
		{
			var chartHeight=this.ChartHeight;
			let hqchartCtrl=this.$refs.HQChartCtrl;
			hqchartCtrl.NetworkFilter=this.NetworkFilter;		//绑定数据回调
			
			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.KLine.Option.Windows=[{
						Script: 'MA1:MA(CLOSE,N);MA2:MA(CLOSE,M);',
						Args: [{
							Name: 'N',
							Value: 13
						}, {
							Name: 'M',
							Value: 49
						}],
						Name: "我的主图",
						Modify: false,
						Change: false
					},
					{
					   Script: 'DIF:EMA(CLOSE,SHORT)-EMA(CLOSE,LONG);DEA:EMA(DIF,MID);MACD:(DIF-DEA)*2,COLORSTICK;',
								Args: [{
									Name: 'SHORT',
									Value: 12
								}, {
									Name: 'LONG',
									Value: 26
								},{
									Name: 'MID',
									Value: 9
								}],
								Name: "我的副图",
								Modify: false,
								Change: false
					},
					{
						Index: "RSI",
						Modify: false,
						Change: false
					}];
			

			hqchartCtrl.Minute.Option.IsAutoUpdate=true;
			hqchartCtrl.Minute.Option.AutoUpdateFrequency=10000;		//更新频率 ms
			
			hqchartCtrl.SetSize(this.ChartWidth,chartHeight);
			hqchartCtrl.OnSize();
			hqchartCtrl.CreateHQChart();
		},
		
		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);
		},
		changsctype(){
			this.scripttype=!this.scripttype;
		},
		vinInput(e) {
			
			let val = e;
			// if (/[^a-zA-Z0-9]/g.test(val)) { // 先过滤不需要的字符，只保留数字和字母
			// 	val = val.replace(/[^a-zA-Z0-9]/g, '');
			// }
			
			// if (!/^[A-Z\d]+$/.test(val)) {// 再进行转换，小写转为大写
			// 	val = val.toUpperCase();
			// }
			
			val = val.toUpperCase();
			this.mycode = val; //这里对应的是value绑定的变量
			return val; // 最后输出值，要保证输入框的值和value绑定的值一致
		},
		editcode(){
			this.viewstyle="height: 180px; background-color: #fff;" 
			this.editmode=true;
			
		},
		checkcode: async function(){
			
			let pid=this.productid;
			if(pid>0 && !this.codeloaded){
			   console.log(pid);
			   
			   let res = await this.$api.getArchivesDetail({ id: pid, diyname: '' });
			   console.log(res);
			   if (res.code>0){
				 this.pagetitle=  res.data.archivesInfo.title;
				 this.mycode=res.data.archivesInfo.tongdaxin;
				 this.studyid=res.data.archivesInfo.studyid;
				 //console.log(this.mycode);
				 this.codeloaded=true;
			   }
			   
			}
			
			this.editmode=false;
			this.viewstyle="height: 180px; background-color: #2d2d2d;"
			this.myhtml="<pre><code>"+this.mycode+"</code></pre>";
			let that=this;
			// setTimeout(function(){
			//   let ctx = that.$refs.article;
			//   if(ctx){
			//   ctx.setContent("<pre><code>"+that.mycode+"</code></pre>");	
			//   }
			// },500);
			

			
			
			var option=
			{
				Callback:(data)=>
				{
					console.log("[Explain] data ", data);
					for(var i in data)
					{
						var item=data[i];	//每一句翻译好的语句
					}
					that.errColor="#00FF00";
					that.codeError="语法正确";
					
					if(that.scripttype){//主图
					    //console.log(that.mycode);
						var indexdata={Name:"我的主图", Script:that.mycode, Args:[]};
						let hqchartCtrl=this.$refs.HQChartCtrl;
						
						hqchartCtrl.ChangeScriptIndex(0,indexdata);
					}else{
						var indexdata={Name:"我的副图", Script:that.mycode, Args:[]};
						let hqchartCtrl=this.$refs.HQChartCtrl;
						hqchartCtrl.ChangeScriptIndex(1,indexdata);
					}
					
				},
				ErrorCallback:(error, data)=>
				{   if(error.LineNumber){
					that.errColor="#FF0000";
					that.codeError=`语法错误: 行号:${error.LineNumber}, ${error.Description}`;
					}
				}
			};
			
			// #ifdef H5
			HQChart.JSComplier.Explain(that.mycode,option,option.ErrorCallback);
			// #endif
			
			// #ifndef H5
			JSCommonComplier.JSComplier.Explain(that.mycode,option,option.ErrorCallback);
			// #endif
			
			 
			
		},
		openstudy(){
			this.$Router.push({
				path: '/pages/article/detail',
				query: { id: this.studyid }
			});
		},
		copycode(){
			uni.setClipboardData({
					data:this.mycode,
			    success: function (res) {
			        uni.showToast({
			        		title: '已复制到剪贴板',
			        })
			    }
			});
		},
		downcode(){
			uni.showToast({
					title: '本功能暂未开放',
			})
		},
		getUserIndex: async function() {
			let res = await this.$api.getUserIndex();
			uni.stopPullDownRefresh();
			if (!res.code) {
				this.$u.toast(res.msg);
				return;
			}
			this.$u.vuex('vuex_user', res.data.userInfo || {});
		},
		downclick(index){
				if(index==0){
					this.copycode();
				}
				if(index==1){
					if (this.vuex_token) {
						this.getUserIndex();
					} else {
						this.$u.vuex('vuex_user', {});
					}
					if (!this.vuex_token) {
					  this.$u.toast('请先登录再操作！');	
					  return;
					}
					
					this.downcode();
				}
		
		}
	}
}
</script>

<style lang="scss">
	@import "~ng-codemirror/index.scss";


	.ptip {
		background-color: #0066CC;width: 80%;height: 40px;
		position: fixed;
		background-color: #3d7bb8;
		bottom:80px;
		border-radius: 15px;
		color:#ffffff;
		vertical-align:middle;
		text-align: center;
		z-index: 995;
		padding-top: 12px;
		
		left:10%;
	}
	
	.ptip:after {
			    content: "";
			    position: fixed;
				left: 49%;
				z-index: 994;
			    width: 10px;
			    height: 10px;
				bottom: 75px;
			    
			    background-color: #3d7bb8;
			    /* border-top: 1px solid #dcdcdc;
			    border-right: 1px solid #dcdcdc; */
			    transform: rotate(
					-45deg
				);
			}

</style>

