<template>
	<!-- <iframe src="https://chat.mddai.cn/" frameborder="0"></iframe> -->
	<view class="">
		<view style="color: #fff;z-index: 99999999;position: relative;">
			<tn-nav-bar :bottomShadow="false" backgroundColor="#207CF7">数智员工</tn-nav-bar>
			<view :style="{height: tobheight+'px'}"></view>
		</view>

		<div class="employBox">

			<div class="applyBox" v-if='isApply'>
				<div class="t1">
					您尚未申请微信机器人
				</div>
				<div class="t2" v-if="status==null||status==2" :style="{color:!userInfo.robot_is_login?'':'#237FED'}">
					填写下方资料申请
				</div>
				<div v-if="status==null||status==2">
					<div class="name">
						<div class="left">
							姓名:
						</div>
						<div class="right">
							<u--input placeholder="请输入姓名" border="surround" v-model="rName"></u--input>
						</div>
					</div>
					<div class="phone">
						<div class="left">
							手机号:
						</div>
						<div class="right">
							<u--input placeholder="请输入手机号" border="surround" v-model="rPhone"></u--input>
						</div>
					</div>
					<u-button @click="applyR" color="linear-gradient(90deg, #549DFF 0%, #207CF7 100%)" text="提交申请"
						style="width: 85%;margin-top: 120rpx;"></u-button>
				</div>
				<div v-if="status==0" class="part">
					<!-- <div class="part"> -->
					<div class="txt" style="color: orange;">
						微信机器人申请审核中
					</div>
				</div>
				<div v-if="status==2" class="part">
					<!-- <div class="part"> -->
					<div class="txt" style="color: red;">
						微信机器人申请审核失败,您可以重新申请
					</div>
					<div class="becuase">失败原因：</div>
					<div class="des">
						{{robotInfo}}
					</div>
				</div>
			</div>

			<div v-else>
				<div class="stateBox">
					<div class="left">
						当前状态：{{loginTxt}}
					</div>
					<!-- 	<div class="btn">
						登录
					</div> -->
				</div>
				<div class="t1">
					{{!userInfo.robot_is_login?'使用微信扫码登录机器人':userInfo.nickname}}

				</div>
				<div class="t2" :style="{color:!userInfo.robot_is_login?'':'#237FED'}">
					{{!userInfo.robot_is_login?'微信扫码快速登录':'您已登录'}}

				</div>
				<!-- <image src="/static/loading_pic.gif" alt="" /> -->
				<div class="codeBox" v-if="!userInfo.robot_is_login">
					<div class="lt"></div>
					<div class="rt"></div>
					<div class="lb"></div>
					<div class="rb"></div>

					<img :src="codeInfo" alt="" v-if="codeInfo" />
					<image src="/static/loading_pic.gif" alt="" v-else />

				</div>

				<img v-else
					style="margin-top: 100rpx;margin-left: 50%;transform: translateX(-50%);width: 250rpx;height: 250rpx;"
					src="@/static/success.png" alt="" />

				<div class="fresh" v-if="!userInfo.robot_is_login">
					<span>刷新</span>
					<image @click="fresh" ref="hyh" id="img01" class="shuaxin" :class="{'go':addRotate}"
						src="/static/newIndex/change.png" style="width: 32rpx;height:28rpx;">
					</image>
				</div>
				<div class="btn2" v-if="is_wx" @click="handleDw(codeInfo)">
					保存二维码图片
				</div>
			</div>

		</div>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				addRotate: false,
				content: '',
				type: '',
				title: '',
				tobheight: 45,
				platform: this.$platform.get(),
				isLoading: true,


				codeInfo: '',

				loginTxt: '未登录',

				timer: null,

				is_wx: false,
				isPc: false,
				isDowload: false,
				userInfo: {
					robot_is_login: 0
				},

				isApply: true,

				rName: '',
				rPhone: '',

				status: -1,

				robotInfo: ''

			}
		},
		async onLoad(e) {


			if (e && e.type) {
				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)
				}
			}


			const userAgent = navigator.userAgent.toLowerCase();
			if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(userAgent)) {
				// 移动端
				console.log('移动端')
				this.isPc = false
			} else {
				// pc端
				this.isPc = true
				console.log('PC端')
			}
			// console.log('1213', download);
			this.is_wx = this.is_weixin()

		},

		onShow() {
			this.getUserInfo()
		},
		beforeDestroy() {
			console.log('beforeDestroy()---------------------');
			clearInterval(this.timer)
		},
		onHide() {
			console.log('onHide()---------------------');
			// 清除定时器
			clearInterval(this.timer)
		},
		methods: {

			async applyR() {
				let phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/
				if (!this.rName) {
					return uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					})
				}
				if (!this.rPhone) {
					return uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
				}
				if (!phoneReg.test(this.rPhone)) {
					return uni.showToast({
						title: '手机号不合法',
						icon: 'none'
					})
				}
				let p = {
					name: this.rName,
					mobile: this.rPhone,
				}
				let res1 = await this.$http('robot.robotApplay', p)
				if (res1.code == 0) {
					uni.showToast({
						title: '申请提交成功，请等待审核通过',
						icon: 'success'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
				console.log('申请机器人返回值', res1);
			},
			fresh() {
				clearInterval(this.timer)
				this.getCodeData()
				this.addRotate = true
				setTimeout((item, index) => {
					this.addRotate = false
				}, 1000)
			},
			// 判断是否是微信浏览器
			is_weixin() {
				var ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					console.log('微信浏览器');
					return true;
				} else {
					console.log("不是微信浏览器");
					return false;
				}
			},
			async getCodeData() {
				if (!uni.getStorageSync('token')) {
					return
				}
				let res1 = await this.$http('robot.createRobot', {})
				if (res1.code == 0) {
					// this.draftList = res1.data
					this.codeInfo = res1.msg.wxRobotLoginUrl
					console.log('机器人二维码返回值：', res1, this.codeInfo);


					let _this = this
					this.timer = setInterval(() => {
						_this.getCodeState()
					}, 3000)
					// this.loginTxt = '已登录'
				} else {
					uni.showToast({
						title: res1.msg,
						icon: 'none'
					})
				}
			},



			async getCodeState() {
				if (!uni.getStorageSync('token')) {
					return
				}
				let res1 = await this.$http('robot.checkRobotIsScan', {})
				console.log('机器人二维码状态返回值：', res1);
				if (res1.code == 0) {
					// this.draftList = res1.data
					this.loginTxt = '已扫码'
					this.getUserInfo()
					clearInterval(this.timer)
				} else {
					clearInterval(this.timer)
					// uni.showToast({
					// 	title: res1.msg,
					// 	icon: 'none'
					// })
				}
			},

			async getUserInfo() {
				if (!uni.getStorageSync('token')) {
					return
				}
				let res1 = await this.$http('robot.info', {})
				console.log('机器人用户状态返回值：', res1, res1.data);
				if (res1.code == 0) {
					this.isApply = !res1.data.is_config_fastgpt
					this.status = res1.data.robotInfo ? res1.data.robotInfo.state : null

					this.robotInfo = res1.data.robotInfo.no_msg

					// this.isApply = !0
					// this.status = 2
					if (!res1.data.is_config_fastgpt) {
						return
					}

					this.userInfo = res1.data
					if (res1.data.robot_is_login == 1) {
						this.loginTxt = '已登录'
						clearInterval(this.timer)
					} else {
						this.getCodeData()
					}
				} else {
					clearInterval(this.timer)
					uni.showToast({
						title: res1.msg,
						icon: 'none'
					})
				}
			},

			async handleDw(url) {
				let _this = this

				const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
					.test(
						navigator.userAgent) ? false : true;
				if (this.is_wx) {
					// 微信内置浏览器
					// this.downLoad2(this.delItem.url)
					let _that = this
					uni.showModal({
						title: '温馨提示',
						content: '微信内置浏览器不支持图片下载，请长按图片以保存到手机',
						confirmText: '知道了',
						confirmColor: '#207CF7',
						success: function(res) {

						}
					})
					return
				} else {
					if (detectDeviceType()) {
						let _this = this
						// PC端
						// this.delItem.url = 'http://www.liwantao.top/test.mp4'
						uni.downloadFile({
							url, //文件链接
							timeout: 99999999,
							success: (res) => {
								if (res.statusCode === 200) {
									var oA = document.createElement("a");
									oA.download = '数智员工登录二维码'; // 设置下载的文件名，默认是'下载'	
									oA.href = res.tempFilePath; //临时路径再保存到本地
									document.body.appendChild(oA);
									oA.click();
									oA.remove(); // 下载之后把创建的元素删除
								}
							},
							fail: (err) => {
								// console.log(_this.show, _this.isDowload, _this.progress, err);
								uni.showToast({
									icon: 'none',
									mask: true,
									title: '失败请重新下载',
								});
							},
						})

					} else {
						// 其他移动端浏览器
						// window.open(this.delItem.url)

						let _this = this
						// this.delItem.url = 'http://www.liwantao.top/test.mp4'

						var oA = document.createElement("a");
						oA.download = '数智员工登录二维码';
						oA.href = url;
						document.body.appendChild(oA);
						oA.click();
						oA.remove();
					}
				}

			}
		}
	}
</script>

<style lang="scss">
	@import './index.scss';
</style>