<template>
    <div class="register-box">
        <login-header></login-header>
        <main class="wrap">
            <section>
                <div class="login-form">
                    <h1>Hi，欢迎注册!</h1>
                    <p>注册手机号将作为登录账号</p>
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                        <el-form-item prop="phoneNum">
                            <el-select v-model="value">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                            <el-input
                                type="text"
                                v-model.number="ruleForm.phoneNum"
                                placeholder="请输入手机号"
                                class="phone"
                                maxlength="11"
                            ></el-input>
                        </el-form-item>
                        <el-form-item prop="pass">
                            <el-input
                                type="password"
                                v-model.trim="ruleForm.pass"
                                autocomplete="off"
                                placeholder="请设置登录密码"
                                v-if="showPassword"
                                maxlength="20"
                            ></el-input>
                            <el-input
                                type="text"
                                v-model.trim="ruleForm.pass"
                                autocomplete="off"
                                placeholder="请设置登录密码"
                                v-else
                                maxlength="20"
                            ></el-input>
                            <div
                                :class="showPassword ? 'show-password' : 'hide-password'"
                                @click="toggleShowPassword"
                            ></div>
                        </el-form-item>
                        <el-form-item prop="checkPass">
                            <el-input
                                type="password"
                                v-model.trim="ruleForm.checkPass"
                                autocomplete="off"
                                placeholder="确认登录密码"
                                v-if="showCheckPassword"
                                maxlength="20"
                            ></el-input>
                            <el-input
                                type="text"
                                v-model.trim="ruleForm.checkPass"
                                autocomplete="off"
                                placeholder="确认登录密码"
                                v-else
                                maxlength="20"
                            ></el-input>
                            <div
                                :class="showCheckPassword ? 'show-password' : 'hide-password'"
                                @click="toggleShowCheckPassword"
                            ></div>
                        </el-form-item>
                        <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 prop="salesman" style="position:relative;width:190px;">
                            <el-input
                                v-model.trim="ruleForm.salesman"
                                placeholder="请填写邀请业务员姓名"
                                maxlength="50"
                                :disabled="checked"
                            ></el-input>
                            <el-checkbox
                                v-model="checked"
                                style="position:absolute;left:210px;top:0;"
                                @change="hasSalesman"
                            >无邀请业务员</el-checkbox>
                        </el-form-item>
                        <el-form-item prop="agreement" class="check-box">
                            <el-checkbox name="type" v-model="ruleForm.agreement"></el-checkbox>
                            <p>
                                我已阅读并同意
                                <router-link to="/agreement/privacyPolicy" target="_blank">《隐私政策》</router-link>
                            </p>
                        </el-form-item>
                        <el-form-item class="btn-reg">
                            <el-button
                                type="primary"
                                @click="submitForm('ruleForm')"
                                :loading="submitLoading"
                            >立即注册</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </section>
        </main>
        <login-footer></login-footer>
    </div>
</template>

