<template>
    <div class="login-from-container" data-1664161475611>
        <div class="login-from-box">
            <div class="login-from">
                <div class="login-title">{{ getTitleText() }}</div>
                <div
                    class="login-sub-title"
                    v-if="loginMethod == 1 || loginMethod == 2"
                >登录之后您可以享受企业服务、税收分析、订阅信息、定制化服务</div>
                <!-- 默认登录 -->
                <div v-if="loginMethod == 1">
                    <el-input
                        placeholder="请输入用户名..."
                        v-model="accountName"
                        class="mb-20"
                        :class="{'is-error':accountNameError}"
                        @focus="clearError('accountNameError')"
                    >
                        <i slot="prefix" class="el-input__icon el-icon-user"></i>
                        <div class="is-error-info" v-if="accountNameError">请输入用户名</div>
                    </el-input>
                    <div class="is-error-info" v-if="accountNameError">请输入用户名...</div>
                    <el-input
                        placeholder="请输入登录密码..."
                        v-model="password"
                        show-password
                        class="mb-20"
                        :class="{'is-error':passwordError}"
                        @focus="clearError('passwordError')"
                    >
                        <i slot="prefix" class="el-input__icon el-icon-lock"></i>
                    </el-input>
                    <div class="is-error-info" v-if="passwordError">请输入登录密码...</div>
                </div>
                <!-- 手机登录 -->
                <div v-if="loginMethod == 2">
                    <el-input placeholder="请输入手机号码..." v-model="mobilePhone" class="mb-20">
                        <i slot="prefix" class="el-input__icon el-icon-mobile-phone"></i>
                    </el-input>
                    <div class="verification-code-row mb-20">
                        <el-input
                            placeholder="请输入图片验证码..."
                            v-model="imgCode"
                            class="fl img-code-input"
                        >
                            <img
                                slot="prefix"
                                src="~@/assets/image/login/verificationCode.png"
                                class="img-code-icon"
                                alt
                            />
                        </el-input>
                        <div class="img-code-box fl" @click="getVerificationCode">
                            <img class="imgCode" :src="imgCodeUrl" alt="验证码" />
                        </div>
                    </div>
                    <div class="verification-code-row mb-20">
                        <el-input
                            placeholder="请输入手机验证码..."
                            v-model="phoneCode"
                            class="fl img-code-input"
                            :class="{'is-error':phoneCodeError}"
                            @focus="clearError('phoneCodeError')"
                        >
                            <img
                                slot="prefix"
                                src="~@/assets/image/login/numCodeIcon.png"
                                class="img-code-icon-num"
                                alt
                            />
                        </el-input>
                        <div class="img-code-box get-code fl">
                            <el-button :disabled="true" v-if="phoneCodeDisable">{{ word }}</el-button>
                            <el-button v-else @click="getPhoneCode">{{ word }}</el-button>
                        </div>
                        <div
                            class="is-error-info"
                            style="margin-top:0"
                            v-if="phoneCodeError"
                        >请输入手机验证码</div>
                    </div>
                </div>
                <!-- 注册 || 忘记密码 -->
                <div v-if="loginMethod == 3 || loginMethod == 4">
                    <el-input
                        placeholder="请输入手机号码..."
                        v-model="mobilePhone"
                        class="mb-20"
                        :class="{'is-error':mobilePhoneError}"
                        @focus="clearError('mobilePhoneError')"
                    >
                        <i slot="prefix" class="el-input__icon el-icon-mobile-phone"></i>
                    </el-input>
                    <div
                        class="is-error-info"
                        v-if="mobilePhoneError"
                    >{{ mobilePhone ? '请输入正确的手机号码':'请输入手机号码' }}</div>
                    <el-input
                        placeholder="请输入用户名..."
                        v-model="accountName"
                        class="mb-20"
                        :class="{'is-error':accountNameError}"
                        @focus="clearError('accountNameError')"
                        v-if="loginMethod == 3"
                    >
                        <i slot="prefix" class="el-input__icon el-icon-user"></i>
                    </el-input>
                    <div class="is-error-info" v-if="accountNameError && loginMethod == 3">请输入用户名</div>
                    <form>
                        <el-input
                            placeholder="请输入新密码..."
                            v-model="newPassword"
                            show-password
                            class="mb-20"
                            :class="{'is-error':newPasswordError}"
                            @focus="clearError('newPasswordError')"
                        >
                            <i slot="prefix" class="el-input__icon el-icon-lock"></i>
                        </el-input>
                    </form>

                    <div class="is-error-info" v-if="newPasswordError">请输入新密码</div>
                    <form>
                        <el-input
                            placeholder="请再次输入新密码..."
                            v-model="confirmPassword"
                            show-password
                            class="mb-20"
                            :class="{'is-error':confirmPasswordError}"
                            @focus="clearError('confirmPasswordError')"
                        >
                            <i slot="prefix" class="el-input__icon el-icon-lock"></i>
                        </el-input>
                    </form>

                    <div class="is-error-info" v-if="confirmPasswordError">请输入新密码</div>
                    <div class="verification-code-row mb-20">
                        <el-input
                            placeholder="请输入图片验证码..."
                            v-model="imgCode"
                            class="fl img-code-input"
                            :class="{'is-error':imgCodeError}"
                            @focus="clearError('imgCodeError')"
                        >
                            <img
                                slot="prefix"
                                src="~@/assets/image/login/verificationCode.png"
                                class="img-code-icon"
                                alt
                            />
                        </el-input>
                        <div class="img-code-box fl" @click="getVerificationCode">
                            <img class="imgCode" :src="imgCodeUrl" alt="验证码" />
                        </div>
                        <div class="is-error-info" style="margin-top:0" v-if="imgCodeError">请输入图片验证码</div>
                    </div>
                    <div class="verification-code-row mb-20">
                        <el-input
                            placeholder="请输入手机验证码..."
                            v-model="phoneCode"
                            class="fl img-code-input"
                            :class="{'is-error':phoneCodeError}"
                            @focus="clearError('phoneCodeError')"
                        >
                            <img
                                slot="prefix"
                                src="~@/assets/image/login/numCodeIcon.png"
                                class="img-code-icon-num"
                                alt
                            />
                        </el-input>
                        <div class="img-code-box get-code fl">
                            <el-button :disabled="true" v-if="phoneCodeDisable">{{ word }}</el-button>
                            <el-button v-else @click="getPhoneCode">{{ word }}</el-button>
                        </div>
                        <div
                            class="is-error-info"
                            style="margin-top:0"
                            v-if="phoneCodeError"
                        >请输入手机验证码</div>
                    </div>
                </div>
                <div class="remember-row mb-20" v-if="loginMethod == 1 || loginMethod == 2">
                    <div class="remember-password fl" v-if="loginMethod == 1">
                        <el-checkbox v-model="isRemember">记住密码</el-checkbox>
                    </div>
                    <span class="forgot-password fr pointer" @click="loginMethodChange(4)">忘记密码?</span>
                </div>
                <!-- 登录按钮 -->
                <div class="login-btn">
                    <el-button
                        type="primary"
                        v-if="loginLoading"
                        :loading="true"
                        disabled
                    >{{ loginLoadingText }}</el-button>
                    <el-button
                        type="primary"
                        v-else
                        @click="submitLoginInfo"
                    >{{ getLoginBtnText() }}</el-button>
                </div>
                <div class="other-login" v-if="loginMethod == 1 || loginMethod == 2">
                    <span
                        class="fl pointer"
                        v-if="loginMethod == 1"
                        @click="loginMethodChange(2)"
                    >手机验证码登录</span>
                    <span
                        class="fl pointer"
                        v-if="loginMethod == 2"
                        @click="loginMethodChange(1)"
                    >账号密码登录</span>
                    <span class="fr pointer">
                        你还没有账户?
                        <span class="reg-span" @click="loginMethodChange(3)">立即注册 ></span>
                    </span>
                </div>
                <div class="other-login" v-else>
                    <span class="fr pointer">
                        已经拥有账户?
                        <span class="reg-span" @click="loginMethodChange(1)">立即登录 ></span>
                    </span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import "./LoginFrom.scss";
