yangyin
2024-05-20 4fe305c2a999eb2d1ccb92c9ffd9aefb8c68b316
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
<template>
    <el-form size="large" ref="ruleFormRef" :model="state.ruleForm" :rules="state.rules" class="login-content-form">
        <el-form-item class="login-animation1">
            <el-input
                text
                :placeholder="$t('message.account.accountPlaceholder1')"
                v-model="state.ruleForm.account"
                clearable
                autocomplete="username"
            >
                <template #prefix>
                    <el-icon class="el-input__icon"><ele-User /></el-icon>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item class="login-animation2">
            <el-input
                :type="state.isShowPassword ? 'text' : 'password'"
                :placeholder="$t('message.account.accountPlaceholder2')"
                v-model="state.ruleForm.password"
                autocomplete="current-password"
            >
                <template #prefix>
                    <el-icon class="el-input__icon"><ele-Unlock /></el-icon>
                </template>
                <template #suffix>
                    <i
                        class="iconfont el-input__icon login-content-password"
                        :class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
                        @click="state.isShowPassword = !state.isShowPassword"
                    >
                    </i>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item class="login-animation3">
            <el-col :span="15">
                <el-input
                    text
                    maxlength="4"
                    :placeholder="$t('message.account.accountPlaceholder3')"
                    v-model="state.ruleForm.code"
                    clearable
                    autocomplete="off"
                >
                    <template #prefix>
                        <el-icon class="el-input__icon"><ele-Position /></el-icon>
                    </template>
                </el-input>
            </el-col>
            <el-col :span="1"></el-col>
            <el-col :span="8">
                <div class="login-content-code">
                    <img
                        class="login-content-code-img"
                        @click="getCaptcha"
                        width="130px"
                        height="38px"
                        :src="state.captchaImage"
                        style="cursor: pointer"
                    />
                </div>
            </el-col>
        </el-form-item>
        <el-form-item class="login-animation4">
            <el-button type="primary" class="login-content-submit" round v-waves @click="onSignIn" :loading="state.loading.signIn">
                <span>{{ $t('message.account.accountBtnText') }}</span>
            </el-button>
        </el-form-item>
    </el-form>
</template>
 
<script setup lang="ts" name="loginAccount">
import { reactive, ref, computed, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, FormInstance } from 'element-plus';
import { useI18n } from 'vue-i18n';
import Cookies from 'js-cookie';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useUserInfo } from '/@/stores/userInfo';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session, Local } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import { GetCaptcha, GetVerifyCaptcha, LoginSoftware, GetRolesListByUserID } from '/@/api/login/index';
import profileMan from '/@/assets/profile/man.svg';
import { accessTokenKey, clearAccessTokens } from '/@/utils/request';
 
// 定义变量内容
const { t } = useI18n();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const route = useRoute();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const state = reactive({
    isShowPassword: false,
    ruleForm: {
        account: '',
        password: '',
        code: '',
        codeId: 0,
    },
    captchaImage: '',
    loading: {
        signIn: false,
    },
    rules: {
        account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
    },
});
 
const pressEnterLogin = (ev: KeyboardEvent) => {
    if (ev.key === 'Enter') {
        onSignIn();
    }
};
 
