<template>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="0" label-position="top" size="large" @keyup.enter="login">
		<el-form-item prop="phone" :label="$t('login.mobilePlaceholder')">
			<el-input v-model="form.phone" prefix-icon="el-icon-iphone" clearable :placeholder="$t('login.mobilePlaceholder')">
				<template #prepend>+86</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="yzm" :label="$t('login.smsPlaceholder')">
			<div class="login-msg-yzm">
				<el-input v-model="form.yzm" prefix-icon="el-icon-unlock" clearable :placeholder="$t('login.smsPlaceholder')"></el-input>
				<el-button @click="getYzm" :disabled="disabled">{{this.$t('login.smsGet')}}<span v-if="disabled"> ({{time}})</span></el-button>
			</div>
		</el-form-item>
        <el-form-item prop="code" :label="$t('login.code')">
            <el-input v-model="form.code" :placeholder="$t('login.codeErr')">
				<template #suffix>
					<el-tooltip placement="top-start" :content="$t('login.codeTips')">
						<div class="captcha" @click="updateCaptcha"><img :src="captcha.base64" /></div>
					</el-tooltip>
				</template>
			</el-input>
        </el-form-item>
        <el-form-item prop="privacy">
            <el-checkbox :label="$t('login.rememberMe')" v-model="form.privacy">
                <template #default>
                    <div class="privacy">我已阅读并同意<span @click="showPrivacy">《隐私协议》</span></div>
                </template>
            </el-checkbox>
        </el-form-item>
		<el-form-item>
            <el-button type="primary" size="large" style="width: 100%;" :loading="islogin" @click="login">{{ $t('login.signIn') }}</el-button>
		</el-form-item>
	</el-form>
	<el-dialog title="隐私协议" v-model="visible" :width="680" destroy-on-close :close-on-click-modal="false" :show-close="false">
		<div class="showPrivacy">
			<div v-html="baseData.privacy"></div>
		</div>
		<template #footer>
			<el-button type="primary" @click="showPrivacyState">我已阅读并同意</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
    emits: ['success', 'upCaptcha'],
    props: ['baseData',"captcha"],
	data() {
		return {
			form: {
				phone: "",
				yzm: "",
			},
			rules: {
				phone: [
					{ required: true, message: this.$t('login.mobileError'), trigger: 'blur' },
					{
						validator: (rule, value, callback) => {
							const phoneReg = /^1[3-9]\d{9}$/ // 手机号正则
							const landlineReg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/
							if (!value) {
								callback(new Error('请输入联系方式'))
							} else if (!phoneReg.test(value) && !landlineReg.test(value)) {
								callback(new Error('请输入有效的手机号码号码'))
							} else {
								callback()
							}
						},
						trigger: 'blur'
					}
				],
				yzm: [
					{required: true, message: this.$t('login.smsError')}
				],
				code: [
					{ required: true, message: this.$t('login.codeErr'), trigger: 'blur' }
				],
				privacy: [
					{ required: true, message: this.$t('login.privacy'), trigger: 'change' }
				]
			},
			disabled: false,
			time: 0,
			islogin: false,
			visible:false,
			isShow:false
		}
	},
	mounted() {

	},
	methods: {
		updateCaptcha(){
			this.$emit("upCaptcha");
		},
		showPrivacy(){
			this.visible = true;
		},
		showPrivacyState(){
			if (this.form.privacy == false) {
				this.form.privacy = true;
			}
			this.visible = false;
		},
		onClose() {
			this.isShow = false;
		},
		async onSuccess(){
			this.isShow = false;
		},
		getYzm(){
			var field = ["phone","code"];
			this.$refs.loginForm.validateField(field, async (valid) => {
				if(!valid){
					return false
				}
				var resp = await this.$API.auth.sms.post({"mobile":this.form.phone,"code":this.form.code,"key":this.captcha.key,"scene":"login"});
				if (resp.code == 0) {
					return this.$message.error(resp.msg);
				}
				this.$message.success(resp.msg)
				this.disabled = true
				this.time = 60
				var t = setInterval(() => {
					this.time -= 1
					if(this.time < 1){
						clearInterval(t)
						this.disabled = false
						this.time = 0
					}
				},1000)
			})
		},
		async login(){
			var validate = await this.$refs.loginForm.validate().catch(()=>{})
			if(!validate){ return false }
			this.isShow = false;
			this.islogin = true
			var data = {
				mobile: this.form.phone,
				code: this.form.yzm,
				scene: "login",
			}
			//获取token
			var user = await this.$API.auth.mobile.post(data)
			if (user.code == 1) {
				this.$TOOL.cookie.set("TOKEN", user.data.access_token, {
					expires: user.data.expires_in
				})
			} else {
				this.islogin = false
				this.$message.error(user.msg)
				return false
			}
			//获取菜单
			var menu = await this.$API.menu.list.get()
			if (menu.code == 1) {
				if (menu.data.menu.length == 0) {
					this.islogin = false
					this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
						type: 'error',
						center: true
					})
					return false
				}
				var userData = await this.$API.auth.user.get()
				if (userData.code == 0) {
					this.islogin = false
					this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
						type: 'error',
						center: true
					})
					return false
				}
				if (userData.data.is_mch == 2) {
					this.$store.commit("SET_layout", "header")
				} else {
					this.$store.commit("TOGGLE_layoutTags")
				}
				this.$TOOL.data.set("USER_TYPE", userData.data.type)
				this.$TOOL.data.set("USER_INFO", userData.data)
				this.$TOOL.data.set("MENU", menu.data.menu)
				this.$TOOL.data.set("PERMISSIONS", menu.data.permissions)
				this.$TOOL.data.set("DASHBOARDGRID", menu.data.dashboardGrid)
			} else {
				this.islogin = false
				this.$message.warning(menu.message)
				return false
			}
			var userType = userData.data.type;
			var dashboard = "/dashboard";
			if (userType == 1) {
				dashboard = "/manage/dashboard";
			} else if (userType == 2) {
				dashboard = "/merchant/dashboard";
			} else if (userType == 3) {
				dashboard = "/store/dashboard";
			} else if (userType == 4) {
				dashboard = "/factory/dashboard";
			}
			this.$emit("success");
			this.$message.success(user.msg)
			this.islogin = false;
			this.$router.replace({
				path: dashboard
			})
		}
	}
}
</script>

<style>

.privacy {
	color: #333;
}
.privacy span {
	color: #f00;
}
.showPrivacy {
	max-height: 500px;
	overflow: hidden;
	overflow-y: scroll;
	line-height: 1.5;
}
.el-input--large .el-input__wrapper{
	position: relative;
}
.captcha{
	display: flex;
	align-items: center;
	cursor: pointer;
	position: absolute;
	right: 1px;
	top: 1px;
	bottom: 1px;
	z-index: 99;
}
.captcha img{
	height: 38px;
	border-radius: 5px;
}
</style>