<template>
	<view>
		<view style="color: #000;">
			<tn-nav-bar @back="handleBack" backgroundColor="#F5FFFD" :bottomShadow="false">应用</tn-nav-bar>
			<view :style="{ height: tobheight + 'px' }"></view>
		</view>
		<div class="addFix" v-if="showInitLead">
			<div class="leadBg">
				<div class="leadBox1" v-if="showLead1" :style="{'background-image': `url(${leadBaseUrl}yy_lead2.png)`}">
					<div class="nextBtn" @click="nextLead">
					</div>
				</div>
				<div class="leadBox2" v-if="showLead2">
					<div class="nextBtn" @click="finishLead">
					</div>
				</div>
			</div>
		</div>

		<wike-skeleton :count="5" v-if="!info.title"></wike-skeleton>
		<!-- 提问模版新布局 -->
		<view class="quesTemBox">
			<view class="mtitle">
				{{ info.title }}
			</view>

			<view class="msubTitle">
				{{ info.sub_title }}
			</view>


			<view class="inputBox">
				<u--textarea v-model="valuechat" @focus="focustextarea" border="none" maxlength="-1" height="120"
					:placeholder="placeholder"></u--textarea>
				<image v-if="valuechat" @click="getempty" class="clearImg" src="/static/clear.png" mode=""></image>
				<!-- <image @click="valuechat=''" class="clearImg" src="/static/clear.png" mode=""></image> -->
			</view>


			<view class="msubmit" hover-class="hoversubmit" @click="init(valuechat)">运行</view>
		</view>





		<view class="directask">
			<view class="answer-container" v-if="answer&&currentmodel=='文心一言'">
				<view class="answer u-flex align-center flex-wrap">
					<text v-if="answer == '正在思考中...'||answer == '请等我几秒钟,正在输入回答...'">{{answer}}</text>
					<u-parse v-else :content="answer" scrollTable selectable :tag-style="parse_style"
						style="width: 100%;"></u-parse>


					<text v-if="answer == '正在思考中...'">{{ second }}s</text>
					<!-- <text class="flash" v-if="show_flash">│</text> -->
					<view
						:style="{marginLeft: answer == '正在思考中...'||answer == '请等我几秒钟,正在输入回答...'?20+'rpx':0+'rpx',marginTop: answer != '正在思考中...'||answer != '请等我几秒钟,正在输入回答...'?10+'rpx':0+'rpx'}"
						v-if="show_flash">
						<view style="margin-top: -5rpx;">
							<u-loading-icon size="17" mode="circle" color="#00ca88" :duration="300"></u-loading-icon>
						</view>
					</view>
				</view>
				<button hover-class="hoversubmit" class="duplicate u-flex justify-center" :disabled="!done"
					@click="copyText(backups)">一键复制</button>
			</view>

			<!-- <view class="answer-container" v-if="answer"> -->
			<view class="answer-container" v-if="answer&&(currentmodel=='研究生'||currentmodel=='大学生')">
				<view class="answer u-flex align-center flex-wrap">
					<text v-if="answer == '正在思考中...'||answer == '请等我几秒钟,正在输入回答...'">{{answer}}</text>
					<u-parse v-else :content="answer" scrollTable selectable :tag-style="parse_style"
						style="width: 100%;"></u-parse>
					<!-- <text>{{ answer }}</text> -->
					<text v-if="answer == '正在思考中...'">{{ second }}s</text>
					<!-- <text class="flash" v-if="show_flash">│</text> -->
					<view
						:style="{marginLeft: answer == '正在思考中...'||answer == '请等我几秒钟,正在输入回答...'?20+'rpx':0+'rpx',marginTop: answer != '正在思考中...'||answer != '请等我几秒钟,正在输入回答...'?10+'rpx':0+'rpx'}"
						v-if="show_flash">
						<view style="margin-top: -5rpx;">
							<u-loading-icon size="17" mode="circle" color="#00ca88" :duration="300"></u-loading-icon>
						</view>

					</view>
				</view>
				<button hover-class="hoversubmit" class="duplicate u-flex justify-center" :disabled="!done"
					@click="copyText(backups)">一键复制</button>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="wxad" v-if="appInfo.wxad_template_detail && appInfo.wxad_template_detail >= 1">
				<view style="100%">
					<wike-flow-main :flowtype="appInfo.wxad_template_detail" :banner_id="appInfo.banner_id"
						:video_banner_id="appInfo.video_banner_id" :native_id="appInfo.native_id"></wike-flow-main>
				</view>
			</view>

			<!-- #endif -->
			<view style="margin-top: 20rpx;"><wike-ad></wike-ad></view>
		</view>
		<u-action-sheet @select="selectClick" :round="10" :actions="sheetlist" :title="titlesheet" :show="showsheet"
			safeAreaInsetBottom @close="showsheet = false" cancelText="关闭"></u-action-sheet>
		<wike-model v-if="signShow" :authorize="false" :title="signTitle" btnText="立即获取" @save="signSign"
			@close="signShow = false"></wike-model>

		<!-- 暂时注释 -->
		<wike-modal-qrcode :qrcode="gzhqrcode" :showconcern="showconcern"
			@concernclose="concernclose"></wike-modal-qrcode>


	</view>
</template>

