<template>
    <main>
        <section class="layout-box">
            <div class="center-title clearfix">
                <h3>通过邮箱验证校验</h3>
                <a href="javascript:;" class="back-btn" @click="goBack">返回</a>
            </div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                <template v-if="stepOne">
                    <el-form-item prop="oldPhoneNum">
                        <el-input type="text" v-model.number="ruleForm.oldPhoneNum" disabled></el-input>
                    </el-form-item>
                    <el-form-item prop="oldEmail">
                        <el-input type="text" v-model.number="ruleForm.oldEmail" disabled></el-input>
                    </el-form-item>
                </template>
                <template v-else>
                    <el-form-item prop="email">
                        <el-input type="text" v-model="ruleForm.email" placeholder="请输入新的邮箱"></el-input>
                    </el-form-item>
                </template>
                <el-form-item prop="verificationCode">
                    <el-input
                        v-model.trim="ruleForm.verificationCode"
                        placeholder="邮箱验证码"
                        class="verification-code"
                        maxlength="6"
                    ></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" v-if="stepOne">
                    <el-button
                        type="primary"
                        @click="submitForm('ruleForm')"
                        :loading="submitLoading"
                    >下一步</el-button>
                </el-form-item>
                <el-form-item class="btn-reg" v-else>
                    <el-button
                        type="primary"
                        @click="submitForm2('ruleForm')"
                        :loading="submitLoading2"
                    >确定修改</el-button>
                </el-form-item>
            </el-form>
        </section>
    </main>
</template>

<script>
import { mapState } from "vuex";
import { api_verifyEmailExists, api_email } from "api/login.js";
import {
    api_changeMoblie,
    api_validateEmail,
    api_changeEmail
} from "api/center.js";
import utils from "utils/utils.js";
let timer;
export default {
    name: "setLoginPass",
    computed: {
        ...mapState(["userInfo"])
    },
    methods: {
        goBack() {
            this.$router.go(-1);
        },
        sendSms() {
            this.sendSmsLoading = true;
            if (this.showCountDown) {
                if (this.stepOne) {
                    let verificationCode = {
                        data: {
                            phoneNo: this.userInfo.loginInfo.phoneNo,
                            emailAdd: this.ruleForm.oldEmail
                        }
                    };

                    api_email(verificationCode)
                        .then(res => {
                            if (res.success) {
                                this.sendSmsLoading = false;
                                this.showCountDown = false;
                                this.markStr = res.data.markStr;

                                this.$message({
                                    message: "验证码发送成功，请注意查收",
                                    type: "success"
                                });
                                timer = setInterval(() => {
                                    this.countDown--;
                                    if (this.countDown < 0) {
                                        this.showCountDown = true;
                                        clearInterval(timer);
                                        this.countDown = 60;
                                    }
                                }, 1000);
                            } else {
                                this.$message.error(res.msg);
                                this.sendSmsLoading = false;
                            }
                        })
                        .catch(err => {
                            this.sendSmsLoading = false;
                        });
                } else {
                    this.$refs.ruleForm.validateField("email", valid => {
                        if (valid !== "") {
                            this.sendSmsLoading = false;
                            this.rules.oldPhoneNum;
                        } else {
                            let verificationCode = {
                                data: {
                                    emailAdd: this.ruleForm.email
                                }
                            };

                            api_email(verificationCode)
                                .then(res => {
                                    if (res.success) {
                                        this.sendSmsLoading = false;
                                        this.showCountDown = false;
                                        this.markStr = res.data.markStr;

                                        this.$message({
                                            message:
                                                "验证码发送成功，请注意查收",
                                            type: "success"
                                        });
                                        timer = setInterval(() => {
                                            this.countDown--;
                                            if (this.countDown < 0) {
                                                this.showCountDown = true;
                                                clearInterval(timer);
                                                this.countDown = 60;
                                            }
                                        }, 1000);
                                    } else {
                                        this.$message.error(res.msg);
                                        this.sendSmsLoading = false;
                                    }
                                })
                                .catch(err => {
                                    this.sendSmsLoading = false;
                                });
                        }
                    });
                }
            }
        },
        submitForm(formName) {
            this.submitLoading = true;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let validateEmailData = {
                        data: {
                            emailAdd: this.ruleForm.oldEmail,
                            markStr: this.markStr,
                            emailCode: this.ruleForm.verificationCode
                        }
                    };
                    api_validateEmail(validateEmailData).then(res => {
                        if (res.success) {
                            this.stepOne = false;
                            clearInterval(timer);
                            this.ruleForm.verificationCode = "";
                            this.countDown = 60;
                            this.showCountDown = true;
                        } else {
                            this.$message.error(res.msg);
                        }
                        this.submitLoading = false;
                    });
                } else {
                    this.submitLoading = false;

                    return false;
                }
            });
        },
        submitForm2(formName) {
            this.submitLoading2 = true;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let changeEmailData = {
                        data: {
                            newEmail: this.ruleForm.email,
                            markStr: this.markStr,
                            emailCode: this.ruleForm.verificationCode
                        }
                    };
                    api_changeEmail(changeEmailData).then(res => {
                        if (res.success) {
                            this.$router.push({
                                path: "/center/setting/email/result"
                            });
                        } else {
                            this.$message.error(res.msg);
                        }
                        this.submitLoading2 = false;
                    });
                } else {
                    this.submitLoading2 = false;

                    return false;
                }
            });
        }
    },
    data() {
        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 => {});
            }
        };
        var checkCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("验证码不能为空"));
            } else if (value.length < 4) {
                return callback(new Error("验证码格式不正确"));
            } else {
                callback();
            }
        };
        return {
            ruleForm: {
                oldPhoneNum: "",
                email: "",
                verificationCode: ""
            },
            rules: {
                email: [{ validator: validateEmail, trigger: "blur" }],
                verificationCode: [{ validator: checkCode, trigger: "blur" }]
            },
            submitLoading: false,
            submitLoading2: false,
            stepOne: true,
            oldKycDictionaryId: "",
            countDown: 60,
            showCountDown: true,
            sendSmsLoading: false,
            markStr: ""
        };
    },
    created() {
        clearInterval(timer);
    },
    mounted() {
        this.ruleForm.oldPhoneNum =
            this.userInfo.loginInfo.phoneNo.substring(0, 3) +
            "****" +
            this.userInfo.loginInfo.phoneNo.substring(7);
        this.ruleForm.oldEmail = this.userInfo.loginInfo.email;
    }
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/common.css";
.layout-box {
    overflow: hidden;
    min-height: calc(100vh - 184px);
    background: #fff;
}
.layout-box /deep/ .el-input.is-disabled .el-input__inner {
    color: #333;
}
.layout-box /deep/ .verification-code {
    width: 190px;
}
.layout-box /deep/ .verification-code + .el-button--primary {
    width: 120px;
    padding: 12px 0;
    margin-left: 16px;
    vertical-align: middle;
}
.count-down {
    width: 120px;
}
.el-form {
    width: 330px;
    margin: 60px;
    .el-button,
    .el-select {
        width: 330px;
    }
}
.center-title {
    position: relative;
}
.back-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    padding-left: 22px;
    font-size: 14px;
    background: url(~assets/images/icon-center-back.png) left center no-repeat;
    color: #3d86e9;
}
</style>
