gaoluyang
5 天以前 6c497f71f5441633099fc7a7896da8e8c7835f05
src/pages/login.vue
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,343 @@
<template>
   <view class="normal-login-container">
      <view class="logo-content">
         <text>账号密码登录</text>
      </view>
      <view class="login-form-content">
         <view class="input-item flex align-center">
            <up-input prefixIcon="account" placeholder="请输入账号" border="bottom"
                           @blur="getUserLoginFacotryList"
                           maxlength="30" v-model="loginForm.userName" clearable></up-input>
         </view>
         <view class="input-item flex align-center">
            <up-input prefixIcon="lock" placeholder="请输入密码" border="bottom" maxlength="20" v-model="loginForm.password" clearable type="password"></up-input>
         </view>
         <view class="input-item flex align-center select-container">
            <up-icon name="tags" size="18"></up-icon>
            <up-picker-data
               v-model="loginForm.factoryId"
               title="请选择公司"
               :options="factoryList"
               valueKey="id"
               style="width: 100%;"
               labelKey="name">
            </up-picker-data>
         </view>
         <view>
            <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
         </view>
      </view>
      <!-- è®°ä½å¯†ç é€‰é¡¹ -->
      <view class="remember-password">
         <up-checkbox
            :customStyle="{marginBottom: '8px'}"
            label="记住密码"
            name="agree"
            usedAlone
            v-model:checked="rememberPassword"
         >
         </up-checkbox>
      </view>
   </view>
