<template>
	<u-popup v-model="show" mode="center" closeable @close='close' border-radius='20'>
		<view class="content">
			<view class="title">
				图片验证
			</view>
			<view class="loading" v-show="loadImage=='ok'" @click="getImage()">
				<image class="codeImg" @load="loadImage='ok'" @error="loadImage='err'" :src="image" mode="scaleToFill">
				</image>
			</view>
			<view class="loading" v-if="loadImage=='loading'">
				加载中...
			</view>
			<view class="loading" v-if="loadImage=='err'" @click="getImage()">
				加载失败点击刷新
			</view>
			<input class="codeInput" type="text" v-model="code" placeholder="请输入图片中的验证内容" />
			<view class="flex">
				<u-button class="buttom" size='medium' @click="getImage()">刷新</u-button>
				<u-button class="buttom" size='medium' type="primary" @click="openVerify">确定</u-button>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import {
		verify_code,
		verify
	} from '@/api/login.js';
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		props: {
			show: {
				type: Boolean,
				default: false,
			},
			phone: {
				type: Number|String,
				default: '',
			},
			loginType: {
				type: String,
				default: '',
			}
		},

		data() {
			return {
				code: '',
				image: '',
				loadImage: "loading",
				key: '',
			}
		},
		computed: {
			...mapState(['baseURL'])
		},
		methods: {
			close() {
				this.$emit("close")
			},
			async getImage() {
				try {
					this.loadImage = "loading";
					let {
						data: {
							key
						}
					} = await verify_code();
					this.key = key;
					this.image = `${this.baseURL}/api/sms_captcha?key=${key}&time=${(new Date()).getTime()}`;

				} catch (e) {
					console.log(e, "err")
					//TODO handle the exception
				}
			},
			openVerify() {
				const obj = this;
				if(!obj.code){
					uni.showToast({
						title:"请输入图片中的内容"
					})
				}
				verify({
						key: obj.key,
						phone: obj.phone,
						type: obj.loginType,
						code:obj.code
					})
					.then(({
						data
					}) => {
						console.log(data, 'data')
						uni.showToast({
							title: '验证码已发送',
							duration: 2000,
							position: 'top',
							icon: 'none'
						});
						obj.close();
						obj.$emit("openCode")
					})
					.catch(err => {
						obj.code="";
						uni.showToast({
							title: err.msg,
							icon:"error"
						});
						obj.getImage();
						console.log(err, 'err');
					});
			}
		},
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 30rpx;

		.codeImg {
			width: 100%;
			height: 130rpx;
		}

		.loading {
			margin-top: 30rpx;
			background-color: #e3e3e3;
			border-radius: 10rpx;
			overflow: hidden;
			text-align: center;
			line-height: 130rpx;
			width: 660rpx;
			height: 130rpx;
			color: #999999;
		}
	}

	.codeInput {
		width: 100%;
		height: 60rpx;
		padding-bottom: 30rpx;
		border-bottom: 1px solid #e3e3e3;
		margin-top: 50rpx;
		margin-bottom: 50rpx;
	}
</style>