import {
|
getHistoryFromStorage,
|
saveHistoryToStorage,
|
formatDateTime,
|
isValid,
|
getRemainingTime,
|
generateCode,
|
generatePassword,
|
showMessage,
|
copyToClipboard
|
} from './utils.js';
|
import WeChatOAuth from './wechat-oauth.js';
|
import ApiClient from './api-client.js';
|
import { WECOM_CONFIG } from './wecom-config.js';
|
|
// 获取DOM元素
|
const phoneInput = document.getElementById('phone');
|
const getCodeBtn = document.getElementById('getCodeBtn');
|
const codeCountSpan = document.getElementById('code-count');
|
const historyBody = document.getElementById('historyBody');
|
|
// 初始化 OAuth 和 API 客户端
|
let oauth = null;
|
let apiClient = null;
|
|
// 页面初始化
|
export function initApp() {
|
// 初始化 OAuth 客户端
|
oauth = new WeChatOAuth(WECOM_CONFIG);
|
apiClient = new ApiClient(WECOM_CONFIG.apiBaseUrl);
|
|
// 检查是否有授权码(从企业微信重定向回来)
|
const authCode = oauth.getAuthCode();
|
if (authCode) {
|
handleAuthCallback(authCode);
|
} else if (oauth.isAuthorized()) {
|
// 已有用户信息,直接显示
|
displayUserInfo();
|
loadHistory();
|
setupEventListeners();
|
} else {
|
// 未授权,显示授权链接或自动跳转
|
handleUnauthorized();
|
}
|
}
|
|
/**
|
* 处理企业微信授权回调
|
*/
|
async function handleAuthCallback(code) {
|
try {
|
showMessage('正在获取用户信息...', 'info');
|
const userInfo = await oauth.exchangeCodeForUserInfo(code);
|
|
// 清除 URL 中的 code 参数
|
window.history.replaceState({}, document.title, window.location.pathname);
|
|
// 显示用户信息
|
displayUserInfo(userInfo);
|
|
// 初始化应用功能
|
loadHistory();
|
setupEventListeners();
|
|
showMessage('授权成功!', 'success');
|
} catch (error) {
|
console.error('授权处理失败:', error);
|
showMessage(`授权失败: ${error.message}`);
|
handleUnauthorized();
|
}
|
}
|
|
/**
|
* 处理未授权状态
|
*/
|
function handleUnauthorized() {
|
// 如果在企业微信环境中,使用企业微信 JSSDK
|
if (isInWeCom()) {
|
redirectToWeChatAuth();
|
} else {
|
// 非企业微信环境,显示提示或授权链接
|
showAuthPrompt();
|
}
|
}
|
|
/**
|
* 检查是否在企业微信环境中
|
*/
|
function isInWeCom() {
|
return /wxwork/i.test(navigator.userAgent);
|
}
|
|
/**
|
* 重定向到企业微信授权页面
|
*/
|
function redirectToWeChatAuth() {
|
const authUrl = oauth.getAuthUrl();
|
window.location.href = authUrl;
|
}
|
|
/**
|
* 显示授权提示
|
*/
|
function showAuthPrompt() {
|
const container = document.querySelector('.container');
|
const authPrompt = document.createElement('div');
|
authPrompt.className = 'auth-prompt';
|
authPrompt.innerHTML = `
|
<div class="auth-content">
|
<h2>需要授权</h2>
|
<p>请使用企业微信打开此页面进行授权</p>
|
<p>或点击下方按钮进行授权</p>
|
<button class="btn-primary btn-auth" id="authBtn">授权登录</button>
|
<p class="auth-tip">授权将获取您的基本信息,用于身份验证</p>
|
</div>
|
`;
|
container.innerHTML = '';
|
container.appendChild(authPrompt);
|
|
document.getElementById('authBtn').addEventListener('click', () => {
|
redirectToWeChatAuth();
|
});
|
}
|
|
/**
|
* 显示用户信息
|
*/
|
function displayUserInfo(userInfo = null) {
|
const info = userInfo || oauth.getUserInfo();
|
|
if (!info) {
|
return;
|
}
|
|
// 更新页面显示的用户信息
|
const nameElement = document.querySelector('.company-name');
|
if (nameElement && info.name) {
|
nameElement.textContent = info.name || info.userid;
|
}
|
|
// 更新手机号(如果返回的话)
|
if (phoneInput && info.mobile) {
|
phoneInput.value = info.mobile;
|
}
|
|
// 存储完整用户信息用于后续使用
|
window.currentUser = info;
|
|
// 可以根据需要显示更多用户信息
|
console.log('当前用户信息:', info);
|
}
|
|
// 事件监听器
|
function setupEventListeners() {
|
getCodeBtn.addEventListener('click', handleGetCode);
|
phoneInput.addEventListener('input', function(e) {
|
// 只允许输入数字
|
this.value = this.value.replace(/[^\d]/g, '');
|
});
|
phoneInput.addEventListener('change', updateCodeCount);
|
phoneInput.addEventListener('blur', updateCodeCount);
|
}
|
|
// 获取验证码处理
|
function handleGetCode() {
|
const phone = phoneInput.value.trim();
|
|
// 验证手机号
|
if (!phone) {
|
showMessage('请输入手机号');
|
return;
|
}
|
|
if (!/^1[3-9]\d{9}$/.test(phone)) {
|
showMessage('请输入有效的手机号');
|
return;
|
}
|
|
// 检查申请次数
|
const history = getHistoryFromStorage();
|
const phoneRecords = history.filter(record => record.phone === phone && isValid(record.expiryTime));
|
|
if (phoneRecords.length >= 5) {
|
showMessage('该手机号本周期已达到申请次数限制(5次)');
|
return;
|
}
|
|
// 生成验证码和密码
|
const code = generateCode();
|
const password = generatePassword();
|
const currentTime = new Date();
|
const expiryTime = new Date(currentTime.getTime() + 72 * 60 * 60 * 1000);
|
|
// 创建新记录
|
const newRecord = {
|
phone: phone,
|
password: password,
|
requestTime: formatDateTime(currentTime),
|
expiryTime: expiryTime.toISOString(),
|
id: Date.now()
|
};
|
|
// 保存到历史记录
|
history.push(newRecord);
|
saveHistoryToStorage(history);
|
|
// 更新UI
|
updateCodeCount();
|
loadHistory();
|
phoneInput.value = '';
|
|
// 显示成功提示
|
showMessage(`密码已生成:${password}`, 'success');
|
}
|
|
// 更新申请次数
|
function updateCodeCount() {
|
const phone = phoneInput.value.trim();
|
if (!phone) {
|
codeCountSpan.textContent = '0';
|
return;
|
}
|
|
const history = getHistoryFromStorage();
|
const validRecords = history.filter(record =>
|
record.phone === phone && isValid(record.expiryTime)
|
);
|
codeCountSpan.textContent = validRecords.length;
|
}
|
|
// 加载历史记录到表格
|
function loadHistory() {
|
const history = getHistoryFromStorage();
|
|
// 过滤72小时内的记录
|
const recentHistory = history.filter(record => isValid(record.expiryTime));
|
|
if (recentHistory.length === 0) {
|
historyBody.innerHTML = '<tr class="empty-row"><td colspan="5">暂无记录</td></tr>';
|
return;
|
}
|
|
// 按时间倒序排列
|
recentHistory.sort((a, b) => new Date(b.expiryTime) - new Date(a.expiryTime));
|
|
historyBody.innerHTML = recentHistory.map(record => `
|
<tr>
|
<td><strong>${record.password}</strong></td>
|
<td>${record.requestTime}</td>
|
<td>${formatDateTime(new Date(record.expiryTime))}</td>
|
<td>${getRemainingTime(record.expiryTime)}</td>
|
<td>
|
<button class="btn-action" data-password="${record.password}">复制</button>
|
</td>
|
</tr>
|
`).join('');
|
|
// 为复制按钮添加事件监听
|
document.querySelectorAll('.btn-action').forEach(btn => {
|
btn.addEventListener('click', function() {
|
const password = this.dataset.password;
|
copyToClipboard(password).then(() => {
|
showMessage('密码已复制到剪贴板', 'success');
|
});
|
});
|
});
|
|
// 定期更新剩余时间
|
setInterval(() => {
|
const cells = document.querySelectorAll('.history-table tbody tr td:nth-child(4)');
|
let index = 0;
|
recentHistory.forEach(record => {
|
if (cells[index]) {
|
cells[index].textContent = getRemainingTime(record.expiryTime);
|
}
|
index += 5;
|
});
|
}, 60000); // 每分钟更新一次
|
}
|
|
// 页面加载时定期更新剩余时间
|
setInterval(() => {
|
const cells = document.querySelectorAll('.history-table tbody tr td:nth-child(4)');
|
cells.forEach(cell => {
|
const row = cell.closest('tr');
|
if (row && row.querySelector('td:nth-child(2)')) {
|
const expiryText = row.querySelector('td:nth-child(3)').textContent;
|
if (expiryText) {
|
cell.textContent = getRemainingTime(expiryText);
|
}
|
}
|
});
|
}, 60000); // 每分钟更新一次
|