chatapp-h5/h5/platform-policy/platform-policy.js
2026-04-24 21:13:53 +08:00

286 lines
8.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const API_BASE_URL = "https://jvapi.haiyihy.com";
let commonHeaders = {
authorization: "Bearer undefined",
"req-app-intel": "version=1.0.0;build=1;model=SM-G9550;sysVersion=9;channel=Google",
"req-client": "Android",
"req-imei": "8fa54d728ab449e04f9292329ed44bda",
"req-lang": "id-ID",
"req-sys-origin": "origin=ATYOU;originChild=ATYOU",
"req-version": "V2",
"req-zone": "Asia/Shanghai"
};
const i18n = {
en: {
platform_policy: "Platform Policy",
time: "Time",
hours: "hours",
target: "Target",
host_salary: "Host salary",
agent_salary: "Agent salary",
total_salary: "Total salary",
no_policy_data_available: "No policy data available"
},
ar: {
platform_policy: "سياسة المنصة",
time: "الوقت",
hours: "ساعات",
target: "الهدف",
host_salary: "راتب المضيف",
agent_salary: "راتب الوكيل",
total_salary: "إجمالي الراتب",
no_policy_data_available: "لا توجد بيانات سياسة"
},
tr: {
platform_policy: "Platform politikası",
time: "Süre",
hours: "saat",
target: "Hedef",
host_salary: "Host maaşı",
agent_salary: "Ajans maaşı",
total_salary: "Toplam maaş",
no_policy_data_available: "Politika verisi yok"
},
bn: {
platform_policy: "প্ল্যাটফর্ম নীতি",
time: "সময়",
hours: "ঘণ্টা",
target: "টার্গেট",
host_salary: "হোস্ট বেতন",
agent_salary: "এজেন্ট বেতন",
total_salary: "মোট বেতন",
no_policy_data_available: "কোনো নীতি ডেটা নেই"
}
};
const state = {
lang: resolveLanguage(),
fromAgencyCenter: new URLSearchParams(window.location.search).get("from") === "agencycenter",
policies: []
};
const $ = (selector) => document.querySelector(selector);
const t = (key) => (i18n[state.lang] && i18n[state.lang][key]) || i18n.en[key] || key;
function resolveLanguage() {
const params = new URLSearchParams(window.location.search);
const lang = params.get("lang") || navigator.language || "en";
if (lang.startsWith("ar")) return "ar";
if (lang.startsWith("tr")) return "tr";
if (lang.startsWith("bn")) return "bn";
return "en";
}
function splitHeaderPairs(value) {
const result = {};
if (!value) return result;
value.split(";").forEach((item) => {
const index = item.indexOf("=");
if (index > -1) result[item.slice(0, index)] = item.slice(index + 1);
});
return result;
}
function parseAccessOrigin(raw) {
const data = JSON.parse(raw);
const appIntel = splitHeaderPairs(data["Req-App-Intel"]);
const sysOrigin = splitHeaderPairs(data["Req-Sys-Origin"]);
return {
reqLang: data["Req-Lang"],
authorization: data.Authorization,
buildVersion: appIntel.build,
appVersion: appIntel.version,
appChannel: appIntel.channel,
reqImei: appIntel["Req-Imei"],
sysOrigin: sysOrigin.origin,
sysOriginChild: sysOrigin.child
};
}
function setHeadersFromApp(headers) {
const next = {};
if (headers.authorization) next.authorization = headers.authorization;
if (headers.reqLang) next["req-lang"] = headers.reqLang;
if (headers.appVersion || headers.buildVersion || headers.appChannel) {
const intel = [];
if (headers.appVersion) intel.push(`version=${headers.appVersion}`);
if (headers.buildVersion) intel.push(`build=${headers.buildVersion}`);
if (headers.appChannel) intel.push(`channel=${headers.appChannel}`);
next["req-app-intel"] = intel.join(";");
}
if (headers.reqImei) next["req-imei"] = headers.reqImei;
if (headers.sysOrigin) {
const origin = [`origin=${headers.sysOrigin}`];
if (headers.sysOriginChild) origin.push(`child=${headers.sysOriginChild}`);
next["req-sys-origin"] = origin.join(";");
}
commonHeaders = { ...commonHeaders, ...next };
}
function connectToApp() {
return new Promise((resolve) => {
window.renderData = resolve;
window.getIosAccessOriginParam = resolve;
if (!(window.app || window.webkit || window.FlutterPageControl)) {
setHeadersFromApp({
authorization: "",
reqLang: state.lang,
appVersion: "1.0.0",
buildVersion: "1",
appChannel: "Web",
reqImei: "H5-STATIC",
sysOrigin: "LIKEI",
sysOriginChild: "LIKEI"
});
resolve(null);
return;
}
let attempt = 0;
const poll = () => {
attempt += 1;
if (window.app && typeof window.app.getAccessOrigin === "function") {
resolve(window.app.getAccessOrigin());
return;
}
if (attempt < 50) {
window.setTimeout(poll, 100);
return;
}
if (window.FlutterApp && typeof window.FlutterApp.postMessage === "function") {
window.FlutterApp.postMessage("requestAccessOrigin");
}
resolve(null);
};
poll();
}).then((raw) => {
if (raw) setHeadersFromApp(parseAccessOrigin(raw));
});
}
async function apiGet(path) {
const response = await fetch(`${API_BASE_URL}${path}`, {
method: "GET",
headers: commonHeaders
});
const data = await response.json().catch(() => ({}));
if (!response.ok || data.status === false) {
const error = new Error(data.errorMsg || data.message || `Request failed: ${response.status}`);
error.response = data;
throw error;
}
return data;
}
function getTeamId() {
const cached = localStorage.getItem("teamInfo");
if (cached) {
try {
const teamInfo = JSON.parse(cached);
if (teamInfo && teamInfo.id) return teamInfo.id;
} catch (error) {
console.error("Failed to parse teamInfo:", error);
}
}
return null;
}
function formatTarget(value) {
if (!value) return "0";
const number = parseFloat(value);
if (Number.isNaN(number)) return value;
if (number >= 1000000) return `${(number / 1000000).toFixed(1)}M`;
if (number >= 1000) return `${(number / 1000).toFixed(1)}K`;
return number.toString();
}
function closePage() {
if (window.history.length > 1) {
window.history.back();
return;
}
if (window.app && typeof window.app.closePage === "function") {
window.app.closePage();
return;
}
if (window.FlutterPageControl && typeof window.FlutterPageControl.postMessage === "function") {
window.FlutterPageControl.postMessage("close_page");
}
}
function showToast(message) {
const toast = $("#toast");
toast.textContent = message || "Request failed";
toast.hidden = false;
window.clearTimeout(showToast.timer);
showToast.timer = window.setTimeout(() => {
toast.hidden = true;
}, 2500);
}
function renderI18n() {
document.documentElement.lang = state.lang;
document.documentElement.dir = state.lang === "ar" ? "rtl" : "ltr";
document.querySelectorAll("[data-i18n]").forEach((node) => {
node.textContent = t(node.dataset.i18n);
});
}
function policyCell(label, value, className = "") {
return `<div class="policy-cell ${className}">
<div class="label">${label}</div>
<div class="value">${value}</div>
</div>`;
}
function renderPolicies() {
const root = $("#policyList");
if (!state.policies.length) {
root.innerHTML = `<div class="empty-state"><div class="empty-icon">📋</div><p>${t("no_policy_data_available")}</p></div>`;
return;
}
root.innerHTML = `<div class="policy-stack">${state.policies.map((item) => `
<section class="policy-card">
<div class="level-badge">Lv.${item.level}</div>
<div class="policy-grid">
${policyCell(`${t("time")} (${t("hours")})`, item.onlineTime || 0, "align-left")}
${policyCell(t("target"), formatTarget(item.target))}
${policyCell(t("host_salary"), `$${item.memberSalary || 0}`, "align-right")}
${state.fromAgencyCenter ? policyCell(t("agent_salary"), `$${item.ownSalary || 0}`, "align-left") : ""}
${state.fromAgencyCenter ? policyCell(t("total_salary"), `$${item.totalSalary || 0}`) : ""}
</div>
</section>
`).join("")}</div>`;
}
async function fetchPolicies() {
const teamId = getTeamId();
const result = await apiGet(`/team/release/policy?id=${teamId}`);
if (result.status && result.body && result.body.policy) {
state.policies = result.body.policy || [];
} else {
state.policies = [];
}
}
async function init() {
renderI18n();
$("[data-action='back']").addEventListener("click", closePage);
try {
await connectToApp();
await fetchPolicies();
} catch (error) {
console.error("Failed to fetch team policy:", error);
state.policies = [];
showToast(error.response?.errorMsg || error.message);
} finally {
renderPolicies();
}
}
init();