<template>
	<view>
		<div ref="terminalContainer" style="height: auto;width: 100%;"></div>
		<view class="imagesBox">
			<image :src="imgbas64" mode=""></image>
		</view>
	</view>
</template>

<script>
	import {
		Terminal
	} from 'xterm';
	import {
		FitAddon
	} from 'xterm-addon-fit';
	import 'xterm/css/xterm.css'
	import {
		fileTail
	} from '@/config/api.js'
	import {
		LOG_TAIL_STATUS
	} from './logConfig.js'
	export default {
		props: ['relId'],
		data() {
			return {
				imgbas64: '',
				terminal: null,
				fitAddon: null,
				token: '',
				socketTask: null,
				termConfig: {
					rightClickSelectsWord: true,
					disableStdin: true,
					cursorStyle: 'bar',
					cursorBlink: false,
					fastScrollModifier: 'shift',
					fontSize: 13,
					rendererType: 'canvas',
					fontFamily: 'courier-new, courier, monospace',
					lineHeight: 1.08,
					convertEol: true,
					theme: {
						foreground: '#FFFFFF',
						background: '#212529'
					}
				},
			};
		},
		mounted(options) {
			this.fileTailFn()
		},
		methods: {
			async fileTailFn() {
				let obj = {
					relId: this.relId,
					type: 10
				}
				const {
					data: res
				} = await fileTail(obj)
				this.token = res.token
				this.$nextTick(() => {
					this.initializeTerminal();
				})
			},
			initializeTerminal() {
				// 创建终端实例
				this.terminal = new Terminal({
					...this.termConfig
				});

				// 创建适应插件
				this.fitAddon = new FitAddon();
				this.terminal.loadAddon(this.fitAddon);
				// 将终端挂载到页面
				this.terminal.open(this.$refs.terminalContainer);

				// 设置终端大小适应窗口
				this.fitAddon.fit();

				// 你可以添加其他配置，例如主题等
				// this.terminal.setOption('theme', { background: '#282c34' });
				// ...
				this.terminal.write('\x1b[?25l')

				// 示例：在终端中输出一行文本
				// this.terminal.write('Hello, UniApp xterm!');
				this.initSocket()
			},
			initSocket(data) {
				// 打开websocket
				// let wsUrl =`${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/orion/keep-alive/tail/${this.token}`
				let wsUrl = `ws://192.168.1.15:35/orion/keep-alive/tail/${this.token}`
				console.log(wsUrl)
				let _this = this

				this.socketTask = uni.connectSocket({
					url: wsUrl,
					header: {
						'content-type': 'application/json'
					},
					responseType: 'String',
					success: (res) => {
						console.log('1,链接已建立')
						console.log(res)

					},
					complete: () => {
						console.log('WebSocket connected');
					},
				});

				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开！');
				});
				uni.onSocketMessage(async (event) => {
					let data = event.data
					let bob = new Blob([data])
					console.log(bob)
					console.log(data)
					// console.log(await bob.text())
					_this.terminal.write(await bob.text())
					_this.terminal.scrollToBottom()

				});
				uni.onSocketError(function(res) {
					console.log(res)
					console.log('WebSocket连接打开失败，请检查！');
				});


				return
				this.client = new WebSocket(wsUrl)
				this.client.onopen = () => {
					this.status = LOG_TAIL_STATUS.RUNNABLE.value
					this.$emit('open')
				}
				this.client.onerror = () => {
					this.status = LOG_TAIL_STATUS.ERROR.value
				}
				this.client.onclose = (e) => {
					this.status = LOG_TAIL_STATUS.CLOSE.value
					if (e.code > 4000 && e.code < 5000) {
						// 自定义错误信息
						this.term.write(`\x1b[93m${e.reason}\x1b[0m`)
					}
					this.$emit('close')
				}
				this.client.onmessage = async event => {
					console.log('来这了吗？')
					this.term.write(await event.data.text())
					if (!this.fixedLog) {
						this.term.scrollToBottom()
					}
				}
			},
		},
	};
</script>

<style>
	/* @import 'xterm/dist/xterm.css'; */
	.imagesBox {
		width: 450rpx;
		height: 450rpx;
	}
</style>