</template>
<script setup>
import {modal} from "@/plugins";
const showToast = (message) => {
   uni.showToast({
      title: message,
      icon: 'none'
   })
}
import {
   userLoginFacotryList,
   updateClientId,
   getNoticeCount,
} from "@/api/login";
import { ref, onMounted } from "vue";
import useUserStore from '@/store/modules/user'
import { getWxCode } from '@/utils/geek';
import { wxLogin } from '@/api/oauth';
import { setToken } from '@/utils/auth';
import View from "@/pages/procurementManagement/procurementLedger/view.vue";
const userStore = useUserStore()
const useWxLogin = ref(false); // æ˜¯å¦ä½¿ç”¨å¾®ä¿¡ç™»å½•
const rememberPassword = ref(false); // è®°ä½å¯†ç 
const loginForm = ref({
   userName: "",
   password: "",
   factoryId: "",
   currentFatoryName: "",
});
const factoryList = ref([]) // å…¬å¸åˆ—表
// ä¿å­˜å¯†ç åˆ°æœ¬åœ°å­˜å‚¨
function savePassword() {
   if (rememberPassword.value) {
      uni.setStorageSync('remembered_username', loginForm.value.userName);
      uni.setStorageSync('remembered_password', loginForm.value.password);
      uni.setStorageSync('remember_password', true);
   } else {
      uni.removeStorageSync('remembered_username');
      uni.removeStorageSync('remembered_password');
      uni.setStorageSync('remember_password', false);
   }
}
// ä»Žæœ¬åœ°å­˜å‚¨åŠ è½½å¯†ç 
function loadPassword() {
   const remembered = uni.getStorageSync('remember_password');
   if (remembered) {
      rememberPassword.value = true;
      const savedUsername = uni.getStorageSync('remembered_username');
      const savedPassword = uni.getStorageSync('remembered_password');
      if (savedUsername) {
         loginForm.value.userName = savedUsername;
      }
      if (savedPassword) {
         loginForm.value.password = savedPassword;
      }
   }
}
if (useWxLogin.value) {
   getWxCode().then(res => {
      console.log(res);
      wxLogin('miniapp',res).then(res => {
         if(res.token != null){
            setToken(res.token);
            loginSuccess()
         }
      });
   })
}
function getUserLoginFacotryList() {
   if(loginForm.value.userName){
      userLoginFacotryList({userName:loginForm.value.userName}).then(res => {
         console.log('res',res)
         // æ£€æŸ¥res.data是否为数组
         if (res.data && Array.isArray(res.data)) {
            // é‡æ–°ç»„装数据格式:deptId变成id,deptName变成name
            factoryList.value = res.data.map(item => ({
               id: item.deptId,
               name: item.deptName
            }))
         } else {
            // å¦‚æžœres.data不是数组,设置为空数组
            factoryList.value = []
         }
      }).catch(error => {
         showToast('获取公司列表失败:', error)
         factoryList.value = []
      })
   }else {
      factoryList.value = []
   }
}
async function handleLogin() {
   if (loginForm.value.userName === "") {
      showToast("请输入您的账号")
   } else if (loginForm.value.password === "") {
      showToast("请输入您的密码")
   } else if (loginForm.value.factoryId === "") {
      showToast("请选择公司")
   } else {
      showToast("登录中,请耐心等待...")
      pwdLogin()
   }
};
// å¯†ç ç™»å½•
async function pwdLogin() {
   userStore.loginCheckFactory(loginForm.value).then(() => {
      modal.closeLoading()
      // ç™»å½•成功后保存密码
      savePassword();
      loginSuccess()
   }).catch(() => {
      modal.closeLoading()
   })
};
function loginSuccess(result) {
   userStore.getInfo().then(res => {
      const userId = res.user.userId;
      // ç™»å½•成功后,将客户端推送标识发送到服务器
      sendClientIdToServer();
      // å¯åŠ¨å®šæ—¶èŽ·å–æœªè¯»æ¶ˆæ¯æ•°é‡çš„å®šæ—¶å™¨
      startNoticeCountTimer(userId);
   })
   // è®¾ç½®ç”¨æˆ·ä¿¡æ¯
   userStore.getInfo().then(res => {
      uni.switchTab({
         url: '/pages/index'
      });
   })
}
// å¯åŠ¨å®šæ—¶èŽ·å–æœªè¯»æ¶ˆæ¯æ•°é‡çš„å®šæ—¶å™¨
function startNoticeCountTimer(userId) {
   // ç«‹å³èŽ·å–ä¸€æ¬¡æœªè¯»æ¶ˆæ¯æ•°é‡
   updateNoticeCount(userId);
   // è®¾ç½®å®šæ—¶å™¨ï¼Œæ¯30秒获取一次
   setInterval(() => {
      updateNoticeCount(userId);
   }, 30000);
}
// æ›´æ–°æœªè¯»æ¶ˆæ¯æ•°é‡
function updateNoticeCount(userId) {
   getNoticeCount(userId)
      .then(res => {
         const count = res.data || 0;
         console.log("未读消息数量:", count);
         // æ›´æ–°tabbar的角标
         if (count > 0) {
            uni.setTabBarBadge({
               index: 1, // æ¶ˆæ¯æ ‡ç­¾é¡µçš„索引
               text: count.toString(),
            });
         } else {
            uni.removeTabBarBadge({
               index: 1,
            });
         }
      })
      .catch(error => {
         console.error("获取未读消息数量失败:", error);
      });
}
// å°†å®¢æˆ·ç«¯æŽ¨é€æ ‡è¯†å‘送到服务器
function sendClientIdToServer() {
   // èŽ·å–æœ¬åœ°å­˜å‚¨çš„å®¢æˆ·ç«¯æ ‡è¯†
   const clientId = uni.getStorageSync("clientid");
   if (clientId) {
      console.log("登录成功,准备发送客户端标识到服务器:", clientId);
      // è¿™é‡Œè°ƒç”¨åŽç«¯æŽ¥å£å‘送客户端标识
      updateClientId({ cid: clientId })
         .then(res => {
            console.log("服务器响应:", res);
            if (res.code === 200) {
               console.log("客户端标识已成功发送到服务器");
            } else {
               console.log("服务器返回错误:", res.msg);
            }
         })
         .catch(error => {
            console.log("发送客户端标识到服务器失败:", error);
         });
      // ç¤ºä¾‹ï¼šapi.updateClientId({ clientId: clientId });
      // ç”±äºŽæ²¡æœ‰å…·ä½“的接口,这里只打印日志
      console.log("客户端标识已发送到服务器");
   } else {
      console.log("未获取到客户端推送标识");
   }
}
// é¡µé¢åŠ è½½æ—¶æ£€æŸ¥æ˜¯å¦æœ‰ä¿å­˜çš„å¯†ç 
onMounted(() => {
   loadPassword();
   getUserLoginFacotryList()
});
</script>
<style lang="scss">
page {
   background-color: #ffffff;
}
.normal-login-container {
   width: 100%;
   height: 100vh;
   .logo-content {
      width: 90%;
      font-weight: 400;
      font-size: 30px;
      color: #333333;
      margin: 80px 0 0 30px;
      image {
         border-radius: 4px;
      }
      .title {
         margin-left: 10px;
      }
   }
   .u-checkbox {
      margin-left: 34px;
   }
   .login-form-content {
      text-align: center;
      margin: 58px auto;
      padding: 0 30px;
      .input-item {
         margin: 30px auto;
         height: 45px;
         .icon {
            font-size: 38rpx;
            margin-left: 10px;
            color: #999;
         }
         .input {
            width: 100%;
            font-size: 14px;
            line-height: 20px;
            text-align: left;
            padding-left: 15px;
         }
      }
      .select-container {
         flex: 1;
         border-bottom: 1px solid #e5e5e5;
         padding: 6px 9px;
         :deep(.up-select) {
            border: none;
            background: transparent;
            .up-select__label {
               font-size: 14px;
               color: #333;
            }
            .up-select__value {
               font-size: 14px;
               color: #333;
            }
         }
      }
      .login-btn {
         margin-top: 60px;
         height: 50px;
         background: linear-gradient( 140deg, #00BAFF 0%, #006CFB 100%);
         box-shadow: 0px 4px 10px 0px rgba(3,88,185,0.2);
         border-radius: 40px 40px 40px 40px;
      }
      .xieyi {
         color: #333;
         margin-top: 20px;
      }
      .login-code {
         height: 38px;
         float: right;
         .login-code-img {
            height: 38px;
            position: absolute;
            margin-left: 10px;
            width: 200rpx;
         }
      }
   }
}
</style>