<template>
	<view class="_capmain">
		<input class="inp flex1" type="number" :name="name" :placeholder="placeholder" :maxlength="codelength" confirm-type="done" cursor-spacing="120" />
		<input v-if="hasmore" type="hidden" :name="name+'_id'" :value="dbid" style="display:none;" />
		<view class="itm">
			<view v-if="sec>0">{{maxsec-sec}}</view>
			<button v-else class="btn sm sq" @tap="sendcap">{{btntxt}}</button>
		</view>
	</view>
</template>

<script>
	export default {
		behaviors: ['uni://form-field-group'],
		emits: ['change'],
		props: {
			name: {
				type: String,
				default: ''
			},
			hasmore: {
				type: Boolean,
				default: false
			},
			btntxt: {
				type: String,
				default: ''
			},
			account: {
				type: String,
				default: ''
			},
			func: {
				type: String,
				default: ''
			},
			placeholder: {
				type: String,
				default: ''
			},
			codelength: {
				type: [String,Number],
				default: 4
			},
			maxsec: {
				type: [String,Number],
				default: 60
			}
		},
		data() {
			return {
				sec: 0,
				dbid: 0,
				capid: '',
			};
		},
		watch: {},
		mounted() {
		},
		methods: {
			async sendcap(e) {
				if(!this.account)
					return this.toast(this.lang('capcode.noinput'));
					
				var retjson = await this.callajax({
					func: this.func,
					data:{account:this.account,length:this.codelength}
				});
				if(retjson.code != 1)
					return this.toast(retjson.errmsg);
				this.dbid = retjson.id;
				this.sec++;
				this._sectick = setInterval(() => {
					this.sec++;
					if (this.sec < this.toint(this.maxsec))
						return;
					this.sec = 0;
					clearInterval(this._sectick);
					this.$emit('change', {
						from: 'tickend',
						value: 0
					});
				}, 1000);
				this.$emit('change', {
					from: 'send',
					value: retjson
				});
			}
		}
	}
</script>

<style scoped>
	._capmain {
		display: flex;
		align-items: center;
		position: relative;
	}

	._capmain>.inp {
		text-align: center;
		font-size: 1em;
		height: 1em;
	}

	._capmain>.itm {
		min-width: 6em;
		text-align: right;
	}

</style>