import {
    accountLogin,
    getMobilePhoneCode,
    accountRegister,
    mobilePhoneLogin,
    forgetPassword,
} from "../../../api/login";
// 密码加密
import Utils from "@/utils/encrypt";
// 引入工具方法
import { sendMsg } from "@/utils/common";
// 导入cookie操作
import { setCookie, getCookie, delCookie } from "@/utils/cookie-util";
export default {
    data() {
        return {
            // 登录loading
            loginLoading: false,
            loginLoadingText: "",
            /**
             *
             * 登录方式
             * 1 默认登录
             * 2 手机号登录
             * 3 注册
             * 4 忘记密码
             *
             */
            loginMethod: 1,
            // 用户名
            accountName: "",
            accountNameError: false,
            // 登录密码
            password: "",
            passwordError: false,
            // 手机号码
            mobilePhone: "",
            mobilePhoneError: false,
            // 图片验证码
            imgCode: "",
            imgCodeUrl: "",
            imgCodeError: false,
            // 手机验证码
            phoneCode: "",
            phoneCodeError: false,
            // 新密码
            newPassword: "",
            newPasswordError: false,
            // 确认密码
            confirmPassword: "",
            confirmPasswordError: false,
            // 记住密码
            isRemember: false,
            // 加密码
            encrypt: "hAw6eqnFLKxpsDv3",
            // 获取手机验证密码倒计时
            sendTimer: null,
            word: "获取验证码", // 手机短信验证码文字
            isOvertime: false, // 手机短信验证时间判断
            phoneCodeDisable: false, // 手机短信验证码按钮禁用开启
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        //
        init() {
            // 获取图片验证码
            this.getVerificationCode();
            // 账号回显
            this.accountName = getCookie("accountName");
            // 手机号回显
            this.mobilePhone = getCookie("mobilePhone");
            // 如果有密码记录
            if (getCookie("password")) {
                this.password = Utils.decrypt(
                    getCookie("password"),
                    this.encrypt
                );
                this.isRemember = true;
            }
        },
        // 获取图片验证码
        getVerificationCode() {
            this.imgCodeUrl =
                process.env.VUE_APP_BASE_API +
                "/verificationCode/img?height=40&width=84&fontSize=25" +
                "&n=" +
                parseInt(Math.random() * 9999 + 1);
        },
        // 获取手机验证码
        getPhoneCode() {
            let { imgCode, mobilePhone } = this;
            if (this.checkIsAllow(["mobilePhone", "imgCode"])) {
                this.phoneCodeDisable = true;
                getMobilePhoneCode(mobilePhone.trim(), imgCode.trim())
                    .then((res) => {
                        if (res.data.status == 0) {
                            if (this.isOvertime) {
                                return false;
                            }
                            let time = 60;
                            this.sendTimer = setInterval(() => {
                                this.isOvertime = true;
                                time--;
                                this.word = "已发送" + time + "秒";
                                console.log(`测试定时器`);
                                if (time <= 0) {
                                    this.isOvertime = false;
                                    clearInterval(this.sendTimer);
                                    this.word = "发送验证码";
                                    this.phoneCodeDisable = false;
                                }
                            }, 1000);
                            this.$router.push("/");
                            console.log("跳转到首页");
                        } else {
                            sendMsg(0, res.data.msg);
                            this.phoneCodeDisable = false;
                        }
                    })
                    .catch((err) => {
                        sendMsg(0, "获取验证码失败");
                        console.log(err);
                        this.phoneCodeDisable = false;
                    });
            }
        },
        // 登录界面切换
        loginMethodChange(status) {
            this.loginMethod = status;
            this.clearAllError();
        },
        // 获取title
        getTitleText() {
            let { loginMethod } = this;
            return loginMethod == 1 || loginMethod == 2
                ? "松江经济技术开发区（小昆山分区）"
                : loginMethod == 3
                ? "注册"
                : "忘记密码";
        },
        // 获取登录按钮文本
        getLoginBtnText() {
            let { loginMethod } = this;
            return loginMethod == 1 || loginMethod == 2
                ? "登录"
                : loginMethod == 3
                ? "注册"
                : "修改密码";
        },
        // 提交登录信息
        submitLoginInfo() {
            // 登录方式
            let { loginMethod } = this;
            // 检测字段
            let checkKeyList = [];
            // 账号密码登录
            if (loginMethod == 1) {
                checkKeyList = ["accountName", "password"];
            }
            // 手机登录
            if (loginMethod == 2) {
                checkKeyList = ["mobilePhone", "imgCode", "phoneCode"];
            }
            // 注册
            if (loginMethod == 3) {
                checkKeyList = [
                    "mobilePhone",
                    "accountName",
                    "newPassword",
                    "confirmPassword",
                    "imgCode",
                    "phoneCode",
                ];
            }
            // 忘记密码
            if (loginMethod == 4) {
                checkKeyList = [
                    "mobilePhone",
                    "newPassword",
                    "confirmPassword",
                    "imgCode",
                    "phoneCode",
                ];
            }
            // 效验不通过
            if (!this.checkIsAllow(checkKeyList)) {
                return;
            }
            // 默认登录
            if (loginMethod == 1) {
                this.accountLogin();
            }
            // 手机号登录
            if (loginMethod == 2) {
                this.mobilePhoneLogin();
            }
            // 注册账号
            if (loginMethod == 3) {
                this.accountRegister();
            }
            // 忘记密码
            if (loginMethod == 4) {
                this.forgetPassword();
            }
        },
        // 忘记密码 --- 修改密码
        forgetPassword() {
            let { mobilePhone, newPassword, imgCode, phoneCode } = this;
            let param = {
                mobilePhone,
                newPassword,
                imgCode,
                smsVerificationCode: phoneCode,
            };
            this.loginLoading = true;
            this.loginLoadingText = "修改中...";

            forgetPassword(param)
                .then((res) => {
                    const data = res.data;
                    if (data.status == 0) {
                        sendMsg(1, "修改成功");
                        // 保存用户名
                        setCookie("accountName", accountName.trim());
                        this.loginMethodChange(1);
                    } else {
                        sendMsg(0, data.msg);
                    }
                    this.loginLoading = false;
                })
                .catch((err) => {
                    sendMsg(0, "修改失败");
                    console.log(err);
                    this.loginLoading = false;
                });
        },
        // 手机号登录
        mobilePhoneLogin() {
            let { mobilePhone, imgCode, phoneCode } = this;
            this.loginLoading = true;
            this.loginLoadingText = "登录中...";
            mobilePhoneLogin(mobilePhone, imgCode, phoneCode)
                .then((res) => {
                    const data = res.data;
                    if (data.status == 0) {
                        sendMsg(1, "登录成功");
                        // 保存用户名
                        setCookie("mobilePhone", mobilePhone.trim());
                        this.loginSuccessFn();
                    } else {
                        sendMsg(0, data.msg);
                    }
                    this.loginLoading = false;
                })
                .catch((err) => {
                    sendMsg(0, "登录失败");
                    console.log(err);
                    this.loginLoading = false;
                });
        },
        // 注册账号
        accountRegister() {
            let {
                mobilePhone,
                accountName,
                newPassword,
                confirmPassword,
                imgCode,
                phoneCode,
            } = this;
            let param = {
                mobilePhone,
                accountName,
                password: newPassword,
                confirmPassword,
                imgCode,
                smsVerificationCode: phoneCode,
            };
            this.loginLoading = true;
            this.loginLoadingText = "注册中...";
            accountRegister(param)
                .then((res) => {
                    const data = res.data;
                    if (data.status == 0) {
                        sendMsg(1, "注册成功");
                        // 保存用户名
                        setCookie("accountName", accountName.trim());
                        this.loginSuccessFn();
                    } else {
                        sendMsg(0, data.msg);
                    }
                    this.loginLoading = false;
                })
                .catch((err) => {
                    sendMsg(0, "注册失败");
                    console.log(err);
                    this.loginLoading = false;
                });
        },
        // 默认登录
        accountLogin() {
            let { isRemember, encrypt, accountName, password } = this;
            this.loginLoading = true;
            this.loginLoadingText = "登录中...";
            accountLogin(accountName.trim(), password.trim())
                .then((res) => {
                    const data = res.data;
                    if (data.status == 0) {
                        sendMsg(1, "登录成功");
                        // 保存用户名
                        setCookie("accountName", accountName.trim());
                        // 判断是否勾选记住密码
                        if (isRemember) {
                            let encryptPwd = Utils.encrypt(
                                password.trim(),
                                encrypt
                            );
                            setCookie("password", encryptPwd, 7);
                        } else {
                            delCookie("password");
                        }
                        this.loginSuccessFn();
                    } else {
                        sendMsg(0, data.msg);
                    }
                    this.loginLoading = false;
                })
                .catch((err) => {
                    sendMsg(0, "登录失败");
                    console.log(err);
                    this.loginLoading = false;
                });
        },
        // 登录成功后的响应
        loginSuccessFn() {
            let getLoginFrom = localStorage.getItem("loginFrom") || "/";
            this.$router.push(getLoginFrom);
            this.$store.dispatch('getUserInfo');
        },
        // 检测是否通过
        checkIsAllow(checkKeyList) {
            let isAllow = true;
            checkKeyList.forEach((el) => {
                if (!this.checkKey(this[el], el + "Error")) {
                    isAllow = false;
                }
            });
            return isAllow;
        },
        // 检测字段
        checkKey(val, key) {
            let flag = true;
            if (!val || !val.trim()) {
                this[key] = true;
                flag = false;
            }
            if (
                key == "mobilePhoneError" &&
                !/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(val)
            ) {
                this[key] = true;
                flag = false;
            }
            return flag;
        },
        // 清楚错误
        clearError(key) {
            this[key] = false;
        },
        // 清除所有错误
        clearAllError() {
            this.accountNameError = false;
            this.passwordError = false;
            this.newPasswordError = false;
            this.confirmPasswordError = false;
            this.imgCodeError = false;
            this.phoneCodeError = false;
            this.mobilePhoneError = false;
        },
    },
    destroyed() {
        clearInterval(this.sendTimer);
        this.sendTimer = null;
    },
};
</script>