<script>
import { mapMutations } from "vuex";
import {
    api_verifyMobileExists,
    api_register,
    api_code,
    api_validateCode,
    api_login
} from "api/login.js";
import utils from "utils/utils.js";
import loginHeader from "./components/header";
import loginFooter from "./components/footer";
let timer;
export default {
    name: "register",
    components: {
        loginHeader,
        loginFooter
    },
    data() {
        var checkPhone = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入手机号"));
            } else if (!utils.isvalidPhone(value)) {
                callback(new Error("手机号格式错误"));
            } else {
                let phoneNum = {
                    params: {
                        phoneNo: value
                    }
                };
                api_verifyMobileExists(phoneNum)
                    .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 < 6) {
                return callback(new Error("验证码格式不正确"));
            } else {
                callback();
            }
        };
        var validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else if (!utils.isvalidPass(value)) {
                callback(
                    new Error(
                        "密码位数最少8位且必须含有数字、小写字母、大写字母"
                    )
                );
            } else {
                if (this.ruleForm.checkPass !== "") {
                    this.$refs.ruleForm.validateField("checkPass");
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.ruleForm.pass) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        var validateSalesman = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("邀请业务员姓名不能为空"));
            } else if (!utils.regEngName(value)) {
                return callback(new Error("邀请业务员姓名只能输入汉字"));
            } else {
                callback();
            }
        };

        return {
            ruleForm: {
                phoneNum: "",
                pass: "",
                checkPass: "",
                verificationCode: "",
                salesman: "",
                agreement: []
            },
            rules: {
                phoneNum: [{ validator: checkPhone, trigger: "blur" }],
                pass: [{ validator: validatePass, trigger: "blur" }],
                checkPass: [{ validator: validatePass2, trigger: "blur" }],
                verificationCode: [{ validator: checkCode, trigger: "blur" }],
                salesman: [{ validator: validateSalesman, trigger: "blur" }],
                agreement: [
                    {
                        type: "array",
                        required: true,
                        message: "请阅读服务协议并选中",
                        trigger: "change"
                    }
                ]
            },
            options: [
                {
                    value: "选项1",
                    label: "+86"
                }
            ],
            value: "+86",
            checked: false,
            showPassword: true,
            showCheckPassword: true,
            countDown: 60,
            showCountDown: true,
            markStr: "",
            submitLoading: false,
            sendSmsLoading: false
        };
    },
    methods: {
        ...mapMutations(["setLoginInfo", "setMarkStr"]),
        toggleShowPassword() {
            this.showPassword = !this.showPassword;
        },
        toggleShowCheckPassword() {
            this.showCheckPassword = !this.showCheckPassword;
        },
        hasSalesman(val) {
            if (val) {
                this.ruleForm.salesman = "无";
                this.$refs.ruleForm.validateField("salesman", valid => {
                    if (valid !== "") {
                    } else {
                    }
                });
            } else {
                this.ruleForm.salesman = "";
            }
        },
        submitForm(formName) {
            if (this.markStr === "") {
                this.$message.error("请获取验证码！");
                return false;
            }
            this.submitLoading = true;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let registerData = {
                        data: {
                            phoneNo: this.ruleForm.phoneNum.toString(),
                            password: this.ruleForm.pass,
                            confirmpassword: this.ruleForm.checkPass,
                            markStr: this.markStr,
                            smsCode: this.ruleForm.verificationCode,
                            inviteCode: this.ruleForm.salesman
                        }
                    };
                    api_register(registerData).then(res => {
                        if (res.success) {
                            utils.setCookie("token", res.data.webToken);
                            this.$store.commit(
                                "setLoginInfo",
                                JSON.parse(res.data.kycNaturalVO)
                            );
                            this.$store.commit(
                                "setMarkStr",
                                res.data.emailMarkStr
                            );
                            localStorage.setItem(
                                "initVuex",
                                JSON.stringify(this.$store.state)
                            );
                            this.$router.push({
                                path: "/emailActivation"
                            });
                        } else {
                            this.$message.error(res.msg);
                        }
                        this.submitLoading = false;
                    });
                } else {
                    this.submitLoading = false;

                    return false;
                }
            });
        },
        sendSms() {
            this.sendSmsLoading = true;
            if (this.showCountDown) {
                this.$refs.ruleForm.validateField("phoneNum", valid => {
                    if (valid !== "") {
                        this.sendSmsLoading = false;
                    } else {
                        let verificationCode = {
                            data: {
                                phoneNo: this.ruleForm.phoneNum
                            }
                        };
                        api_code(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;
                            });
                    }
                });
            }
        }
    },
    created() {
        clearInterval(timer);
        let phoneNum = this.$route.query.phoneNum;
        if (phoneNum) {
            this.ruleForm.phoneNum = phoneNum;
        }

        // let initVuex = JSON.stringify(
        //     this.$store.state
        // ); /**用这种方法来实现深度拷贝，避免循环 */
        // localStorage.setItem("initVuex", initVuex); /**存初始化的vuex值 */
        // localStorage.removeItem("tokon");
    }
};
</script>

<style lang="less" scoped>
.register-box /deep/ .phone .el-input__inner {
    padding-left: 100px;
}
.register-box /deep/ .el-select {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
    width: 84px;
}
.register-box /deep/ .verification-code {
    width: 190px;
}
.register-box /deep/ .verification-code + .el-button--primary {
    width: 120px;
    padding: 12px 0;
    margin-left: 16px;
    vertical-align: middle;
}
.register-box /deep/ .check-box {
    margin-top: -20px;
    .el-checkbox {
        margin-right: 10px;
    }
    .el-form-item__error {
        margin-top: -20px;
    }
    p {
        display: inline-block;
        color: #747474;
        a {
            color: #3d86e9;
        }
    }
}
.register-box /deep/ .btn-reg {
    margin-top: -20px;
    .el-button--primary {
        width: 100%;
    }
}
.register-box /deep/ .el-select {
    .el-input__inner {
        height: 38px;
        margin: 1px;
        border: none;
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        border-right: 1px solid #dcdfe6;
        box-sizing: border-box;
    }
}
.register-box /deep/ .el-input__inner {
    background: #fcfcfc;
}
.count-down {
    width: 120px;
}
.register-box {
    background: #f7f7f7;
}
.wrap {
    min-height: calc(100vh - 224px);
    margin: 50px 0;
}
section {
    width: 1080px;
    margin: 0 auto;
    background: #fff;
}
.login-form {
    width: 330px;
    margin: 0 auto;
    padding: 30px 0 18px;
    text-align: left;
    h1 {
        font-size: 28px;
        font-weight: normal;
        color: #3d86e9;
    }
    p {
        margin: 10px 0;
        font-size: 14px;
        color: #a1a1a1;
    }
    .show-password {
        position: absolute;
        top: 50%;
        right: 10px;
        margin-top: -2px;
        width: 24px;
        height: 12px;
        background: url(~assets/images/icon-close-eye.png) no-repeat;
        cursor: pointer;
    }
    .hide-password {
        position: absolute;
        top: 50%;
        right: 10px;
        margin-top: -6px;
        width: 24px;
        height: 12px;
        background: url(~assets/images/icon-open-eye.png) no-repeat;
        cursor: pointer;
    }
}
.phone-select {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
    width: 84px;
}
</style>