onMounted(() => {
    getCaptcha();
    ruleFormRef.value?.$el.addEventListener('keypress', pressEnterLogin);
});
onUnmounted(() => {
    ruleFormRef.value?.$el.removeEventListener('keypress', pressEnterLogin);
});
// 时间获取
const currentTime = computed(() => {
    return formatAxis(new Date());
});
// 获取验证码
const getCaptcha = async () => {
    state.ruleForm.code = '';
 
    const res = await GetCaptcha();
    if (res?.Code === 0) {
        if (res.Data) {
            state.ruleForm.codeId = Number(res.Data.Id);
            state.captchaImage = 'data:text/html;base64,' + res.Data.Img;
        } else {
            ElMessage.error('获取验证码失败');
        }
    } else {
        ElMessage.error('获取验证码失败' + (res?.Message ? `,${JSON.stringify(res.Message)}` : ''));
    }
};
// 校验验证码
const verifyCaptcha = async () => {
    let params = {
        Id: state.ruleForm.codeId,
        Code: state.ruleForm.code,
    };
    const res = await GetVerifyCaptcha(params);
    if (res?.Code === 0) {
        return res.Data;
    } else {
        ElMessage.error('验证码校验失败!' + (res?.Message ? `,${JSON.stringify(res.Message)}` : ''));
        return false;
    }
    // return new Promise((resolve, reject) => {
    //     let params = {
    //         Id: state.ruleForm.codeId,
    //         Code: state.ruleForm.code,
    //     };
    //     axios
    //         .get(LOGIN_API_URL + '/Auth/Tool/VerifyCaptcha@V1.0', {
    //             params,
    //         })
    //         .then((res: any) => {
    //             resolve(res.data.Data);
    //         })
    //         .catch((err: any) => {
    //             reject(err);
    //         });
    //     apiSysAuthCaptchaRuleGet(params)
    //         .then((res: any) => {
    //             resolve(res.Data);
    //         })
    //         .catch((err: any) => {
    //             reject(err);
    //         });
    // });
};
// 登录
const onSignIn = async () => {
    ruleFormRef.value.validate(async (valid: boolean) => {
        if (!valid) return false;
        // 校验验证码
        let isPassCaptcha = await verifyCaptcha();
        if (!isPassCaptcha) {
            getCaptcha();
            ElMessage.error('验证码错误,请重新输入!');
            return;
        }
        let params = {
            SoftWare: (window as any).globalConfig.Auth.SoftWareCode,
            LoginName: state.ruleForm.account,
            LoginPwd: state.ruleForm.password,
            Message: (window as any).globalConfig.Auth.Message,
        };
 
        const res = await LoginSoftware(params);
        if (res?.Code === 0) {
            if (res.Data) {
                if (res.Data?.Token == undefined) {
                    getCaptcha(); // 重新获取验证码
                    ElMessage.error('登录失败,请检查账号!');
                    return;
                }
                // 缓存access-token
                Local.set(accessTokenKey, res.Data?.Token);
 
                // admin 页面权限标识,对应路由 meta.roles,用于控制路由的显示/隐藏
                let adminRoles: Array<string> = [];
                if (res.Data.User?.ID) {
                    const res1 = await GetRolesListByUserID({
                        UserID: res.Data.User.ID,
                    });
                    if (res?.Code === 0) {
                        adminRoles = (res1.Data || []) as [];
                    } else {
                        ElMessage.error('获取用户角色失败' + (res?.Message ? `,${JSON.stringify(res.Message)}` : ''));
                    }
                }
 
                // admin 按钮权限标识
                let adminAuthBtnList: Array<string> = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
                let userName = res.Data.User.Name;
                const userInfos = {
                    SoftWare: res.Data.Software,
                    User: res.Data.User,
                    userName: userName,
                    photo: profileMan,
                    time: new Date().getTime(),
                    roles: adminRoles,
                    authBtnList: adminAuthBtnList,
                };
                await useUserInfo().setUserInfos(userInfos); //缓存用户信息
 
                state.loading.signIn = true;
                if (!themeConfig.value.isRequestRoutes) {
                    // 前端控制路由,2、请注意执行顺序
                    const isNoPower = await initFrontEndControlRoutes();
                    // console.log(isNoPower,172)
                    signInSuccess(isNoPower);
                } else {
                    // 模拟后端控制路由,isRequestRoutes 为 true,则开启后端控制路由
                    // 添加完动态路由,再进行 router 跳转,否则可能报错 No match found for location with path "/"
                    const isNoPower = await initBackEndControlRoutes();
                    // 执行完 initBackEndControlRoutes,再执行 signInSuccess
                    // console.log(isNoPower,178)
                    signInSuccess(isNoPower);
                }
            } else {
                ElMessage.error('登录失败,请检查账号!');
            }
        } else {
            ElMessage.error('登录失败,请检查账号!' + (res?.Message ? `,${JSON.stringify(res.Message)}` : ''));
        }
 
        // 登录校验
        // await apiSysAuthLoginPost(params)
        //     .then(async (res: any) => {
 
        //     })
        //     .catch((err: any) => {
        //         console.log(err);
        //     });
    });
};
// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
    if (isNoPower) {
        ElMessage.warning('您没有登录权限');
        clearAccessTokens();
    } else {
        // 初始化登录成功时间问候语
        let currentTimeInfo = currentTime.value;
        // 登录成功,跳到转首页
        // 如果是复制粘贴的路径,非首页/登录页,那么登录成功后重定向到对应的路径中
        // console.log(route.query, 199);
        if (route.query?.redirect) {
            router.push({
                path: <string>route.query?.redirect,
                query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
            });
        } else {
            router.push('/');
        }
        // 登录成功提示
        const signInText = t('message.signInText');
        ElMessage.success(`${currentTimeInfo},${signInText}`);
        // 添加 loading,防止第一次进入界面时出现短暂空白
        NextLoading.start();
    }
    state.loading.signIn = false;
};
 
</script>
 
<style scoped lang="scss">
.login-content-form {
    margin-top: 20px;
 
    @for $i from 1 through 4 {
        .login-animation#{$i} {
            opacity: 0;
            animation-name: error-num;
            animation-duration: 0.5s;
            animation-fill-mode: forwards;
            animation-delay: calc($i/10) + s;
        }
    }
 
    .login-content-password {
        display: inline-block;
        width: 20px;
        cursor: pointer;
 
        &:hover {
            color: #909399;
        }
    }
 
    .login-content-code {
        display: flex;
        align-items: center;
        justify-content: space-around;
 
        .login-content-code-img {
            width: 100%;
            height: 40px;
            line-height: 40px;
            background-color: #ffffff;
            border: 1px solid rgb(220, 223, 230);
            cursor: pointer;
            transition: all ease 0.2s;
            border-radius: 4px;
            user-select: none;
 
            &:hover {
                border-color: #c0c4cc;
                transition: all ease 0.2s;
            }
        }
    }
 
    .login-content-submit {
        width: 100%;
        letter-spacing: 2px;
        font-weight: 300;
        margin-top: 15px;
    }
}
</style>