<template>
    <div id="login">
        <div class="login-wrapper">
            <div class="login-container">
                <div class="login-brand">
                    <img src="~@/assets/img/logo.png" />
                </div>
                <div class="login-box">
                    <el-form
                        class="login-form"
                        :model="form"
                        @submit.native.prevent="verify"
                        label-position="top"
                        v-loading="loading"
                        element-loading-text="Login"
                        element-loading-background="rgba(255, 255, 255, 0.7)"
                    >
                        <el-form-item class="tip">{{
                            $t("login.step")
                        }}</el-form-item>
                        <el-form-item :label="$t('login.username')">
                            <el-input
                                v-model.trim="form.username"
                                auto-complete="off"
                            />
                        </el-form-item>
                        <el-form-item :label="$t('login.password')">
                            <el-input
                                v-model="form.password"
                                auto-complete="off"
                                type="password"
                                show-password
                            />
                        </el-form-item>
                        <el-form-item label=" ">
                            <el-input
                                class="submit"
                                type="submit"
                                :value="$t('login.submit')"
                            />
                        </el-form-item>
                    </el-form>
                    <div class="languageSelect-container"></div>
                    <div style="display: flex; justify-content: space-between">
                        <el-link
                            type="primary"
                            :underline="false"
                            v-on:click="forgotPasswordShow"
                            >忘记密码</el-link
                        >
                        <el-link
                            type="primary"
                            :underline="false"
                            v-on:click="operationFileDownload"
                            >操作手册下载</el-link
                        >
                    </div>
                    <el-dialog
                        title="忘记密码"
                        :visible.sync="isForgotPasswordShow"
                        v-on:close="forgotPasswordClose('ruleForm')"
                    >
                        <el-form
                            :model="ruleForm"
                            status-icon
                            :rules="rules"
                            ref="ruleForm"
                            label-width="100px"
                            class="demo-ruleForm"
                        >
                            <el-form-item label="手机号码" prop="phone">
                                <el-input
                                    class="forgot_password_input"
                                    type="tel"
                                    v-model="ruleForm.phone"
                                    autocomplete="off"
                                ></el-input>
                                <el-button
                                    style="margin-left: 5px"
                                    type="primary"
                                    v-on:click="sendVerificationCode"
                                    :disabled="isDisabled"
                                    >{{ content }}
                                </el-button>
                            </el-form-item>
                            <el-form-item label="验证码" prop="code">
                                <el-input
                                    class="forgot_password_input"
                                    type="text"
                                    v-model="ruleForm.code"
                                    autocomplete="off"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="密码" prop="pass">
                                <el-input
                                    class="forgot_password_input"
                                    type="password"
                                    v-model="ruleForm.pass"
                                    autocomplete="off"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="确认密码" prop="checkPass">
                                <el-input
                                    class="forgot_password_input"
                                    type="password"
                                    v-model="ruleForm.checkPass"
                                    autocomplete="off"
                                ></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button
                                    type="primary"
                                    v-on:click="changePassword('ruleForm')"
                                    >修改</el-button
                                >
                                <el-button
                                    type="primary"
                                    v-on:click="
                                        cancelChangePassword('ruleForm')
                                    "
                                    >取消</el-button
                                >
                            </el-form-item>
                        </el-form>
                    </el-dialog>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { AxiosRequestData } from "../../data/axios_request";
import cache from "@/utils/cache";
import { networkUrl } from "../../data/global_configuration";

