<template>
    <div class="login">
        <div class="login-bar">
            <div class="form-bar">
                <h3 class="title">智慧仓储管理平台</h3>
                <el-tabs
                    v-model="activeName"
                    style="width: 400px; padding: 25px 25px 5px 25px"
                >
                    <el-tab-pane label="账号登录" name="account">
                        <!-- 账户密码登录 -->
                        <el-form
                            ref="loginForm"
                            :model="loginForm"
                            :rules="loginRules"
                            class="login-form"
                            v-if="activeName === 'account'"
                        >
                            <el-form-item prop="username">
                                <el-input
                                    v-model="loginForm.username"
                                    type="text"
                                    auto-complete="off"
                                    placeholder="账号"
                                >
                                    <svg-icon
                                        slot="prefix"
                                        icon-class="user"
                                        class="el-input__icon input-icon"
                                    />
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input
                                    v-model="loginForm.password"
                                    type="password"
                                    auto-complete="off"
                                    placeholder="密码"
                                    show-password
                                    @keyup.enter.native="handleLogin"
                                >
                                    <svg-icon
                                        slot="prefix"
                                        icon-class="password"
                                        class="el-input__icon input-icon"
                                    />
                                </el-input>
                            </el-form-item>

                            <!-- 5.29 新增双因子验证 -->
                            <el-form-item
                                prop="textCode"
                                class="code-container"
                                v-if="loginForm.username === 'adminBns'"
                            >
                                <el-input
                                    v-model="loginForm.textCode"
                                    placeholder="短信验证码"
                                    style="width: 67%"
                                >
                                    <svg-icon
                                        slot="prefix"
                                        icon-class="validCode"
                                        class="el-input__icon input-icon"
                                    />
                                </el-input>
                                <div class="login-code">
                                    <div
                                        class="login-code-img"
                                        style="
                                            border: 1px solid rgb(220, 223, 230);
                                        "
                                        v-if="showNew === 1"
                                        @click="getTextCodeNew"
                                    >
                                        获取验证码
                                    </div>
                                    <div
                                        class="login-code-img"
                                        style="
                                            border: 1px solid rgb(220, 223, 230);
                                        "
                                        v-show="showNew === 2"
                                    >
                                        {{ countNew }} s
                                    </div>
                                    <div
                                        class="login-code-img"
                                        style="
                                            border: 1px solid rgb(220, 223, 230);
                                        "
                                        v-if="showNew === 3"
                                        @click="getTextCodeNew"
                                    >
                                        重发
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item
                                prop="code"
                                v-if="captchaEnabled"
                                class="code-container"
                            >
                                <el-input
                                    v-model="loginForm.code"
                                    auto-complete="off"
                                    placeholder="图形验证码"
                                    @keyup.enter.native="handleLogin"
                                >
                                    <svg-icon
                                        slot="prefix"
                                        icon-class="validCode"
                                        class="el-input__icon input-icon"
                                    />
                                </el-input>
                                <div class="login-code">
                                    <img
                                        :src="codeUrl"
                                        @click="getCode(1)"
                                        class="login-code-img"
                                    />
                                </div>
                            </el-form-item>
                            <el-form-item style="width: 100%">
                                <el-button
                                    :loading="loading"
                                    size="medium"
                                    type="primary"
                                    style="width: 100%"
                                    @click.native.prevent="handleLogin"
                                >
                                    <span v-if="!loading">登 录</span>
                                    <span v-else>登 录 中...</span>
                                </el-button>
                                <div style="float: right" v-if="register">
                                    <!--          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>-->
                                    <router-link class="link-type" :to="'/ '"
                                        >立即注册</router-link
                                    >
                                </div>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="手机登录" name="phone">
                        <!-- 手机验证码登录 -->
                        <el-form
                            ref="phoneLoginFormRef"
                            :model="phoneLoginParams"
                            :rules="phoneLoginRules"
                            class="login-form"
                            v-if="activeName === 'phone'"
                        >
                            <el-form-item prop="phone">
                                <el-input
                                    v-model="phoneLoginParams.phone"
                                    :readonly="readonlyFlag"
                                    @focus="handleInputClick"
                                    placeholder="手机号"
                                >
                                    <svg-icon
                                        slot="prefix"
                                        icon-class="phone"
                                        class="el-input__icon input-icon"
                                    />
                                </el-input>
                            </el-form-item>
                            <el-form-item
                                prop="textCode"
                                class="code-container"
                            >
                                <el-input
                                    v-model="phoneLoginParams.textCode"
                                    placeholder="短信验证码"
                                    style="width: 63%"
                                    @focus="handleInputClick"
                                    @input="inputChangeTextCode"
                                >
                                    <svg-icon
                                        slot="prefix"
                                        icon-class="validCode"
                                        class="el-input__icon input-icon"
                                    />
                                </el-input>
                                <div class="login-code">
                                    <!-- <div class="login-code-img" style="border: 1px solid rgb(220, 223, 230);" @click="getTextCode">获取验证码</div> -->
                                    <div
                                        class="login-code-img"
                                        style="
                                            border: 1px solid rgb(220, 223, 230);
                                        "
                                        v-show="show === 1"
                                        @click.prevent="getTextCode"
                                    >
                                        获取验证码
                                    </div>
                                    <div
                                        class="login-code-img"
                                        style="
                                            border: 1px solid rgb(220, 223, 230);
                                        "
                                        v-if="show === 2"
                                    >
                                        {{ count }} s
                                    </div>
                                    <div
                                        class="login-code-img"
                                        style="
                                            border: 1px solid rgb(220, 223, 230);
                                        "
                                        v-if="show === 3"
                                        @click.prevent="getTextCode"
                                    >
                                        重发
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item style="width: 100%">
                                <el-button
                                    :loading="loading"
                                    size="medium"
                                    type="primary"
                                    style="width: 100%"
                                    @click.native.prevent="textLogin"
                                >
                                    <span v-if="!loading">登 录</span>
                                    <span v-else>登 录 中...</span>
                                </el-button>
                                <!-- 5.27 隐藏注册页面 -->
                                <!--     <div style="float: right" v-if="register"> -->
                                <!--     <router-link class="link-type" :to="'/register'">立即注册</router-link> -->
                                <!--     </div> -->
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <!--        底部  -->
        <!--       <div class="el-login-footer"> -->
        <!--       <span>Copyright © 2018-2023 ruoyi.vip All Rights Reserved.</span> -->
        <!--       </div> -->

        <!-- 图形验证码弹框 -->
        <el-dialog
            title="请输入图形验证码"
            :visible.sync="dialogCodeVisible"
            v-if="dialogCodeVisible"
            width="30%"
            :before-close="handleClose"
        >
            <el-form
                ref="phoneLoginCodeFormRef"
                :model="phoneLoginParams"
                :rules="phoneLoginCodeRules"
            >
                <el-form-item
                    prop="code"
                    v-if="captchaEnabled"
                    class="code-container"
                >
                    <el-input
                        v-model="phoneLoginParams.code"
                        auto-complete="off"
                        placeholder="图形验证码"
                        @keyup.enter.native="textLogin"
                        style="width: 70%"
                    >
                        <svg-icon
                            slot="prefix"
                            icon-class="validCode"
                            class="el-input__icon input-icon"
                        />
                    </el-input>
                    <div class="login-code">
                        <img
                            :src="phoneCodeUrl"
                            @click="getCode(2)"
                            class="login-code-img"
                            style="width: 100%"
                        />
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSendCode()"
                    >确 定</el-button
                >
            </span>
        </el-dialog>

        <!-- 图形验证码弹框 2 -->
        <el-dialog
            title="请输入图形验证码"
            :visible.sync="dialogCodeVisibleNew"
            v-if="dialogCodeVisibleNew"
            width="30%"
            :before-close="handleCloseNew"
        >
            <el-form
                ref="phoneLoginCodeFormNewRef"
                :model="phoneLoginParamsNew"
                :rules="phoneLoginCodeNewRules"
            >
                <el-form-item
                    prop="code"
                    v-if="captchaEnabled"
                    class="code-container"
                >
                    <el-input
                        v-model="phoneLoginParamsNew.code"
                        auto-complete="off"
                        placeholder="图形验证码"
                        @keyup.enter.native="textLogin"
                        style="width: 70%"
                    >
                        <svg-icon
                            slot="prefix"
                            icon-class="validCode"
                            class="el-input__icon input-icon"
                        />
                    </el-input>
                    <div class="login-code">
                        <img
                            :src="phoneCodeUrlNew"
                            @click="getCode(3)"
                            class="login-code-img"
                            style="width: 100%"
                        />
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSendCodeNew()"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getCodeImg, sendCode, sendCodeNew } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
    name: 'Login',
    data() {
        return {
            codeUrl: '', // 账号登录显示的验证码
            phoneCodeUrl: '', // 手机验证码登录显示的验证码
            loginForm: {
                username: '',
                password: '',
                rememberMe: false,
                code: '', // 账户密码登录时的图片验证码
                uuid: '',
                textCode: '',
            },

            /* 手机号码登录时参数 */
            phoneLoginParams: {
                phone: '',
                code: '',
                textCode: '',
                uuid: '',
            },
            // 账户密码登录时的校验规则
            loginRules: {
                username: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入您的账号',
                    },
                ],
                password: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入您的密码',
                    },
                    {
                        min: 8,
                        max: 16,
                        pattern:
                            /^(?!.*(?:111|888|123|234|345|456|567|678|789|1234|2345|3456|4567|5678|6789|12345|23456|34567|45678|56789|abc|abcd|abcde|abcdef|abcdefg|qwe|qwer|qwert|qwerty|asdf|asdfg|asdfgh|password|passw0rd|letmein|welcome|admin|user|test|pass|root|login))(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+{}\[\]:;"'|\\,.<>\/?~-]).{8,16}$/,
                        message: '请输入正确的登录密码',
                        trigger: 'blur',
                    },
                ],
                code: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请输入验证码',
                    },
                ],
                textCode: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入短信验证码',
                    },
                ],
            },
            // 手机号登录时的校验规则
            phoneLoginRules: {
                phone: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入您的手机号',
                    },
                    {
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号码',
                        trigger: 'blur',
                    },
                ],
                textCode: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入短信验证码',
                    },
                ],
            },
            phoneLoginCodeRules: {
                code: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入图形验证码',
                    },
                ],
            },
            phoneLoginCodeNewRules: {
                code: [
                    {
                        required: true,
                        trigger: 'blur',
                        message: '请输入图形验证码',
                    },
                ],
            },
            loading: false,
            // 验证码开关
            captchaEnabled: true,
            // 注册开关
            register: false,
            redirect: undefined,
            activeName: 'account',
            readonlyFlag: true,
            show: 1,
            count: '',
            timer: null,
            dialogCodeVisible: false, // 图形验证码弹框
            loginParams: {}, //登录页面地址栏参数
            phoneCodeUrlNew: '',
            phoneLoginParamsNew: {
                uuid: '',
                username: '',
            },
            dialogCodeVisibleNew: false,
            timerNew: null,
            showNew: 1,
            countNew: '',
        }
    },
    watch: {
        /* 账户，手机号登录切换时，清空表单的校验 */
        activeName: {
            handler(newVal) {
                // this.$refs['loginForm'].clearValidate()
                // this.$refs['phoneLoginFormRef'].clearValidate()

                if (newVal) {
                    console.log(
                        this.phoneLoginParams.phone,
                        ' this.phoneLoginParams.phone ',
                        this.phoneLoginParams.textCode,
                    )
                    this.phoneLoginParams.phone = ''
                    this.phoneLoginParams.textCode = ''
                    this.loginForm.username = ''
                    this.loginForm.password = ''
                    this.loginForm.textCode = ''
                    this.loginForm.code = ''
                }
                // 切换登录方式时 根据切换方式 自动获取新的图形验证码
                if (newVal === 'account') {
                    this.getCode(1)
                }
            },
            deep: true,
        },

        // 监听 url 地址，如果是商城首页点击跳转 则执行以下逻辑
        $route: {
            handler: function (route) {
                this.redirect = route.query && route.query.redirect
                // console.log(this.$route.query.redirect.split("?"))
                // console.log(this.$route.query.redirect.split("?")[1].split("&"))
                if (this.$route.query.redirect?.split('?').length > 1) {
                    let arr =
                        this.$route.query.redirect.split('?')[1].split('&') ||
                        []
                    arr.forEach((item, index) => {
                        this.$set(
                            this.loginParams,
                            item.split('=')[0] + '',
                            item.split('=')[1],
                        )
                    })
                }
            },
            immediate: true,
        },
    },
    created() {
        if (JSON.stringify(this.loginParams) != '{}') {
            this.jumpLogin()
        }
        this.getCode(1) // 默认账号密码登录 type 传1
        this.getCookie()
    },
    methods: {
        inputChangePhone() {
            this.$forceUpdate()
        },
        inputChangeTextCode() {
            this.$forceUpdate()
        },
        getCode(type) {
            getCodeImg().then((res) => {
                /* 根据 type 判断当前获取的图形验证码如何赋值  1 账号登录 2 手机验证码登录 */
                this.captchaEnabled =
                    res.captchaEnabled === undefined ? true : res.captchaEnabled
                if (this.captchaEnabled) {
                    if (type === 1) {
                        this.codeUrl = 'data:image/gif;base64,' + res.img
                        this.loginForm.uuid = res.uuid
                    } else if (type === 2) {
                        this.phoneCodeUrl = 'data:image/gif;base64,' + res.img
                        this.phoneLoginParams.uuid = res.uuid
                    } else {
                        this.phoneCodeUrlNew =
                            'data:image/gif;base64,' + res.img
                        this.phoneLoginParamsNew.uuid = res.uuid
                    }
                }
            })
        },
        //防止手机号自动充填
        handleInputClick() {
            this.readonlyFlag = false
        },
        //获取短信验证码
        getTextCode() {
            this.$refs.phoneLoginFormRef.validateField(['phone'], (valid) => {
                if (!valid) {
                    this.getCode(2)
                    this.dialogCodeVisible = true
                }
            })
        },

        // 登录用户为admin 时获取短信验证码按钮
        getTextCodeNew() {
            // this.getCode(3)
            // this.dialogCodeVisibleNew = true
            this.phoneLoginParamsNew.username = this.loginForm.username
            sendCode(this.phoneLoginParamsNew)
                .then((res) => {
                    if (res.code == 200) {
                        this.$modal.msgSuccess('发送成功')
                        const TIME_COUNT = 60
                        if (!this.timerNew) {
                            this.countNew = TIME_COUNT
                            this.showNew = 2
                            this.timerNew = setInterval(() => {
                                if (
                                    this.countNew > 0 &&
                                    this.countNew <= TIME_COUNT
                                ) {
                                    this.countNew--
                                } else {
                                    this.showNew = 3
                                    clearInterval(this.timerNew)
                                    this.timerNew = null
                                }
                            }, 1000)
                        }
                        this.dialogCodeVisibleNew = false
                    }
                })
                .catch((err) => {
                    console.log(err)
                })
        },

        // submitSendCodeNew() {
        //   this.$refs.phoneLoginCodeFormNewRef.validate(valid => {
        //     if (valid) {
        //       this.phoneLoginParamsNew.username = this.loginForm.username
        //       sendCodeNew(this.phoneLoginParamsNew)
        //         .then(res => {
        //           if (res.code == 200) {
        //             this.$modal.msgSuccess('发送成功')
        //             const TIME_COUNT = 60
        //             if (!this.timerNew) {
        //               this.countNew = TIME_COUNT
        //               this.showNew = 2
        //               this.timerNew = setInterval(() => {
        //                 if (this.countNew > 0 && this.countNew <= TIME_COUNT) {
        //                   this.countNew--
        //                 } else {
        //                   this.showNew = 3
        //                   clearInterval(this.timerNew)
        //                   this.timerNew = null
        //                 }
        //               }, 1000)
        //             }
        //             this.dialogCodeVisibleNew = false
        //           }
        //         })
        //         .catch(err => {
        //           console.log(err)
        //         })
        //     }
        //   })
        // },

        /* 图形验证码弹框中确定按钮 */
        submitSendCode() {
            this.$refs.phoneLoginCodeFormRef.validate((valid) => {
                if (valid) {
                    const sendParams = {
                        phone: this.phoneLoginParams.phone,
                        code: this.phoneLoginParams.code,
                        uuid: this.phoneLoginParams.uuid,
                    }
                    sendCode(sendParams)
                        .then((res) => {
                            if (res.code == 200) {
                                this.$modal.msgSuccess('发送成功')
                                const TIME_COUNT = 60
                                if (!this.timer) {
                                    this.count = TIME_COUNT
                                    this.show = 2
                                    this.timer = setInterval(() => {
                                        if (
                                            this.count > 0 &&
                                            this.count <= TIME_COUNT
                                        ) {
                                            this.count--
                                        } else {
                                            this.show = 3
                                            clearInterval(this.timer)
                                            this.timer = null
                                        }
                                    }, 1000)
                                }
                            }
                        })
                        .finally(() => {
                            this.dialogCodeVisible = false
                            this.phoneLoginParams.code = ''
                        })
                }
            })
        },
        /* 图形验证码弹框关闭按钮 */
        handleClose() {
            this.dialogCodeVisible = false
            this.$refs['phoneLoginFormRef'].clearValidate()
            this.$refs['phoneLoginCodeFormRef'].clearValidate()
            this.phoneLoginParams.code = ''
        },
        /* 关闭验证码弹框 */
        handleCloseNew() {
            this.dialogCodeVisibleNew = false
            this.$refs['phoneLoginCodeFormNewRef'].clearValidate()
            this.phoneLoginParamsNew.code = ''
        },
        getCookie() {
            const username = Cookies.get('username')
            const password = Cookies.get('password')
            const rememberMe = Cookies.get('rememberMe')
            this.loginForm = {
                username:
                    username === undefined ? this.loginForm.username : username,
                password:
                    password === undefined
                        ? this.loginForm.password
                        : decrypt(password),
                rememberMe:
                    rememberMe === undefined ? false : Boolean(rememberMe),
            }
        },

        // 账户密码登录-------------------------------------------------------------
        handleLogin() {
            console.log(this.loginForm, '参数-----')
            this.$refs.loginForm.validate((valid) => {
                if (valid) {
                    this.loading = true
                    if (this.loginForm.rememberMe) {
                        Cookies.set('username', this.loginForm.username, {
                            expires: 30,
                        })
                        Cookies.set(
                            'password',
                            encrypt(this.loginForm.password),
                            {
                                expires: 30,
                            },
                        )
                        Cookies.set('rememberMe', this.loginForm.rememberMe, {
                            expires: 30,
                        })
                    } else {
                        Cookies.remove('username')
                        Cookies.remove('password')
                        Cookies.remove('rememberMe')
                    }
                    this.$store
                        .dispatch('Login', this.loginForm)
                        .then(() => {
                            if (localStorage.getItem('isCode') == 1) {
                                this.$router
                                    .push({ path: '/resetPassword' })
                                    .catch(() => {})
                            } else {
                                this.$router.push({ path: '/' }).catch(() => {})
                            }
                        })
                        .catch(() => {
                            this.loading = false
                            if (this.captchaEnabled) {
                                this.getCode(1)
                            }
                        })
                }
            })
        },
        // 短信验证码登录-----------------------------------------------------------
        textLogin() {
            console.log(this.loginForm)
            this.$refs.phoneLoginFormRef.validate((valid) => {
                if (valid) {
                    this.loading = true
                    // if (this.loginForm.rememberMe) {
                    //   Cookies.set('username', this.loginForm.username, {
                    //     expires: 30,
                    //   })
                    //   Cookies.set('password', encrypt(this.loginForm.password), {
                    //     expires: 30,
                    //   })
                    //   Cookies.set('rememberMe', this.loginForm.rememberMe, {
                    //     expires: 30,
                    //   })
                    // } else {
                    //   Cookies.remove('username')
                    //   Cookies.remove('password')
                    //   Cookies.remove('rememberMe')
                    // }
                    this.$store
                        .dispatch('textLogin', this.phoneLoginParams)
                        .then(() => {
                            this.$router.push({ path: '/' }).catch(() => {})
                        })
                        .catch(() => {
                            this.loading = false
                        })
                }
            })
        },
        // 南网商城跳转登录----------------------------------------------------------------
        jumpLogin() {
            this.loading = true
            let param = {
                token: this.loginParams.token,
                username: this.loginParams.userName,
            }
            // console.log(param)
            this.$store
                .dispatch('ssoLogin', param)
                .then(() => {
                    //成功后会跳转页面入首页
                    this.$router.push({ path: '/' }).catch(() => {})
                })
                .catch(() => {
                    this.loading = false
                    //失败返回南网登录页面
                    // window.location.replace('https://test-sso.csgmall.com.cn/?client_id=549OWptc&theme=zhgc_storage&response_type=code&redirect_uri=https%3A%2F%2Ftest-cc.zhgkxt.com')
                })
        },
    },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
    //display: flex;
    //justify-content: center;
    //align-items: center;
    position: relative;
    height: 100%;
    background-image: url('../assets/images/login.png');
    background-size: 100% 100%;
    //background: #1891FF;
}

.title {
    margin: 0px auto 30px auto;
    //text-align: center;
    color: #707070;
}

.login-bar {
    position: absolute;
    height: auto;
    top: 20%;
    left: 14%;
    width: auto;
    height: 500px;
    border-radius: 6px;
    display: flex;
    background: #fff;
    text-align: center;
    padding-top: 40px;
}

.form-bar {
    //height: 500px;
    background: #fff;
}

.login-form {
    //border-radius: 6px;
    //height: 100%;
    background: #ffffff;
    margin-top: 25px;
    .el-input {
        // height: 45px;

        input {
            height: 38px;
        }
    }

    .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 2px;
    }
}

.login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
}

.login-code {
    height: 38px;
    margin-left: 15px;
    flex: 1;
    img {
        height: 38px;
        cursor: pointer;
        vertical-align: middle;
    }
}

.el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
}

.login-code-img {
    height: 38px;
    cursor: pointer;
    border-radius: 3px;
}

/* 解决验证码输入框与密码输入框对齐问题 */
::v-deep .code-container .el-form-item__content {
    display: flex;
}

.el-dialog__body {
    padding: 30px 20px 0 20px;
}
</style>
