<template>
    <div class="email-activation">
        <login-header></login-header>
        <main class="wrap">
            <section>
                <div class="login-form">
                    <img src="~assets/images/icon-yz.png" alt />
                    <h2>邮箱激活</h2>
                    <p class="notice">邮箱验证码发送到您注册邮箱，请注意查收！</p>
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                        <el-form-item prop="email">
                            <el-input
                                v-model.trim="ruleForm.email"
                                placeholder="请输入邮箱地址"
                                maxlength="50"
                            ></el-input>
                        </el-form-item>
                        <el-form-item prop="verificationCode">
                            <el-input
                                v-model.trim="ruleForm.verificationCode"
                                placeholder="邮箱验证码"
                                class="verification-code"
                                maxlength="4"
                            ></el-input>
                            <el-button
                                type="primary"
                                :loading="sendSmsLoading"
                                @click="sendSms"
                                v-if="showCountDown"
                            >发送验证码</el-button>
                            <el-button
                                type="primary"
                                :loading="false"
                                class="count-down"
                                disabled
                                v-else
                            >{{countDown}}秒</el-button>
                        </el-form-item>
                        <el-form-item class="btn-reg">
                            <el-button
                                type="primary"
                                @click="submitForm('ruleForm')"
                                :loading="loading"
                            >激活完成</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </section>
        </main>
        <login-footer></login-footer>
    </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
    api_emailValidate,
    api_email,
    api_verifyEmailExists
} from "api/login.js";
import loginHeader from "./components/header";
import loginFooter from "./components/footer";
import utils from "utils/utils.js";
let timer;
export default {
    name: "emailActivation",
    components: {
        loginHeader,
        loginFooter
    },
    computed: {
        ...mapState(["userInfo"])
    },
    data() {
        var checkCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("验证码不能为空"));
            } else {
                callback();
            }
        };

        var validateEmail = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请正确填写邮箱"));
            } else if (!utils.isvalidEmail(value)) {
                callback(new Error("请输入有效的邮箱"));
            } else {
                let email = {
                    params: {
                        email: value
                    }
                };
                api_verifyEmailExists(email)
                    .then(res => {
                        if (res.success) {
                            callback();
                        } else {
                            callback(new Error(res.msg));
                        }
                    })
                    .catch(err => {});
            }
        };
        return {
            ruleForm: {
                email: "",
                verificationCode: ""
            },
            rules: {
                email: [{ validator: validateEmail, trigger: "blur" }],
                verificationCode: [{ validator: checkCode, trigger: "blur" }]
            },
            countDown: 60,
            showCountDown: true,
            loading: false,
            markStr: "",
            autoSend: false,
            sendSmsLoading: false
        };
    },
    methods: {
        ...mapMutations(["setLoginInfo", "setMarkStr"]),
        countDownFn() {
            this.$message.success("邮箱验证码已发送，请注意查收！");
            this.showCountDown = false;
            timer = setInterval(() => {
                this.countDown--;
                if (this.countDown < 0) {
                    this.showCountDown = true;
                    clearInterval(timer);
                    this.countDown = 60;
                }
            }, 1000);
        },
        sendSms() {
            this.sendSmsLoading = true;
            if (this.showCountDown) {
                this.$refs.ruleForm.validateField("email", valid => {
                    if (valid !== "") {
                        this.sendSmsLoading = false;
                    } else {
                        let emailData = {
                            data: {
                                phoneNo: this.userInfo.loginInfo.phoneNo,
                                emailAdd: this.ruleForm.email
                            }
                        };
                        api_email(emailData)
                            .then(res => {
                                if (res.success) {
                                    this.$message.success(
                                        "邮箱验证码已发送，请注意查收！"
                                    );
                                    this.sendSmsLoading = false;
                                    this.showCountDown = false;
                                    timer = setInterval(() => {
                                        this.countDown--;
                                        if (this.countDown < 0) {
                                            this.showCountDown = true;
                                            clearInterval(timer);
                                            this.countDown = 60;
                                        }
                                    }, 1000);
                                    this.$store.commit(
                                        "setMarkStr",
                                        res.data.markStr
                                    );
                                } else {
                                    this.sendSmsLoading = false;
                                    this.$message.error(res.msg);
                                }
                            })
                            .catch(err => {
                                this.sendSmsLoading = false;
                            });
                    }
                });
            }
        },
        submitForm(formName) {
            let copyInitVuex = JSON.parse(localStorage.getItem("initVuex"));
            copyInitVuex.userInfo.loginInfo.emailActiveFlag = true;
            this.loading = true;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let emailValidateData = {
                        data: {
                            phoneNo: this.userInfo.loginInfo.phoneNo,
                            emailAdd: this.ruleForm.email,
                            markStr: this.markStr || this.userInfo.markStr,
                            emailCode: this.ruleForm.verificationCode
                        }
                    };
                    api_emailValidate(emailValidateData)
                        .then(res => {
                            if (res.success) {
                                this.$store.commit(
                                    "setLoginInfo",
                                    copyInitVuex.userInfo.loginInfo
                                );
                                localStorage.setItem(
                                    "initVuex",
                                    JSON.stringify(copyInitVuex)
                                );
                                this.$router.push({
                                    path: "/regSucc"
                                });
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                        .catch(err => {});
                    this.loading = false;
                } else {
                    this.loading = false;

                    return false;
                }
            });
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            if (from.name === "register") {
                //vm.countDownFn();
            }
        });
    },
    created() {
        clearInterval(timer);
    },
    mounted() {
        if (this.userInfo.loginInfo.emailActiveFlag) {
            this.$router.push({
                path: "/account"
            });
        }
    }
};
</script>

<style lang="less" scoped>
.email-activation /deep/ .verification-code {
    width: 190px;
}
.email-activation /deep/ .verification-code + .el-button--primary {
    width: 120px;
    padding: 12px 0;
    margin-left: 16px;
    vertical-align: middle;
}
.email-activation /deep/ .btn-reg {
    .el-button--primary {
        width: 100%;
    }
}
.count-down {
    width: 120px;
}
.email-activation {
    background: #f7f7f7;
}
.wrap {
    min-height: calc(100vh - 224px);
    margin: 50px 0;
    section {
        width: 1080px;
        margin: 0 auto;
        padding: 60px 0;
        background: #fff;
        .login-form {
            width: 330px;
            margin: 0 auto;
            padding: 30px 0 18px;
            text-align: center;
            h2 {
                font-size: 28px;
                font-weight: normal;
                color: #3f87e9;
            }
            .notice {
                margin: 12px 0 50px;
                font-size: 12px;
                color: #666;
            }
        }
    }
}
</style>
