<template>
	<view class="image-txt-wrap">
		<image :src="captchaBase" class="image" @click="getCode"></image>
		<text class="tip-txt">* 点击图片即可切换验证码</text>
		<input v-model="captcha" @input="inpChange" class="item-inp" name="captcha" type="text" maxlength="4" placeholder="请输入上方的图形验证码" />
		<button :type="btnType" size="mini" class="popup-button-yz" @click="verify">验证</button>
	</view>
</template>

<script>
	import { getCaptcha } from '@/api/user.js'
	export default{
		name: 'ImageTxtPopup',
		props: {
			changeImg: {
				type: Boolean,
				default: false
			},
			//  applyImageTxt申请试用   forgetImageTxt忘记密码
			type: {
				type: String,
				default: ''
			},
		},
		watch: {
			changeImg(newV, oldV){
				if(newV === true){
					this.getCode()
				}
			}
		},
		data(){
			return{
				captchaBase: '',  //  图片验证码base64
				captcha: '',  //  图文验证码
				nowRandomCode: '',  // 当前随机码
				btnType: 'default',  //  验证按钮type
			}
		},
		created() {
			// this.getCode()
		},
		methods: {
			//  获取验证码
			getCode(){
			  const _this = this
			  //  6位随机数
			  this.nowRandomCode = Math.random().toString().slice(-6)
			  getCaptcha(this.nowRandomCode).then(res => {
				// console.log(res.data)
			    //  获取图片路径
			    _this.captchaBase = 'data:image/png;base64,' + res.data
			    // 显示图文验证码弹框
			    _this.captcha = ''  //  清空图文输入内容
			  })
			},
			//  验证码输入监听
			inpChange(){
				if(this.captcha.length == 4){
					this.btnType = 'primary'
				}else{
					this.btnType = 'default'
				}
			},
			//  验证
			verify(){
				if(!this.captcha){
					uni.showToast({icon: 'none',title: '请输入上方的图形验证码'})
					return
				}else{
					if(this.captcha.length != 4){
						uni.showToast({icon: 'none',title: '请输入4位图形验证码'})
						return
					}
					this.$emit('captchaImg', this.captcha, this.nowRandomCode)
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.image-txt-wrap{
		line-height: 1.8;
		.tip-txt{
			display: block;
			font-size: 24upx;
			color: #999;
			margin-bottom: 40upx;
			text-align: center;
		}
		.item-inp{
			background-color: #fff;
			border: 2upx solid #dcdee2;
			border-radius: 8upx;
			color: #666;
			display: inline-block;
			font-size: 24upx;
			height: 64upx;
			line-height: 1.5;
			padding: 8upx 14upx;
			width: 100%;
			box-sizing: border-box;
		}
		.image{
			max-width: 100%;
			width: 400upx;
			height: 160upx;
			margin: 30upx auto 20upx;
			display: block;
			img{
				max-width: 100%;
			}
		}
		.popup-button-yz{
			display: block;
			margin: 40upx auto 50upx;
			width: 30%;
			line-height: 2.8;
		}
	}
</style>
