const $ = layui.$;
// 全局变量
let gmjldata = []; // 转换后的扁平数组
let originalData = []; // 原始树形数据
let qishuok = {}; // 期号数据
let selectedLotteryPath = [];
let selectedLotteryIds = [];
let currentIssue = ""; // 当前期号
let currentPayPublishOptions = null;
let currentPayPicker = null;
let isSubmittingPayArticle = false;
let selections = [];
let stepsConfig = [];
// 页面加载完成后获取首页信息
layui.$(document).ready(function () {
CommonUtil.loadPageConfig({ ads: false, links: false });
checkPaidPublishPermission().then(function (result) {
if (!result.canPaid) {
layui.layer.alert(
result.reason || "暂无付费文章发布权限。",
{
title: "暂无权限",
},
function () {
window.location.href = "fabumianfeiwenzhang.html";
},
);
return;
}
loadLotteryData();
});
});
// 付费文章发布权限以 mine/summary 返回字段为准。
function checkPaidPublishPermission() {
return ApiClient.get(ApiClient.API.mineSummary)
.then(function (res) {
if (
!ApiClient.isSuccess(res) ||
!res.data ||
!window.PublishPermission
) {
return { canPaid: false, reason: "暂时无法获取发布权限。" };
}
const permission = PublishPermission.parseSummary(res.data);
return {
...permission,
reason: permission.reason || permission.paidReason,
};
})
.catch(function () {
return { canPaid: false, reason: "暂时无法获取发布权限。" };
});
}
// 加载彩种数据
async function loadLotteryData() {
try {
console.log("开始加载彩种数据...");
const response = await ApiClient.get(ApiClient.API.homeNav);
console.log("API返回的原始数据:", response);
if (
response.code === 0 &&
response.data &&
Array.isArray(response.data)
) {
originalData = await preparePayPublishMenuTree(response.data);
// 1. 转换树形结构为适合selectY2的扁平数组
gmjldata = convertTreeToFlatArray(originalData);
console.log("转换后的扁平数组:", gmjldata);
// 2. 初始化期号数据
initIssueData(originalData);
// 3. 初始化LayUI组件
initLayuiComponents();
} else {
throw new Error(response.msg || "获取数据失败");
}
} catch (error) {
console.error("加载彩种数据失败:", error);
layui.layer.msg("加载彩种数据失败: " + error.message, { icon: 2 });
}
}
// 转换树形结构为扁平数组
function convertTreeToFlatArray(treeData) {
const excludeNames = [
"首页",
"专家推荐",
"断组",
"杀组合",
"断组1",
"杀组合1",
"断组2",
"杀组合2",
"组三",
"组六",
];
let flatArray = [];
// 递归遍历树形数据
function traverse(node, parentId = 0) {
const nodeId = getMenuNodeId(node);
const nodeName = getMenuNodeName(node);
const children = getMenuNodeChildren(node);
// 检查当前节点名称是否在排除列表中
if (!nodeId || !nodeName || excludeNames.includes(nodeName)) {
return; // 跳过这个节点及其子节点
}
// 添加当前节点到扁平数组
flatArray.push({
id: nodeId,
pid: parentId,
name: nodeName,
code: node.code || node.lotteryCode || "",
});
// 如果有子节点,递归处理
if (children && Array.isArray(children)) {
children.forEach((child) => {
traverse(child, nodeId);
});
}
}
// 遍历整个树
if (Array.isArray(treeData)) {
treeData.forEach((rootNode) => {
traverse(rootNode, 0);
});
}
return flatArray;
}
function getMenuNodeId(node) {
return node && (node.id || node.menuId || node.value);
}
function getMenuNodeName(node) {
return String(
(node && (node.name || node.menuName || node.title || node.label)) ||
"",
).trim();
}
function getMenuNodeChildren(node) {
return ApiClient.asArray(
node && (node.children || node.childList || node.list),
);
}
function isFixedPublishNav(node) {
const name = getMenuNodeName(node);
const path = String(
(node && (node.path || node.url || node.href)) || "",
).trim();
return (
["首页", "专家推荐"].includes(name) ||
/(^|\/)(index|zhuanjia)\.html/i.test(path)
);
}
function normalizeMenuChildren(node, children) {
node.children = ApiClient.asArray(children);
return node.children;
}
function loadMenuChildrenForNode(node, depth) {
if (!node || depth <= 0) {
return Promise.resolve(node);
}
const existingChildren = getMenuNodeChildren(node);
const menuId = getMenuNodeId(node);
const childrenPromise =
existingChildren.length || !menuId
? Promise.resolve(existingChildren)
: ApiClient.get(ApiClient.API.menuChildren(menuId))
.then(function (res) {
return ApiClient.asArray(
res.data || res.rows || res.records || res.list || res,
);
})
.catch(function () {
return [];
});
return childrenPromise.then(function (children) {
normalizeMenuChildren(node, children);
return Promise.all(
node.children.map(function (child) {
return loadMenuChildrenForNode(child, depth - 1);
}),
).then(function () {
return node;
});
});
}
function preparePayPublishMenuTree(navList) {
const lotteryList = ApiClient.asArray(navList).filter(function (item) {
return !isFixedPublishNav(item);
});
return Promise.all(
lotteryList.map(function (item) {
return loadMenuChildrenForNode(item, 2);
}),
).then(function () {
return lotteryList;
});
}
// 初始化期号数据
function initIssueData(data) {
// 从原始数据中提取期号信息
data.forEach((lottery) => {
const lotteryId = getMenuNodeId(lottery);
if (lottery.lotteryResult && lottery.lotteryResult.expect) {
qishuok[lotteryId] = lottery.lotteryResult.expect;
} else if (lottery.expect || lottery.issue) {
qishuok[lotteryId] = lottery.expect || lottery.issue;
}
});
console.log("期号数据:", qishuok);
}
function formatPayMoney(value) {
return Number(value || 0).toFixed(2) + "元";
}
function updatePayTitleCount() {
const value = $("#payTitle").val() || "";
$("#payTitleCount").text(value.length + "/100");
}
$(document).on("input", "#payTitle", updatePayTitleCount);
function initNumberSelector(config) {
stepsConfig = Array.isArray(config) ? config : [];
selections = Array(stepsConfig.length).fill(null);
updateNumberSelectorUI();
}
function initNumberPool() {
const numberPool = document.getElementById("numberPool");
if (!numberPool) {
return;
}
numberPool.innerHTML = "";
if (!stepsConfig.length) {
return;
}
stepsConfig.forEach(function (step, stepIndex) {
const stepContainer = document.createElement("div");
stepContainer.className = "mianfeiThreeTextRedballBox";
stepContainer.innerHTML = `
${step.name}(选择 ${step.requiredCount} 个)
`;
numberPool.appendChild(stepContainer);
renderStepNumbers(step, stepIndex);
});
}
function renderStepNumbers(step, stepIndex) {
const stepNumberPool = document.getElementById("step-" + stepIndex);
if (!stepNumberPool || !Array.isArray(step.numberRange)) {
return;
}
step.numberRange.forEach(function (number) {
const text =
number !== "" && !isNaN(Number(number)) && Number(number) < 10
? "0" + Number(number)
: String(number);
const numberElement = document.createElement("div");
numberElement.className = step.class;
numberElement.textContent = text;
numberElement.dataset.number = text;
numberElement.dataset.step = stepIndex;
const currentSelection = selections[stepIndex] || { numbers: [] };
if (
currentSelection.numbers.includes(normalizeSelectedNumber(text))
) {
numberElement.classList.add(step.classok);
}
numberElement.addEventListener("click", function () {
toggleNumberSelection(numberElement, step.classok);
});
stepNumberPool.appendChild(numberElement);
});
}
function normalizeSelectedNumber(value) {
const text = String(value);
return text !== "" && !isNaN(Number(text)) ? Number(text) : text;
}
function toggleNumberSelection(numberElement, selectedClass) {
const stepIndex = Number(numberElement.dataset.step);
const number = normalizeSelectedNumber(numberElement.dataset.number);
const step = stepsConfig[stepIndex];
const currentSelection = selections[stepIndex] || { numbers: [] };
if (!step) {
return;
}
if (numberElement.classList.contains(selectedClass)) {
numberElement.classList.remove(selectedClass);
currentSelection.numbers = currentSelection.numbers.filter(
function (item) {
return item !== number;
},
);
} else {
if (!step.allowMultiple) {
clearStepSelection(stepIndex, selectedClass);
currentSelection.numbers = [];
}
if (
step.allowMultiple &&
currentSelection.numbers.length >= step.requiredCount
) {
showNumberMessage(
"本步骤最多只能选择 " + step.requiredCount + " 个数字",
);
return;
}
numberElement.classList.add(selectedClass);
currentSelection.numbers.push(number);
}
selections[stepIndex] = currentSelection;
showFinalResult();
}
function clearStepSelection(stepIndex, selectedClass) {
document
.querySelectorAll('[data-step="' + stepIndex + '"]')
.forEach(function (element) {
element.classList.remove(selectedClass);
});
}
function showFinalResult() {
xzok(selections);
}
function resetNumberSelector() {
const doReset = function () {
selections = Array(stepsConfig.length).fill(null);
updateNumberSelectorUI();
};
if (layui.layer) {
layui.layer.confirm(
"确定要重置所有选择吗?",
{ icon: 3, title: "提示" },
function (index) {
doReset();
layui.layer.close(index);
},
);
return;
}
doReset();
}
function updateNumberSelectorUI() {
initNumberPool();
showFinalResult();
}
function showNumberMessage(message) {
if (layui.layer) {
layui.layer.msg(message);
return;
}
console.warn(message);
}
$(document).on("click", "#resetBtn", resetNumberSelector);
function renderPayPublishOptions(data) {
currentPayPublishOptions = data || {};
currentPayPicker = currentPayPublishOptions.picker || null;
const issue = currentPayPublishOptions.issue || $("#qi").val() || "";
const code = currentPayPublishOptions.code || "";
$("#qi").val(issue);
$("#qihao").text(issue || "--");
$("#expectInput").val(issue || "");
$("#expectText").text(issue || "选择方案后自动获取");
$("#payCode").val(code);
$("#priceInput").val(currentPayPublishOptions.priceCount1 || 0);
$("#priceText").text(currentPayPublishOptions.priceCount1 || 0);
const priceLines = [
"价格:" +
formatPayMoney(currentPayPublishOptions.priceCount1) +
",服务费:" +
formatPayMoney(currentPayPublishOptions.priceCount1Cost),
];
if (
currentPayPublishOptions.pointDeduction != null ||
currentPayPublishOptions.pointMaxDeduction != null
) {
priceLines.push(
"积分抵扣:" +
(currentPayPublishOptions.pointDeduction || 0) +
",最多:" +
formatPayMoney(currentPayPublishOptions.pointMaxDeduction),
);
}
$("#payPriceInfo").html(priceLines.join("
"));
applyPayPickerConfig(currentPayPicker);
}
function normalizePayBallValue(value) {
const text = String(value);
return text !== "" && !isNaN(Number(text)) ? Number(text) : text;
}
function applyPayPickerConfig(picker) {
const groups = Array.isArray(picker && picker.groups)
? picker.groups
: [];
if (!groups.length || typeof initNumberSelector !== "function") {
return;
}
const apiStepsConfig = groups.map(function (group) {
const min = Number(group.minSelect || 0);
const max = Number(group.maxSelect || min || 1);
return {
name: group.name || group.key || "号码选择",
numberRange: ApiClient.asArray(group.balls).map(
normalizePayBallValue,
),
allowMultiple: max > 1,
class: group.color === "blue" ? "Blueball" : "Redball",
classok: group.color === "blue" ? "BlueSelected" : "selected",
requiredCount: max,
minSelect: min,
maxSelect: max,
joiner: group.joiner,
key: group.key,
sortSelected: group.sortSelected,
};
});
initNumberSelector(apiStepsConfig);
}
function validatePayPickerSelection(currentSelections) {
if (!currentPayPicker || !Array.isArray(currentPayPicker.groups)) {
return true;
}
for (let index = 0; index < currentPayPicker.groups.length; index++) {
const group = currentPayPicker.groups[index];
const selected =
currentSelections[index] &&
Array.isArray(currentSelections[index].numbers)
? currentSelections[index].numbers
: [];
const min = Number(group.minSelect || 0);
const max = Number(group.maxSelect || min);
if (selected.length < min || selected.length > max) {
layer.alert(
(group.name || "当前分组") +
"需要选择" +
(min === max ? min : min + "-" + max) +
"个",
);
return false;
}
}
return true;
}
function buildPayPredictedCode(currentSelections) {
if (!currentPayPicker || !Array.isArray(currentPayPicker.groups)) {
return $("#vv").val();
}
const groups = currentPayPicker.groups;
const defaultJoiner = currentPayPicker.joiner || ",";
const groupJoiner = currentPayPicker.groupJoiner || "+";
const groupTexts = groups.map(function (group, index) {
let values =
currentSelections[index] &&
Array.isArray(currentSelections[index].numbers)
? currentSelections[index].numbers.slice()
: [];
if (group.sortSelected) {
values.sort(function (a, b) {
return Number(a) - Number(b);
});
}
return values.join(group.joiner || defaultJoiner);
});
if (currentPayPicker.mode === "positions") {
if (groupJoiner === "-") {
return groupTexts.filter(Boolean).join("-");
}
const lastGroup = groups[groups.length - 1];
if (
lastGroup &&
lastGroup.key === "special" &&
groupTexts.length > 1
) {
const front = groupTexts
.slice(0, -1)
.filter(Boolean)
.join(defaultJoiner);
const last = groupTexts[groupTexts.length - 1];
return [front, last].filter(Boolean).join(groupJoiner);
}
return groupTexts.filter(Boolean).join(defaultJoiner);
}
return groupTexts.filter(Boolean).join(groupJoiner);
}
function loadPayPublishOptions(menuId) {
currentPayPublishOptions = null;
currentPayPicker = null;
$("#payMenuId").val(menuId || "");
$("#payCode").val("");
$("#qi").val("");
$("#qihao").text("正在生成当前期号...");
$("#expectInput").val("");
$("#expectText").text("正在生成当前期号...");
$("#priceInput").val("");
$("#priceText").text(0);
$("#payPriceInfo").text("正在加载价格说明...");
if (!menuId) {
$("#qihao").text("请选择类型后自动生成");
$("#expectText").text("选择方案后自动获取");
$("#payPriceInfo").text("请选择方案后加载价格说明");
return Promise.resolve(null);
}
return ApiClient.get(ApiClient.API.payArticlePublishOptions(menuId))
.then(function (res) {
if (!ApiClient.isSuccess(res)) {
throw new Error(res.msg || "发布前置信息加载失败");
}
renderPayPublishOptions(res.data || {});
return res.data || {};
})
.catch(function (error) {
currentPayPublishOptions = null;
currentPayPicker = null;
$("#qi").val("");
$("#qihao").text("当前期号生成失败");
$("#expectInput").val("");
$("#expectText").text("选择方案后自动获取");
$("#priceInput").val("");
$("#priceText").text(0);
$("#payPriceInfo").text("发布前置信息加载失败");
$(".mianfeiThreeText").hide();
$(".mianfeiThreeButBox").hide();
layui.layer.msg(error.message || "发布前置信息加载失败", {
icon: 2,
});
throw error;
});
}
//console.log(qishuok);
function clearLotterySelection() {
selectedLotteryPath = [];
selectedLotteryIds = [];
currentPayPublishOptions = null;
currentPayPicker = null;
$("#a1,#a2,#a3,#qi,#vv,#payMenuId,#payCode").val("");
$("#payTitle").val("");
$("#payTitleCount").text("0/100");
$("#expectInput").val("");
$("#priceInput").val("");
$("#priceText").text(0);
$("#expectText").text("选择方案后自动获取");
$("#qihao").text("请选择方案");
$("#payPriceInfo").text("请选择方案后加载价格说明");
$("#gmjl").closest(".selectY-box").removeClass("is-selected");
$(".mianfeiThreeText").hide();
$(".mianfeiThreeButBox").hide();
initNumberSelector([]);
}
function initLayuiComponents() {
layui.use(["form", "selectY2", "notice"], function () {
var form = layui.form,
notice = layui.notice,
layer = layui.layer,
selectY2 = layui.selectY2,
$ = layui.$;
const $mianfeiThreeText = $(".mianfeiThreeText");
const $mianfeiThreeButBox = $(".mianfeiThreeButBox");
let xzid = 0;
let ob = selectY2({
elem: "#gmjl",
data: gmjldata,
//url为ajax 获取json数据,当url属性有值时,不提取data属性值
//url:'https://cityApi.html',
placeholder: "请选择方案",
disabledTips: "请选择",
allowClear: true,
clearText: "×",
clear: clearLotterySelection,
success: function (e) {
console.log(e.data);
console.log(e.ids);
console.log(qishuok[e.ids[0]], "zuijinqishu");
//
$("#qi").val("");
$("#qihao").text("正在生成当前期号...");
selectedLotteryPath = e.data || [];
selectedLotteryIds = e.ids || [];
$("#gmjl").closest(".selectY-box").addClass("is-selected");
$("#a1").val(selectedLotteryIds[0] || "");
$("#a2").val(selectedLotteryIds[1] || "");
$("#a3").val(selectedLotteryIds[selectedLotteryIds.length - 1] || "");
xzid = selectedLotteryIds[selectedLotteryIds.length - 1];
$("#payMenuId").val(xzid);
var ttt = e.data;
$mianfeiThreeText.hide();
$mianfeiThreeButBox.hide();
initNumberSelector([]);
loadPayPublishOptions(xzid)
.then(function (options) {
const groups =
options &&
options.picker &&
Array.isArray(options.picker.groups)
? options.picker.groups
: [];
if (!groups.length) {
currentPayPublishOptions = null;
currentPayPicker = null;
layui.layer.msg("后端未返回选号配置,请检查发布前置接口", {
icon: 2,
});
return;
}
$mianfeiThreeText.show();
$mianfeiThreeButBox.show();
})
.catch(function () {});
},
});
});
}
function chk() {
if (isSubmittingPayArticle) {
return false;
}
const menuId = layui.$("#payMenuId").val();
const qi = layui.$("#qi").val();
const title = layui.$("#payTitle").val().trim();
const code = layui.$("#payCode").val().trim() || "-";
if (!menuId) {
layer.alert("请选择发布方案");
return false;
}
if (!currentPayPublishOptions) {
layer.alert("发布前置信息还没有加载完成,请重新选择方案");
return false;
}
if (
!currentPayPicker ||
!Array.isArray(currentPayPicker.groups) ||
!currentPayPicker.groups.length
) {
layer.alert("后端未返回选号配置,请重新选择方案");
return false;
}
if (!title) {
layer.alert("请输入文章标题");
return false;
}
if (!qi) {
layer.alert("当前期号不能为空");
return false;
}
if (!validatePayPickerSelection(selections)) {
return false;
}
const vv = buildPayPredictedCode(selections);
layui.$("#vv").val(vv);
if (!vv) {
layer.alert("请选择号码");
return false;
}
isSubmittingPayArticle = true;
layui.$(".mianfeiThreeBut").text("发布中...").prop("disabled", true);
checkPaidPublishPermission()
.then(function (permission) {
if (!permission.canPaid) {
throw new Error(permission.reason || "暂无付费文章发布权限。");
}
return ApiClient.post(ApiClient.API.payArticlePublish, {
parentId: menuId,
code: code,
title: title,
predictedCode: vv,
issue: Number(qi),
});
})
.then(function (res) {
if (!ApiClient.isSuccess(res)) {
throw new Error(res.msg || "发布失败");
}
layer.msg("发布成功", { icon: 1, time: 1200 }, function () {
window.location.href = "usercenter.html";
});
})
.catch(function (error) {
layer.msg(error.message || "发布失败", { icon: 2 });
})
.finally(function () {
isSubmittingPayArticle = false;
layui.$(".mianfeiThreeBut").text("发布方案").prop("disabled", false);
});
return false;
}
function formatSelectedBallText(value) {
const text = String(value);
return text !== "" && !isNaN(Number(text)) && Number(text) < 10
? "0" + Number(text)
: text;
}
function isSelectionComplete(currentSelections) {
if (!stepsConfig.length) {
return false;
}
return stepsConfig.every(function (step, index) {
const selected =
currentSelections[index] &&
Array.isArray(currentSelections[index].numbers)
? currentSelections[index].numbers
: [];
const min = Number(step.minSelect || step.requiredCount || 0);
const max = Number(step.maxSelect || step.requiredCount || min);
return selected.length >= min && selected.length <= max;
});
}
function xzok(selections) {
const $jieguo = $("#jieguo");
const selectedGroups = [];
selections.forEach(function (selection, index) {
const step = stepsConfig[index] || {};
const numbers =
selection && Array.isArray(selection.numbers)
? selection.numbers
: [];
if (!numbers.length) {
return;
}
const selectedClass = step.classok || "selected";
const balls = numbers
.map(function (number) {
return (
'' +
CommonUtil.escapeHtml(formatSelectedBallText(number)) +
"
"
);
})
.join("");
selectedGroups.push(
'' + balls + "
",
);
});
if (selectedGroups.length) {
$jieguo.html(
'' +
selectedGroups.join('|') +
"
",
);
} else {
$jieguo.text("暂无号码");
}
layui.$("#vv").val(buildPayPredictedCode(selections));
}