export default {
    name: "login",
    // components: {LanguageSelect},
    data() {
        let checkPhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("手机号码不能为空！"));
            }
            if (!/^1[3456789]\d{9}$/.test(value)) {
                callback(new Error("手机号码有误，请重填！"));
            } else {
                callback();
            }
        };
        let checkCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("验证码不能为空！"));
            } else {
                callback();
            }
        };
        let validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else {
                if (this.ruleForm.checkPass !== "") {
                    this.$refs.ruleForm.validateField("checkPass");
                }
                callback();
            }
        };
        let validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.ruleForm.pass) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };

        return {
            form: {
                username: "",
                password: "",
            },
            loading: false,
            isForgotPasswordShow: false,
            ruleForm: {
                phone: "",
                code: "",
                pass: "",
                checkPass: "",
            },
            rules: {
                phone: [{ validator: checkPhone, trigger: "blur" }],
                code: [{ validator: checkCode, trigger: "blur" }],
                pass: [{ validator: validatePass, trigger: "blur" }],
                checkPass: [{ validator: validatePass2, trigger: "blur" }],
            },
            isDisabled: false, // 控制按钮是否可以点击（false:可以点击，true:不可点击）
            content: "获取短信验证码", // 发送验证码按钮的初始显示文字
            timer: null,
            count: "",
        };
    },
    methods: {
        verify() {
            let usernameMsg = this.$t("login.usernameMsg");
            let passwordMsg = this.$t("login.passwordMsg");
            if (!this.form.username) {
                this.$message.error(usernameMsg);
            } else if (!this.form.password) {
                this.$message.error(passwordMsg);
            } else {
                this.signIn();
            }
        },
        login() {
            this.loading = true;
            let successMsg = this.$t("login.successMsg");
            let errorMsg = this.$t("login.errorMsg");
            this.$store
                .dispatch("login/getLoginToken", this.form)
                .then((res) => {
                    this.$route.query.redirect
                        ? this.$router.push(this.$route.query.redirect)
                        : this.$router.push("/index");
                    this.$message.success(successMsg);
                    this.loading = false;
                })
                .catch(() => {
                    this.$message.error(errorMsg);
                    this.loading = false;
                });
        },
        // 提交登录信息
        async signIn() {
            // let username = this.form.username;
            // let password = this.form.password;
            // const url = "/login";
            // let token = null;
            // let response = await AxiosRequestData(
            //     url,
            //     token,
            //     {
            //         account: username,
            //         password: password,
            //         reqChannel: 4,
            //         loginType: 1,
            //     },
            //     false,
            //     1
            // );
            // if (response) {
            //     if (response.code == 0) {
            //         window.localStorage.setItem(token, response.data.token);
            //         let authority = JSON.stringify(response.data.authorities);
            //         this.loading = true;
            //         let successMsg = this.$t("login.successMsg");
            //         let errorMsg = this.$t("login.errorMsg");
            //         // this.getDefaultCompany(username, response.data.token)
            //         this.callGetISPInfo(username, response.data.token);
            //         this.$store
            //             .dispatch("login/getLoginToken", this.form)
            //             .then((res) => {
            //                 this.$route.query.redirect
            //                     ? this.$router.push("/login")
            //                     : this.$router.push("/index");
            //                 this.$message.success(successMsg);
            //                 this.loading = false;
            //             })
            //             .catch(() => {
            //                 this.$message.error(errorMsg);
            //                 this.loading = false;
            //             });
            //     } else {
            //         this.$message.error(response.msg);
            //     }
            // } else {
            //     this.$message.error(response.msg);
            // }

            let username = this.form.username;
            this.loading = true;
            let successMsg = this.$t("login.successMsg");
            let errorMsg = this.$t("login.errorMsg");
            this.$store
                .dispatch("login/getLoginToken", this.form)
                .then((res) => {
                    this.callGetISPInfo(username, res.data.token);
                    this.$route.query.redirect
                        ? this.$router.push("/login")
                        : this.$router.push("/index");
                    this.$message.success(successMsg);
                    this.loading = false;
                })
                .catch(() => {
                    this.$message.error(errorMsg);
                    this.loading = false;
                });
        },
        // 忘记密码
        forgotPasswordShow() {
            this.isForgotPasswordShow = true;
        },
        //操作手册下载
        operationFileDownload() {
            let url = networkUrl();
            window.location.href =
                url +
                "/ext/%E4%BA%91%E5%BC%80%E7%A5%A8%E7%BD%91%E9%A1%B5%E7%89%88%E6%93%8D%E4%BD%9C%E8%AF%B4%E6%98%8E.docx";
        },
        //发送验证码
        async sendVerificationCode() {
            if (!this.ruleForm.phone || this.ruleForm.phone == "") {
                this.$message({
                    message: "请输入手机号",
                    type: "warning",
                });
                return;
            }
            if (!/^1[34578]\d{9}$/.test(this.ruleForm.phone)) {
                this.$message({
                    message: "请输入正确的手机号",
                    type: "warning",
                });
                return;
            }
            const url = "/sms/getSmscode";
            let token = null;
            let response = await AxiosRequestData(
                url,
                token,
                {
                    phoneNo: this.ruleForm.phone,
                },
                false,
                1
            );
            if (response) {
                if (response.code == 0) {
                    this.$message({
                        message: "验证码发送成功！",
                        type: "success",
                    });
                    this.sendCode();
                } else {
                    this.$message.error("验证码发送失败！");
                }
            } else {
                this.$message.error("验证码发送失败！");
            }
        },
        // 发送验证码
        sendCode() {
            // 控制倒计时及按钮是否可以点击
            const TIME_COUNT = 60;
            this.count = TIME_COUNT;
            this.timer = window.setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                    // 倒计时时不可点击
                    this.isDisabled = true;
                    // 计时秒数
                    this.count--;
                    // 更新按钮的文字内容
                    this.content = this.count + "s后重新获取";
                } else {
                    // 倒计时完，可点击
                    this.isDisabled = false;
                    // 更新按钮文字内容
                    this.content = "获取短信验证码";
                    // 清空定时器!!!
                    clearInterval(this.timer);
                    this.timer = null;
                }
            }, 1000);
        },
        //修改用户密码
        changePassword(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitChangePassword();
                } else {
                    return false;
                }
            });
        },
        //提交密码修改
        async submitChangePassword() {
            if (this.ruleForm.phone) {
                const url = "/auth/comm/user/forgotpwd";
                let response = await AxiosRequestData(
                    url,
                    null,
                    {
                        mobile: this.ruleForm.phone,
                        password: this.ruleForm.pass,
                        confirmPassword: this.ruleForm.checkPass,
                        smsCode: this.ruleForm.code,
                        reqChannel: 4,
                    },
                    false,
                    1
                );
                if (response) {
                    if (response.code == 0) {
                        this.$message({
                            message: "密码修改成功！",
                            type: "success",
                        });
                        // this.$emit('update:visible', false)
                    } else {
                        this.$message.error("密码修改失败！");
                    }
                }
            }
        },
        //取消密码修改
        cancelChangePassword(formName) {
            this.isForgotPasswordShow = false;
            this.$refs[formName].resetFields();
            this.isDisabled = false;
            this.content = "获取短信验证码";
            this.timer = null;
            this.count = "";
        },
        //忘记密码页面关闭
        forgotPasswordClose(formName) {
            this.$refs[formName].resetFields();
            this.isDisabled = false;
            this.content = "获取短信验证码";
            this.timer = null;
            this.count = "";
        },
        //获取默认企业信息
        async getDefaultCompany(account, token) {
            if (account && token) {
                const url = "/auth/comm/user/findDefaultChoose";
                let response = await AxiosRequestData(
                    url,
                    token,
                    {
                        mobile: account,
                    },
                    false,
                    2
                ).then((res) => {
                    if (res.code == 0) {
                        this.companyName = res.data.entName;
                        cache.setLocal("company", res.data);
                    }
                });
            }
        },
        //获取服务商信息
        async callGetISPInfo(account, token) {
            cache.removeLocal("ISP");
            if (account && token) {
                const url = "/auth/isp/info/findByMobile";
                let response = await AxiosRequestData(
                    url,
                    token,
                    {
                        mobile: account,
                    },
                    false,
                    2
                ).then((res) => {
                    if (res.code == 0) {
                        this.companyName = res.data.entName;
                        cache.setLocal("ISP", res.data);
                        console.log("服务商信息：");
                        console.log(res.data);
                    }
                });
            }
        },
    },
};
</script>
<style lang='stylus'>
$loginPrimary = #304352;
$loginPrimaryRGB = 48, 67, 82;
$loginGrey = rgba($loginPrimaryRGB, 0.06);
$loginDark = rgba($loginPrimaryRGB, 0.5);