<script>
	import BaseUrl from '@/common/config.js';
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import {
		API_STEROOT,
	} from '@/common/request/request';
	let interstitialAd = null,
		timer,
		time2,
		down,
		delay;
	const {
		marked
	} = require('marked');
	import hljs from "highlight.js";
	import "highlight.js/scss/atom-one-dark.scss";
	export default {
		data() {
			return {
				leadBaseUrl: BaseUrl.leadBaseUrl,
				showInitLead: false,
				showLead2: false,
				showLead1: true,

				placeholder: '请输入关键词或问题...',
				preQues: '',

				signShow: false,
				signTitle: '',
				info: {},
				tobheight: 45,
				platform: this.$platform.get(),
				backups: '',
				answer: '',
				valuechat: '',
				valuechat1: '',

				thevaluechat: '',
				down: 0,
				done: false,
				second: 10,
				showanswer: false,
				show_flash: false,
				selectornot: 0,
				haddressurl: '',
				haddresssk: '',
				eights: false,
				thecontent: '',
				//通道
				thoroughfare: 0,
				showdirect: true,

				//模型
				showsheet: false,
				titlesheet: '切换模型',
				//是否为gpt4模型
				showchat4: false,

				showchat3: false,
				showchat2: false,
				//模型数据
				// #ifdef MP-WEIXIN
				sheetlist: [

					// {
					// 	index: 0,
					// 	name: '研究生',
					// 	subname: "超级高效沟通·简单提问",
					// 	disabled: false
					// },

					{
						index: 1,
						name: '大学生',
						subname: "高效沟通·简单提问",
						color: '#207CF7',
						disabled: false
					},
				],
				// #endif
				// #ifdef H5
				sheetlist: [

					{
						index: 0,
						name: '研究生',
						subname: "超级高效沟通·简单提问",
						disabled: false
					},
					{
						index: 1,
						name: '大学生',
						subname: "高效沟通·简单提问",
						color: '#207CF7',
						disabled: false
					},
					{
						index: 2,
						name: '文心一言',
						subname: "便捷沟通·简单提问",
						// color: '#207CF7',
						disabled: false
					},
					{
						index: 3,
						name: '讯飞火星',
						subname: "极速沟通·便捷提问",
						// color: '#207CF7',
						disabled: false
					},
				],
				// #endif
				// 消耗
				plan: {},
				currentmodel: '',
				chatgpturl: '',
				templateid: '',
				showconcern: false,
				gzhqrcode: '',
				parse_style: {
					// 字符串的形式
					p: 'margin-bottom:0rpx;',
					// 一级标题
					h1: `
				                   margin:25px 0;
				                   font-size: 24px;
				                   text-align: center;
				                   font-weight: bold;
				                   color: #00ca88;
				                   padding:3px 10px 1px;
				                   border-bottom: 2px solid #00ca88;
				                   border-top-right-radius:3px;
				                   border-top-left-radius:3px;
				                   `,
					// 二级标题
					h2: `
				                   margin:40px 0 20px 0;	
				                   font-size: 20px;
				                   text-align:center;
				                   color:#00ca88;
				                   font-weight:bolder;
				                   padding-left:10px;
				                   border:1px solid #00ca88;
				                   `,
					// 三级标题
					h3: `
				                   margin:30px 0 10px 0;
				                   font-size: 18px;
				                   color: #00ca88;
				                   padding-left:10px;
				                   border-left:3px solid #00ca88;
				                   `,
					// 四级标题
					h4: `
				                   margin:20px 0 10px 0;
				                   font-size: 16px;
				                   color: #00ca88;
				                   padding-left:10px;
				                   border-left:3px solid #00ca88;
				                   `,
					// 五级标题
					h5: `
				                   margin:10px 0 10px 0;
				                   font-size: 14px;
				                   color: #00ca88;
				                   padding-left:10px;
				                   border-left:3px solid #00ca88;
				                   `,
					// 六级标题
					h6: `
				                   margin:10px 0 10px 0;
				                   font-size: 12px;
				                   color: #00ca88;
				                   padding-left:10px;
				                   border-left:3px solid #00ca88;
				                   `,
					ul: 'margin:24rpx;color: #555;',
					ol: 'margin:12rpx;color:#555;',
					li: `
				                   margin: 12rpx 0;
				                   color: #555;
				                   `,
					// 链接
					a: `
								   color: #00ca88;`,
					// 加粗
					strong: `
								   font-weight: border;
								   color: #00ca88;
								   `,
					// 斜体
					em: `
								   color: #00ca88;
								   letter-spacing:0.3em;
								   `,
					blockquote: 'padding: 15rpx;margin:0 0 12rpx 0;border-radius: 6rpx;color: #555;border-left: 4px solid #dddddd;',

					hr: `height:1px;padding:0;border:none;text-align:center;background-image:linear-gradient(to right,rgba(248,57,41,0),${'#9e9e9e'},rgba(248,57,41,0));`,
					table: 'border-spacing:0;overflow:auto;min-width:100%;margin:10px 0;border-collapse: collapse;',
					th: 'background-color: whitesmoke;border: 1px solid #2d2d2d;padding:10rpx;',
					td: 'border: 1px solid #2d2d2d;padding:10rpx;',
					pre: `
								   color: #c7254e;
								   padding: 20rpx;
								   border-radius: 5px;
								   white-space: pre;
								   overflow: auto;
								   margin:12rpx 0;
								   font-size:13px;
								   background: #2d2d2d;
								   `,
				},
			};
		},
		computed: {
			...mapGetters(['appInfo', 'userInfo', 'userData', 'isLogin', 'homeTemplate'])
		},
		onShow: function() {
			// if (!this.$ws.socketStatus()) {
			// 	this.$ws.init();
			// }
			if (this.isLogin) {
				this.getUserData();

			}

			if (!this.currentmodel) {

				this.getPlan();
			}
			this.systemwechat()
		},
		onLoad(o) {
			this.showInitLead = !uni.getStorageSync('showInitLead_yy2')
			console.log("uni.getStorageSync('showInitLead')", uni.getStorageSync('showInitLead_yy2'));

			if (this.platform == 'wxMiniProgram') {
				var menumtop = uni.getMenuButtonBoundingClientRect().top - uni.getSystemInfoSync().statusBarHeight;
				var paddingtop = uni.getSystemInfoSync().statusBarHeight + menumtop;
				this.tobheight = menumtop + paddingtop + uni.getMenuButtonBoundingClientRect().height;
			}
			// 通过首页进入
			if (o.currentmodel) {
				this.currentmodel = o.currentmodel

				console.log('this.currentmodel', this.currentmodel);
				if (o.currentmodel == '研究生') {
					this.showchat4 = true
					this.selectClick({
						color: "#207CF7",
						disabled: false,
						index: 0,
						name: "研究生",
						subname: "超级高效沟通·简单提问"
					})
				} else if (o.currentmodel == '文心一言') {
					this.showchat3 = true
					this.selectClick({
						color: "#207CF7",
						disabled: false,
						index: 2,
						name: "文心一言",
						subname: "便捷沟通·简单提问"
					})
				} else if (o.currentmodel == '讯飞火星') {
					this.showchat2 = true
					this.selectClick({
						color: "#207CF7",
						disabled: false,
						index: 3,
						name: "讯飞火星",
						subname: "极速沟通·便捷提问"
					})
				} else {
					this.selectClick({
						color: "#207CF7",
						disabled: false,
						index: 1,
						name: "大学生",
						subname: "高效沟通·简单提问"
					})
				}
			} else {
				// 直接点击应用菜单进入
				if (uni.getStorageSync('prestore')) {
					this.currentmodel = uni.getStorageSync('prestore')

					if (this.currentmodel == '研究生') {
						this.showchat4 = true
						this.selectClick({
							color: "#207CF7",
							disabled: false,
							index: 0,
							name: "研究生",
							subname: "超级高效沟通·简单提问"
						})
					} else if (this.currentmodel == '文心一言') {
						this.showchat3 = true
						this.selectClick({
							color: "#207CF7",
							disabled: false,
							index: 2,
							name: "文心一言",
							subname: "便捷沟通·简单提问"
						})
					} else if (this.currentmodel == '讯飞火星') {
						this.showchat2 = true
						this.selectClick({
							color: "#207CF7",
							disabled: false,
							index: 3,
							name: "讯飞火星",
							subname: "极速沟通·便捷提问"
						})
					} else {
						this.selectClick({
							color: "#207CF7",
							disabled: false,
							index: 1,
							name: "大学生",
							subname: "高效沟通·简单提问"
						})
					}
				}
			}



			this.templateid = this.$Route.query.id
			// console.log(this.templateid);
			this.getInfo();
			this.onmessage();
			// this.init()
			// #ifdef H5
			this.aigetAddress();
			// #endif
			this.initHighLight();

		},
		onReady() {
			let that = this;
			// #ifdef MP-WEIXIN
			clearTimeout(timer);
			// 在适合的场景显示插屏广告
			timer = setTimeout(function() {
				// 在页面onLoad回调事件中创建插屏广告实例
				if (wx.createInterstitialAd && that.appInfo.interstitial_status == 1) {
					interstitialAd = wx.createInterstitialAd({
						adUnitId: that.appInfo.interstitial_id
					});
					interstitialAd.onLoad(() => {});
					interstitialAd.onError(err => {});
					interstitialAd.onClose(() => {
						if (that.appInfo.interstitial_infinite_status && that.appInfo
							.interstitial_infinite_status == 1) {
							that.showInterstitial();
						} else {
							interstitialAd.show().catch(err => {
								console.error(err);
							});
						}
					});
					interstitialAd.show().catch(err => {
						// console.error(err);
					});
				}
			}, 4000);
			// #endif
		},
		onUnload() {
			if (this.$ws.socketStatus()) {
				this.$ws.completeClose();
			}

			clearInterval(time2);
		},
		onHide() {
			// console.log('onHide');
			if (this.$ws.socketStatus()) {
				this.$ws.completeClose();
			}
		},
		methods: {
			nextLead() {
				// this.showLead1 = false
				// this.showLead2 = true

				this.showInitLead = false
				this.showLead1 = false
				uni.setStorageSync('showInitLead_yy2', true)
			},
			finishLead() {
				this.showInitLead = false
				this.showLead2 = false
				uni.setStorageSync('showInitLead_yy2', true)
			},

			handleBack() {
				getApp().lastPage = 'templateDes'
			},

			focustextarea() {
				if (this.valuechat == this.preQues) {
					this.valuechat = ''
				}
			},

			...mapActions(['getUserInfo', 'showAuthModal', 'getUserData']),
			onmessage() {
				let that = this,
					message = '';
				uni.onSocketMessage(function(res) {
					// console.log(2);
					that.showanswer = true;
					let a = res.data;
					if (a.indexOf('wike_err:') != -1) {
						uni.showToast({
							title: '报错:' + a,
							icon: 'none'
						});
						that.answer = '报错:' + a;
						that.show_flash = false;
						return;
					}
					if (!that.$ws.socketStatus()) {
						uni.showToast({
							title: '连接错误，正在重新思考'
						});
						that.onSubmit(that.valuechat);
						return;
					}
					if (a.indexOf('[DONE]') != -1) {
						that.record(that.valuechat, message);
						message = '';
						that.done = true;
						that.show_flash = false;
						// that.$ws.completeClose()
						if (that.$ws.socketStatus()) {
							that.$ws.completeClose();
						}
					} else {
						var b = a.split('data:').filter(w => !!w.trim() && w.trim() !== '[DONE]');
						var c = '';
						b.map(w => JSON.parse(w))
							.map(w => (c = w.choices[0].delta.content))
							.join('');
						// console.log(c);

						if (c != undefined) {
							message += c;
						}
						if (that.thoroughfare == 1) {
							that.backups = message;
							that.answer = marked(message);
						}
						uni.hideLoading();
					}
				});
			},
			initHighLight() {
				hljs.configure({
					useBR: true,
					tabReplace: " ",
				});
				marked.setOptions({
					renderer: new marked.Renderer(),
					gfm: true,
					tables: true,
					breaks: false,
					pedantic: false,
					highlight: function(code, lang) {
						if (lang && hljs.getLanguage(lang)) {
							return hljs.highlight(lang, code, true).value;
						} else {
							return hljs.highlightAuto(code).value;
						}
					},
				});
			},
			systemwechat() {
				this.$http('conf.getGroupConf', {
					group: 'system.wechat'
				}).then(res => {
					if (res.code == 0) {
						this.gzhqrcode = res.data.qrcode_path
						const focuson = uni.getStorageSync('focuson');
						// console.log(focuson);
						if (!focuson) {
							if (this.gzhqrcode) {
								if (this.isLogin && this.appInfo.is_show_logged_qrcode == 1) {
									this.showconcern = true
								}
							}
						}
					}
				})
			},
			concernclose() {
				this.showconcern = false
			},
			//选择模型
			selectClick(index) {
				console.log('index', index);
				for (var a = 0; a < this.sheetlist.length; a++) {
					this.sheetlist[a].color = '#000'
				}
				// #ifdef H5
				this.sheetlist[index.index].color = '#207CF7'
				// #endif
				// #ifdef MP-WEIXIN
				this.sheetlist[index.index - 1].color = '#207CF7'
				// #endif
				if (index.index == 0) {
					this.showchat4 = true
					this.showchat3 = false
					this.showchat2 = false
					this.paintingmode = false
					uni.setStorageSync('prestore', '研究生')
				} else if (index.index == 1) {
					this.paintingmode = false
					this.showchat4 = false
					this.showchat3 = false
					this.showchat2 = false
					uni.setStorageSync('prestore', '大学生')
				} else if (index.index == 3) {
					this.paintingmode = false
					this.showchat4 = false
					this.showchat3 = false
					this.showchat2 = true
					uni.setStorageSync('prestore', '讯飞火星')
				} else {
					this.paintingmode = false
					this.showchat4 = false
					this.showchat3 = true
					this.showchat2 = false
					uni.setStorageSync('prestore', '文心一言')
				}
				// this.switcmode()

				// uni.showToast({
				// 	title:'已切换模型'
				// })
				// console.log(index)
				this.getcurrentmodel()
			},
			getroute() {
				if (!this.isLogin) {
					uni.setStorageSync('route', '/pages/template/detail?id=' + this.templateid);
				}
			},
			waitWss() {
				return new Promise((resolve, reject) => {
					uni.onSocketOpen(function(res) {
						// console.log('WebSocket连接已打开！');
						resolve(1);
					});
				});
			},
			waitClose() {
				return new Promise((resolve, reject) => {
					uni.onSocketClose(function(res) {
						// console.log('WebSocket 已关闭！');
						resolve(1);
					});
				});
			},
			record(question, answer) {
				let that = this,
					type = that.showchat4 ? 'gpt4' : 'gpt35';;
				this.$http('question.add', {
					question,
					answer,
					type
				}).then(res => {
					if (res.code == 0) {
						that.getUserData();
						// console.log(that.question_index);
					} else {
						that.valuechat = '该问题已被隐藏!';
						that.answer = res.msg;
						that.done = true;
						that.show_flash = false;
					}

				});
			},
			getPlan() {
				let that = this;
				this.$http('conf.getGroupConf', {
					group: 'system.plan'
				}).then(res => {
					if (res.code == 0) {
						this.plan = res.data

						let gpt = this.appInfo;
						// #ifdef MP-WEIXIN
						this.sheetlist[0].name = gpt.gpt35_alias ? gpt.gpt35_alias : '大学生'
						this.sheetlist[0].subname = gpt.gpt35_intro ? gpt.gpt35_intro : '高效沟通·简单提问'

						this.sheetlist[1].name = gpt.gpt3_alias ? gpt.gpt3_alias : '文心一言'
						this.sheetlist[1].subname = gpt.gpt3_intro ? gpt.gpt3_intro : '便捷沟通·简单提问'

						this.sheetlist[2].name = gpt.gpt2_alias ? gpt.gpt2_alias : '讯飞火星'
						this.sheetlist[2].subname = gpt.gpt2_intro ? gpt.gpt2_intro : '极速沟通·便捷提问'
						// #endif
						// #ifdef H5
						this.sheetlist[0].disabled = gpt.is_gpt4 == 1 ? false : true

						this.sheetlist[0].name = gpt.gpt4_alias ? gpt.gpt4_alias : '研究生'
						this.sheetlist[0].subname = gpt.gpt4_intro ? gpt.gpt4_intro : '高效沟通·简单提问'
						this.sheetlist[1].name = gpt.gpt35_alias ? gpt.gpt35_alias : '大学生'
						this.sheetlist[1].subname = gpt.gpt35_intro ? gpt.gpt35_intro : '高效沟通·简单提问'

						this.sheetlist[2].name = gpt.gpt3_alias ? gpt.gpt3_alias : '文心一言'
						this.sheetlist[2].subname = gpt.gpt3_intro ? gpt.gpt3_intro : '便捷沟通·简单提问'

						this.sheetlist[3].name = gpt.gpt2_alias ? gpt.gpt2_alias : '讯飞火星'
						this.sheetlist[3].subname = gpt.gpt2_intro ? gpt.gpt2_intro : '极速沟通·便捷提问'
						// #endif




						this.getcurrentmodel()
					}
				})

			},
			getcurrentmodel() {
				let gpt = this.appInfo;
				if (this.showchat4) {
					// this.currentmodel = gpt.gpt4_alias ? gpt.gpt4_alias : '研究生'
					this.currentmodel = '研究生'
				} else if (this.showchat3) {
					this.currentmodel = gpt.gpt3_alias ? gpt.gpt3_alias : '文心一言'
				} else if (this.showchat2) {
					this.currentmodel = gpt.gpt2_alias ? gpt.gpt2_alias : '讯飞火星'
				} else {
					// this.currentmodel = gpt.gpt35_alias ? gpt.gpt35_alias : '大学生'
					this.currentmodel = '大学生'
				}
			},
			aigetAddress() {
				var that = this;
				let uniacid = uni.getStorageSync("uniacid") || "5059";
				that.chatgpturl = API_STEROOT + 'api.ai/chatgpt?uniacid=' + uniacid;
				// if(that.appInfo.connect_lines && that.appInfo.connect_lines == 2){
				// that.$http('ai.getAddress').then(res => {
				// 	if (res.code == 0) {

				// 			that.haddressurl = res.data.url;
				// 			that.haddresssk = res.data.sk;
				// 			that.chatgpturl = API_STEROOT+'api.ai/chatgpt?uniacid='+uniacid;

				// 	}else{
				// 		uni.showToast({
				// 			title: '未正确配置key',
				// 			icon: 'none'
				// 		});
				// 		return;
				// 	}
				// });
				// }else{
				// 	that.chatgpturl = API_STEROOT+'api.ai/chatgpt?uniacid='+uniacid;
				// }



			},
			getInfo() {
				this.$http('template.info', {
					id: this.$Route.query.id
				}).then(res => {
					if (res.code == 0) {
						// uni.setNavigationBarTitle({
						// 	title: res.data.title
						// });
						this.info = res.data;

						this.preQues = res.data.examples
						this.valuechat = res.data.examples

						console.log('模版详情----', this.info, res);
						uni.setNavigationBarTitle({
							title: this.appInfo.site_name
						});
					}
				});
			},
			copyText(text) {
				uni.setClipboardData({
					data: text,
					success: function() {
						// console.log('success');
						uni.showToast({
							title: '复制成功'
						});
					}
				});
			},
			countdown() {
				var that = this;
				that.second--;
				if (that.second == 0) {
					// console.log('15秒定时结束');
					if (!that.showanswer) {
						if (!that.showchat4) {
							uni.showLoading({
								title: '加载中...'
							});
						}
						clearTimeout(down);
						if (that.showdirect) {
							setTimeout(() => {
								uni.hideLoading();
								that.second = 10;
								that.directGpt(that.valuechat);
							}, 1500);
						} else {
							uni.hideLoading();
							that.second = 10;
							if (that.answer == '正在思考中...') {
								that.answer = '请等我几秒钟,正在输入回答...';
							}
						}
						return;
					} else {
						that.second = 10;
						clearTimeout(down);
					}
					return;
				}
				down = setTimeout(() => {
					if (that.showanswer) {
						clearTimeout(down);
						that.second = 10;
						return;
					}
					that.countdown();
				}, 1000);
			},

			getempty() {
				var that = this;
				if (that.answer && !that.done) {
					uni.showToast({
						title: '正在输入回答,请等待输入完成',
						icon: 'none'
					});
					return;
				}
				that.valuechat = '';
				that.answer = '';

				// this.placeholder1 = '请输入关键词或问题...'
			},
			getcheckText() {
				var that = this;
				return new Promise((resolve, reject) => {
					that.$http('ai.checkText', {
						prompt: that.thecontent
					}).then(res => {
						if (res.code == 0) {
							resolve(1);
						} else {
							that.valuechat = '该问题已被隐藏!';
							that.answer = res.msg;
							that.done = true;
							that.show_flash = false;
						}
					})
				});
			},
			signSign() {
				uni.navigateTo({
					url: '/pages/user/member/member'
				});
				this.signShow = false
			},
			async init(e) {
				// if (this.answer) {
				// 	this.answer = ''
				// }

				let that = this;
				if (!that.isLogin) {
					uni.navigateTo({
						url: '/pages/user/signin'
					});
					uni.setStorageSync('route', '/pages/template/detail?id=' + this.templateid);
					return;
				}
				if (!e) {
					uni.showToast({
						title: '请输入关键词或问题',
						icon: 'none'
					});
					return;
				}
				this.thecontent = e;
				if (that.appInfo.time_member && that.appInfo.time_member == 1) {
					if (that.showchat4) {
						if (that.userData.vip_info && that.userData.is_validity > 0 && that.userData.vip_info
							.gpt4_used ==
							that.userData.vip_info.gpt4_times && that.userData.coin < that.plan.lock_gpt4) {
							var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
							// this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>您的提问<span>" + alias +
							// 	"</span>不足或会员套餐内剩余次数不足，无法发起提问</p>"
							this.signTitle =
								"<p style='font-weight: 550;font-size: 16px;'>提问需要<span style='color: #26b3a0;padding: 0 4px;'>" +
								that.plan.lock_gpt4 + "</span><span>" + alias +
								"</span></p><p style='padding-top: 10px;'>您的提问<span>" + alias +
								"</span>不足或会员套餐内剩余次数不足，无法发起提问</p>"
							this.signShow = true
							return;
						}
						if (that.userData.is_validity == 0 && that.userData.coin < that.plan.lock_gpt4) {
							var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
							this.signTitle =
								"<p style='font-weight: 550;font-size: 16px;'>提问需要<span style='color: #26b3a0;padding: 0 4px;'>" +
								that.plan.lock_gpt4 + "</span><span>" + alias +
								"</span></p><p style='padding-top: 10px;'>您的提问<span>" + alias +
								"</span>不足或会员套餐内剩余次数不足，无法发起提问</p>"
							this.signShow = true
							return;
						}
					} else {
						if (that.userData.is_validity > 0 && that.userData.vip_info.gpt35_used == that.userData
							.vip_info
							.gpt35_times && that.userData.coin <= 0) {
							var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
							// this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>您的提问<span>" + alias +
							// 	"</span>不足或会员套餐内剩余次数不足，无法发起提问</p>"
							this.signTitle =
								"<p style='font-weight: 550;font-size: 16px;'>提问需要<span style='color: #26b3a0;padding: 0 4px;'>" +
								1 + "</span><span>" + alias +
								"</span></p><p style='padding-top: 10px;'>您的提问<span>" + alias +
								"</span>不足或会员套餐内剩余次数不足，无法发起提问</p>"
							this.signShow = true
							return;
						}
						if (that.userData.is_validity == 0 && that.userData.coin <= 0) {
							var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
							this.signTitle =
								"<p style='font-weight: 550;font-size: 16px;'>提问需要<span style='color: #26b3a0;padding: 0 4px;'>" +
								1 + "</span><span>" + alias +
								"</span></p><p style='padding-top: 10px;'>您的提问<span>" + alias +
								"</span>不足或会员套餐内剩余次数不足，无法发起提问</p>"
							this.signShow = true
							return;
						}
					}
				} else {
					if (that.showchat4 && that.userData.coin < that.plan.lock_gpt4) {
						var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
						this.signTitle =
							"<p style='font-weight: 550;font-size: 16px;'>提问需要<span style='color: #26b3a0;padding: 0 4px;'>" +
							that.plan.lock_gpt4 + "</span><span>" + alias +
							"</span></p><p style='padding-top: 10px;'>您当前有<span style='color: #26b3a0;padding: 0 4px;'>" +
							that.userData.coin + "</span><span>" + alias + "</span>，无法发起提问，快去获取<span>" + alias +
							"</span>吧</p>"
						this.signShow = true
						return;
					}
					if (!that.showchat4 && that.userData.coin <= 0) {
						var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
						this.signTitle =
							"<p style='font-weight: 550;font-size: 16px;'>提问需要<span style='color: #26b3a0;padding: 0 4px;'>" +
							1 + "</span><span>" + alias +
							"</span></p><p style='padding-top: 10px;'>您当前有<span style='color: #26b3a0;padding: 0 4px;'>" +
							that.userData.coin + "</span><span>" + alias + "</span>，无法发起提问，快去获取<span>" + alias +
							"</span>吧</p>"
						this.signShow = true
						return;
					}
				}
				// if(that.showchat4){
				// 	if(that.userData.coin < that.plan.lock_gpt4){
				// 		var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
				// 		this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>提问需要<span style='color: #26b3a0;padding: 0 4px;'>"+that.plan.lock_gpt4+"</span><span>"+alias+"</span></p><p style='padding-top: 10px;'>您当前有<span style='color: #26b3a0;padding: 0 4px;'>"+that.userData.coin+"</span><span>"+alias+"</span>，此模型不支持会员套餐，无法发起提问，快去获取<span>"+alias+"</span>吧</p>"
				// 		this.signShow = true
				// 		return;
				// 	}
				// }
				// if (this.appInfo.time_member && this.appInfo.time_member == 1) {
				// 	if (that.userData.is_validity > 0 && that.userData.vip_info.gpt35_used == that.userData.vip_info.gpt35_times && that.userData.coin <= 0) {
				// 		var alias = that.appInfo.number_alias ? that.appInfo.number_alias : '点数';
				// 		this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>您的提问<span>"+alias+"</span>/会员套餐内剩余次数不足</p>"
				// 		this.signShow = true

				// 		return;
				// 	}
				// 	if (that.userData.is_validity == 0) {
				// 		if (that.userData.coin <= 0) {
				// 			var alias = that.appInfo.number_alias?that.appInfo.number_alias:'点数';
				// 			this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>您的提问<span>"+alias+"</span>/会员套餐不足</p>"
				// 			this.signShow = true
				// 			return;
				// 		}
				// 	}
				// } else {
				// 	if (that.userData.coin <= 0) {
				// 		var alias = that.appInfo.number_alias?that.appInfo.number_alias:'点数';
				// 		this.signTitle = "<p style='font-weight: 550;font-size: 16px;'>您的提问<span>"+alias+"</span>不足</p>"
				// 		this.signShow = true
				// 		return;
				// 	}
				// }
				// if (!that.haddresssk && that.appInfo.connect_lines && that.appInfo.connect_lines == 2) {
				// 	uni.showToast({
				// 		title: '未正确配置key',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }

				if (that.answer && !that.done) {
					uni.showToast({
						title: '正在输入回答,请等待输入完成',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({})
				// #ifdef H5
				let check = this.appInfo.is_h5_filter && this.appInfo.is_h5_filter == 1 ? await this.getcheckText() :
					1;
				// #endif
				// #ifdef MP-WEIXIN
				let check = await this.getcheckText();
				// #endif
				if (check == 1) {
					uni.hideLoading();
					that.done = false;
					that.answer = '正在思考中...';
					that.show_flash = true;
					that.showanswer = false;
					that.countdown();
					// #ifdef MP-WEIXIN
					if (this.showchat4) {
						this.directGpt(this.thecontent);
						return;
					}
					// #endif

					// #ifdef MP-WEIXIN
					if (!that.$ws.socketStatus()) {
						that.$ws.init();
						that.showdirect = true;
						let re = await that.waitWss();
						if (re == 1) {
							that.onSubmit(e);
						}
					} else {

						that.$ws.completeClose();

						that.showdirect = false;
						that.directGpt(this.thecontent);
					}
					// #endif
					// #ifdef H5
					that.showdirect = true;
					that.fetchmodel(that.thecontent);
					// #endif
				}

			},
			async onSubmit(e) {
				let that = this;
				that.thoroughfare = 1
				var ty = {
					prompt: e,
					guide: that.info.guide,
					key: that.haddresssk ? that.haddresssk : '',
					lines: that.appInfo.connect_lines ? this.appInfo.connect_lines : 1,
					temperature: that.appInfo.temperature ? this.appInfo.temperature : 0,
					presence_penalty: that.appInfo.presence_penalty ? this.appInfo.presence_penalty : 0,
					frequency_penalty: that.appInfo.frequency_penalty ? this.appInfo.frequency_penalty : 0,
				};
				var json = JSON.stringify(ty);
				that.$ws.send(json);
			},
			directGpt(e) {
				let that = this;
				// console.log('s');
				if (that.showdirect) {
					that.answer = '请等我几秒钟,正在输入回答...';
				}
				that.showanswer = that.showdirect;
				that.thoroughfare = 3
				// that.$http(that.showchat4 ? 'ai.chat4' : 'ai.chat', {
				that.$http('ai.baidu', {
					type: 'baidu',
					prompt: e,
					guide: that.info.guide,
				}).then(res => {
					if (res.code == 0) {
						if (that.thoroughfare == 3) {
							that.backups = res.data.trim();
							that.answer = marked(res.data.trim());
							that.show_flash = false;
							that.done = true;
							that.second = 10;
							that.getUserData();
						} else if (res.code == 3) {
							that.answer = res.msg;
							that.show_flash = false;
							that.second = 10;
							that.done = true;
							// that.showanswer = true
						} else {
							that.answer = res.msg;
							that.valuechat = '该问题已被隐藏!';
							that.show_flash = false;
							that.second = 10;
							that.done = true;
							// that.showanswer = true
						}
					} else {
						that.answer = res.msg;
						that.show_flash = false;
						that.second = 10;
						that.done = true;
					}

				});
			},
			fetchmodel(e) {
				var that = this;
				let i = 1,
					message = '';
				let param = {
					// max_tokens: 3000,
					// model: 'gpt-3.5-turbo-0301',
					// stream: true,
					type: that.showchat4 ? 'gpt4' : that.showchat3 ? 'baidu' : that.showchat2 ? 'baidu' : 'gpt35',
					prompt: e,
					guide: that.info.guide
					// messages: [{
					// 		role: 'system',
					// 		content: that.info.guide
					// 	},
					// 	{
					// 		role: 'user',
					// 		content: e
					// 	}
					// ]
				};
				let headers = {};
				headers = {
					'token': uni.getStorageSync("token") || "",
					'platform': this.platform,
					'Content-Type': 'application/json',
				}
				// if(that.appInfo.connect_lines == 2){
				// headers = {
				// 	'Content-Type': 'application/json',
				// 	Authorization: 'Bearer' + ' ' + that.haddresssk
				// }
				// }
				that.thoroughfare = 2
				// console.log(that.chatgpturl);
				fetch(that.chatgpturl, {
						method: 'POST',
						body: JSON.stringify(param),
						headers: headers
					})
					.then(x => {
						if (x.status === 404) {
							this.showdirect = false;
							that.directGpt(e)
							return;
						}
						if (x.status === 200) return x.body;
						throw x;

						// if (x.status === 200 && param.type == 'baidu') {
						// 	this.showdirect = false;
						// 	that.directGpt(e)
						// 	return;
						// } else if (x.status === 200 && param.type !== 'baidu') {
						// 	return x.body
						// }
						// throw x;
					})
					.then(x => {
						const k = x.getReader();
						return new ReadableStream({
							start(V) {
								function F() {
									k.read().then(({
										done: E,
										value: U
									}) => {
										that.showanswer = true;
										if (E) {
											that.done = true;
											that.show_flash = false;
											// that.record(that.valuechat, message);
											return;
										}
										V.enqueue(U);
										const L = new TextDecoder().decode(U);
										const N = L;
										if (N != undefined) {
											message += N;
										}

										if (that.thoroughfare == 2) {
											if (N == '内容包含敏感信息，不予展示。') {
												// console.log('5');
												that.valuechat = '该问题已被隐藏!';
												that.answer = '内容包含敏感信息，不予展示。';
												that.done = true;
												that.show_flash = false;
												return;
											}
											that.backups = message;
											that.answer = marked(message);
										}
										// try {
										// 	const G = L.match(/data:\s/g),
										// 		j = L.split('data:').filter(w => !!w.trim() && w
										// 		.trim() !== '[DONE]');
										// 	var N = null;
										// 	N = j
										// 		.map(w => JSON.parse(w))
										// 		.map(w => (N = w.choices[0].delta.content))
										// 		.join('');
										// 	if (N != undefined) {
										// 		message += N;
										// 	}
										// 	if (that.thoroughfare == 2) {
										// 		that.answer = message;
										// 	}
										// 	let C = j
										// 		.map(w => JSON.parse(w))
										// 		.map(w => (N = w.choices[0].finish_reason))
										// 		.join('');
										// 	if (C == 'stop') {
										// 		that.done = true;
										// 		that.show_flash = false;
										// 		that.record(that.valuechat, message);
										// 		return;
										// 	}
										// } catch (G) {

										// }
										F();
									});
								}
								F();
							}
						});
					})
					.then(x =>
						new Response(x, {
							headers: {
								'Content-Type': 'text/html'
							}
						}).text()
					);
			},
			showInterstitial() {
				time2 = setInterval(
					function() {
						interstitialAd.show().catch(err => {
							// console.error(err);
						});
					},
					this.appInfo.gap ? this.appInfo.gap * 1000 : 12000
				);
			}
		}
	};
</script>

<style lang="scss">
	@import '@/pages/template/detail.scss';

	.directask {
		padding: 30rpx;
		border-top: 1px solid #ededed;

		.helpme {
			color: #9e9e9e;
			font-size: 26rpx;

			.title {
				font-size: 35rpx;
				font-weight: bold;
				margin-bottom: 18rpx;
				color: #000;
			}
		}

		.expand {
			// padding: 20rpx;
			margin: 30rpx 0;
			// padding-bottom: env(safe-area-inset-bottom);

			.surplus {
				color: #fff;
				font-size: 26rpx;
				background: #03a9f4;
				border-radius: 50rpx;
				padding: 8rpx 12rpx;
				margin-right: 20rpx;
				margin-bottom: 15rpx;

				.item {
					margin-left: 10rpx;
				}

				// display: inline-block;
			}
		}

		.textarea {
			// box-shadow: 0px 0px 10px 5px #9e9e9e36;
			margin-top: 30rpx;
			margin-bottom: 30rpx;
			border-radius: 20rpx;

			// padding: 20rpx 30rpx 30rpx 12rpx;
			.u-textarea {
				border-radius: 20rpx;
				padding: 24rpx;
			}

			.operate {
				justify-content: flex-end;
				margin-top: 30rpx;

				.surpluss {
					height: 66rpx;
					line-height: 66rpx;
					font-size: 28rpx;
					padding: 0 42rpx;
					border-radius: 10rpx;
					// border: 1px solid #26B3A0;
					background: linear-gradient(to right, #FFCA28, #FFA726);
					color: #fff;
				}

				.empty {
					margin-right: 30rpx;
					border: 1px solid #9e9e9e;
					color: #9e9e9e;
					padding: 12rpx 42rpx;
					border-radius: 10rpx;
				}

				.submit {
					height: 66rpx;
					line-height: 66rpx;
					font-size: 28rpx;
					padding: 0 42rpx;
					border-radius: 10rpx;
					// border: 1px solid #26B3A0;
					background: linear-gradient(to right, $tc, $tc2);
					color: #fff;
				}

				.hoversubmit {
					background: #f7f7f7;
					color: #acacb3;
				}
			}
		}

		.answer {
			border-radius: 18rpx;
			padding: 26rpx;
			border-width: 0.5px !important;
			border-color: #dadbde !important;
			border-style: solid;
		}

		.duplicate {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 10rpx;
			font-weight: bold;
			color: #fff;
			background: linear-gradient(to right, $tc, $tc2);
			margin-top: 30rpx;
			font-size: 30rpx;
		}
	}

	.flash {
		margin-left: 2px;
		animation: flash 0.8s linear infinite;
	}

	// 实现光标闪烁
	@keyframes flash {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	.wxad {
		border-radius: 20rpx;
		overflow: hidden;
		margin-bottom: 30rpx;
		// margin: 30rpx;
	}
</style>