#login {
    position: relative;
    width: 100%;
    min-height: 100vh;
    background: rgba($loginPrimary, 0.4);
    background-image: linear-gradient(to bottom, #d7d2cc 0%, #304352 100%);

    .login-wrapper {
        width: 360px;
        padding: 150px 0;
        margin: 0 auto;

        .login-container {
            position: relative;

            .login-brand {
                position: relative;
                width: 100px;
                height: 100px;
                margin: 0 auto -50px auto;
                border-radius: 50%;
                box-shadow: 0 4px 40px rgba(0, 0, 0, 0.07);
                padding: 10px;
                background-color: #fff;
                z-index: 1;
                overflow: hidden;

                img {
                    width: 100%;
                }
            }

            .login-box {
                position: relative;
                width: 100%;
                height: 100%;
                background-color: #fff;
                box-shadow: 0 7px 25px rgba(0, 0, 0, 0.08);
                padding: 60px 25px 25px 25px;
                border-radius: 3px;

                .login-form {
                    .tip {
                        color: $loginDark;
                        text-align: center;
                        font-weight: 700;
                        margin-top: 10px;
                    }

                    .el-form-item__label {
                        color: $loginDark;
                        font-weight: 700;
                        padding: 0;
                    }

                    .el-input__inner {
                        height: 45px;
                        line-height: 45px;
                        background: $loginGrey;
                        border: none;
                    }

                    .submit {
                        cursor: pointer;

                        input {
                            width: 100%;
                            color: #fff;
                            border-radius: 3px;
                            background-color: $loginPrimary;
                            box-shadow: 0 2px 7px $loginDark;
                            font-weight: 700;
                            cursor: pointer;
                            border: none;
                            outline: 0;
                            transition: all 0.3s;
                        }

                        &:hover {
                            input {
                                opacity: 0.8;
                            }
                        }
                    }
                }

                .languageSelect-container {
                    position: absolute;
                    right: 15px;
                    top: 15px;

                    .languageSelect {
                        .el-dropdown-selfdefine {
                            color: $loginPrimary;
                            font-size: 16px;
                            padding: 5px 8px;
                            cursor: pointer;
                        }
                    }
                }
            }

            &:after {
                content: ' ';
                position: absolute;
                top: 100%;
                left: 50%;
                width: 88%;
                height: 5px;
                transform: translateX(-50%);
                background-color: #f0f0f0;
                border-radius: 0 0 3px 3px;
            }
        }
    }
}

.forgot_password_input {
    width: 250px;
    /* margin: 5px; */
}
</style>
