api.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. (function (window) {
  2. 'use strict';
  3. // Logger Utility
  4. const Logger = {
  5. _isDev: false,
  6. init: function(isDev) {
  7. this._isDev = isDev;
  8. },
  9. log: function() {
  10. if (this._isDev) {
  11. console.log.apply(console, arguments);
  12. }
  13. },
  14. warn: function() {
  15. if (this._isDev) {
  16. console.warn.apply(console, arguments);
  17. }
  18. },
  19. error: function() {
  20. console.error.apply(console, arguments); // Always log errors
  21. }
  22. };
  23. // Determine _isDev status from main window's URL query params
  24. function getQueryParam(name) {
  25. const params = new URLSearchParams(window.location.search);
  26. return params.get(name);
  27. }
  28. const env = (getQueryParam('env') || '').toLowerCase();
  29. Logger.init(env === 'mock'); // Initialize Logger
  30. /**
  31. * ColorMapRun API SDK (Full Version with Mock)
  32. * 封装了与后端服务器的所有交互
  33. * 依赖: bridge.js (用于 401 跳转登录)
  34. */
  35. // 基础配置
  36. var Config = {
  37. baseUrl: 'https://colormaprun.com/api/card/',
  38. ossUrl: 'http://oss-card.colormaprun.com/card/',
  39. token: '',
  40. useMock: false
  41. };
  42. // 模拟数据定义 (涵盖所有接口)
  43. var MOCK_DB = {
  44. 'CardBaseQuery': {
  45. ecName: '[Mock]跑向大明湖卡片',
  46. ecDesc: '欢迎参加彩图奔跑活动!',
  47. beginSecond: Date.now() / 1000 - 86400 * 5,
  48. endSecond: Date.now() / 1000 + 86400 * 10,
  49. secondCardName: '地图导航'
  50. },
  51. 'CardDetailQuery': {
  52. mcId: 101,
  53. mcName: '[Mock]线上马拉松',
  54. mcType: 1,
  55. beginSecond: Date.now() / 1000 - 86400 * 2,
  56. endSecond: Date.now() / 1000 + 86400 * 5,
  57. teamNum: 0,
  58. coiId: 1, // Mocked coiId
  59. coiName: '个人组',
  60. ocaId: 201 // Mocked ocaId
  61. },
  62. 'MatchRsDetailQuery': [
  63. { id: 1, name: '[Mock]活动1', status: 1 },
  64. { id: 2, name: '[Mock]活动2', status: 0 }
  65. ],
  66. 'CardRankDetailQuery': {
  67. totalRankRs: [
  68. { nickName: 'Mock张三', score: 10000, headUrl: 'https://picsum.photos/40/40?random=1', rankNum: 1 },
  69. { nickName: 'Mock李四', score: 9500, headUrl: 'https://picsum.photos/40/40?random=2', rankNum: 2 },
  70. { nickName: 'Mock王五', score: 8800, headUrl: 'https://picsum.photos/40/40?random=3', rankNum: 3 },
  71. { nickName: 'Mock赵六', score: 7200, headUrl: 'https://picsum.photos/40/40?random=4', rankNum: 4 },
  72. { nickName: 'Mock小明', score: 6500, headUrl: 'https://picsum.photos/40/40?random=5', rankNum: 5 }
  73. ],
  74. teamRankRs: [],
  75. inTeamRs: [],
  76. otherRs: []
  77. },
  78. 'UserCurrentRankNumQuery': { rankNum: 5 },
  79. 'UserJoinCardQuery': { isJoin: false }, // 默认未报名
  80. 'IsNewUserInCardComp': { isNew: true },
  81. 'OnlineMcSignUpDetail': {
  82. teamList: [
  83. { teamId: 1, teamName: '[Mock]个人组' },
  84. { teamId: 2, teamName: '[Mock]团队组' }
  85. ],
  86. signupFields: [
  87. { name: 'realName', label: '真实姓名', type: 'text', required: true, value: '' },
  88. { name: 'phone', label: '手机号码', type: 'tel', required: true, value: '' }
  89. ]
  90. },
  91. 'OnlineMcSignUp': {}, // 报名成功返回空 data
  92. 'IsAllowMcSignUp': { allowSignUp: true },
  93. 'CurrentMonthlyChallengeQuery': {
  94. year: '2023',
  95. monthRs: [{ month: 11, realNum: 10, targetNum: 20 }]
  96. },
  97. 'CardConfigQuery': {
  98. configJson: JSON.stringify({
  99. css: ".custom-header { background-color: #f0f8ff; }",
  100. tabActiveColor: "#007bff",
  101. teamType: 0, // Mocked teamType
  102. popupRuleConfig: { height: "60%", theme: "light" },
  103. popupMessageConfig: {}, // Mocked popupMessageConfig
  104. popupRuleList: [
  105. { type: 1, data: { title: '规则1', content: '这是<b>Mock</b>的活动规则内容。' } },
  106. { type: 1, data: { title: '规则2', content: '第二条规则。', logo: { src: 'https://picsum.photos/100/50', width: '100px', height: '50px' } } }
  107. ],
  108. popupDataList: [ // Mocked popupDataList
  109. { type: 1, data: { title: '通用弹窗1', content: '通用弹窗内容1。' } }
  110. ]
  111. })
  112. },
  113. 'UserConfigQuery': {
  114. configJson: JSON.stringify({
  115. tplInfo: { tplTypeId: 1, ssctId: 1 },
  116. mapInfo: [
  117. { activityList: [{ showName: '迷你路线', pathImg: '', ocaId: 1, matchType: 1, point: { longitude: 117.0, latitude: 36.6, name: '起点' } }] }
  118. ],
  119. popupRuleList: [{ type: 1, data: { title: '用户个性化', content: '这是用户专属内容' } }]
  120. })
  121. },
  122. 'MonthlyChallengeQuery': [
  123. { year: '2023', monthRs: [{ month: 10, realNum: 15, targetNum: 20 }] },
  124. { year: '2022', monthRs: [{ month: 12, realNum: 25, targetNum: 20 }] }
  125. ],
  126. 'MonthRankDetailQuery': [
  127. { nickName: '月榜冠军', score: 500, headUrl: 'https://picsum.photos/40/40?random=6' }
  128. ],
  129. 'AchievementQuery': [
  130. {
  131. year: '2023',
  132. aiRs: [
  133. { aiName: '初次登场', aiTime: Date.now() / 1000 - 86400 * 30, iconUrl: 'https://picsum.photos/60/60?random=7' },
  134. { aiName: '跑步达人', aiTime: Date.now() / 1000 - 86400 * 10, iconUrl: 'https://picsum.photos/60/60?random=8' }
  135. ]
  136. }
  137. ],
  138. 'ExchangeListQuery': [
  139. { exchangeId: 1, goodsName: '[Mock]运动手环', createTime: Date.now() / 1000 - 86400 * 7, status: 1 },
  140. { exchangeId: 2, goodsName: '[Mock]定制水杯', createTime: Date.now() / 1000 - 86400 * 15, status: 0 }
  141. ],
  142. 'ExchangeDetailQuery': {
  143. exchangeId: 1, goodsName: '[Mock]运动手环', createTime: Date.now() / 1000 - 86400 * 7, status: 1,
  144. address: 'Mock地址', receiver: 'Mock收件人', phone: '138****8888'
  145. },
  146. 'UnReadMessageQuery': [
  147. { mqId: 1, mqType: 1, mqTitle: '[Mock]新成就', mqMessage: '恭喜您解锁新成就!', iconUrl: 'https://picsum.photos/50/50?random=9' }
  148. ],
  149. 'ReadMessage': {},
  150. 'MapListQuery': [
  151. { mapId: 1, mapName: '[Mock]公园地图', latitude: 36.6, longitude: 117.0, activityList: [] }
  152. ],
  153. 'CompStatisticQuery': { totalDistance: 123.45, totalPeople: 1000 },
  154. 'WarnMessageQuery': [
  155. { warnType: 1, warnTitle: '[Mock]黄牌警告', warnMessage: '您的成绩异常', iconUrl: 'https://picsum.photos/50/50?random=10' }
  156. ],
  157. 'CertStyleQuery': {
  158. styleId: 1, styleName: '简约风', templateUrl: 'https://picsum.photos/600/400?random=11',
  159. elements: [
  160. { type: 'text', field: 'userName', x: 100, y: 150, fontSize: 24, color: '#333' }
  161. ]
  162. },
  163. 'UserBaseQueryInCertificate': { userName: '[Mock]证书用户', activityName: '[Mock]活动名', completionTime: Date.now() / 1000 },
  164. 'CertificateCreateByUserAi': { certUrl: 'https://picsum.photos/600/400?random=12' },
  165. 'OnlineScoreQuery': { score: 880, extTime: Date.now() / 1000 + 86400 * 30 },
  166. 'CanExchangeGoodsList': [
  167. { goodsId: 1, goodsName: '[Mock]运动手环', goodsPic: 'https://picsum.photos/100/100?random=13', goodsLeftNum: 50, corrScore: 500 },
  168. { goodsId: 2, goodsName: '[Mock]定制水杯', goodsPic: 'https://picsum.photos/100/100?random=14', goodsLeftNum: 0, corrScore: 300 }
  169. ],
  170. 'CanExchangeGoodsDetail': {
  171. goodsId: 1, goodsName: '[Mock]运动手环', goodsPic: 'https://picsum.photos/200/200?random=15', corrScore: 500,
  172. desc: '这是<b>Mock</b>的运动手环详情,功能强大,是您运动的好伙伴!'
  173. },
  174. 'ScoreExchangeGoods': {},
  175. 'UserBasicInformationQuery': { nickName: 'Mock用户', headUrl: 'https://picsum.photos/50/50?random=16' },
  176. 'GridsQuery': {
  177. compId: 201, compName: '[Mock]网格挑战', widthNum: 3, heightNum: 3,
  178. maskImgPic: 'https://picsum.photos/300/300?random=17',
  179. actualImgPic: 'https://picsum.photos/300/300?random=18',
  180. state: 2, // 1:未开始 2:进行中 3:已结束
  181. detailRs: [
  182. { orderNum: 1, isComplete: 1, showName: '完成1', relationType: 1, ocaId: 10, longitude: 117.1, latitude: 36.6, popupImg: 'https://picsum.photos/100/100?random=19' },
  183. { orderNum: 2, isComplete: 0, showName: '未完2', relationType: 1, ocaId: 11, longitude: 117.2, latitude: 36.7, popupImg: 'https://picsum.photos/100/100?random=20' }
  184. ]
  185. },
  186. 'CardUriQuery': {}, // 暂无 Mock 结构
  187. 'MatchFinishInfoQuery': {}, // 暂无 Mock 结构
  188. 'RedisRebuild': {} // 暂无 Mock 结构
  189. };
  190. var API = {
  191. init: function(options) {
  192. if (options.baseUrl) Config.baseUrl = options.baseUrl;
  193. if (options.ossUrl) Config.ossUrl = options.ossUrl;
  194. if (options.token) Config.token = options.token;
  195. if (typeof options.useMock === 'boolean') Config.useMock = options.useMock;
  196. if (Config.useMock) Logger.warn('%c [API] Mock 模式已开启 ', 'background: orange; color: white;');
  197. },
  198. getOssUrl: function() {
  199. return Config.ossUrl;
  200. },
  201. setToken: function(token) {
  202. Config.token = token;
  203. },
  204. request: function(endpoint, data) {
  205. if (Config.useMock) {
  206. return new Promise(function(resolve, reject) {
  207. Logger.log('[API-Mock] Request:', endpoint, data);
  208. setTimeout(function() {
  209. var mockData = MOCK_DB[endpoint];
  210. if (endpoint === 'OnlineMcSignUp') MOCK_DB['UserJoinCardQuery'].isJoin = true;
  211. if (endpoint === 'ScoreExchangeGoods') MOCK_DB['OnlineScoreQuery'].score -= 100;
  212. Logger.log('[API-Mock] Response:', endpoint, mockData || {});
  213. resolve(mockData || {});
  214. }, 300);
  215. });
  216. }
  217. var url = Config.baseUrl + endpoint;
  218. var headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'token': Config.token };
  219. var formData = new URLSearchParams();
  220. for (var key in data) { if (data.hasOwnProperty(key)) formData.append(key, data[key]); }
  221. Logger.log('[API] Request:', endpoint, data);
  222. return fetch(url, { method: 'POST', headers: headers, body: formData, mode: 'cors', credentials: 'omit' })
  223. .then(function(response) { return response.json(); })
  224. .then(function(res) {
  225. Logger.log('[API] Response:', endpoint, res);
  226. if (res.code === 0) return res.data;
  227. if (res.code === 401 || res.statusCode === 401) {
  228. Logger.warn('[API] Token invalid');
  229. if (window.Bridge && window.Bridge._post) window.Bridge._post('toLogin');
  230. else alert('登录已过期');
  231. throw new Error('Unauthorized');
  232. }
  233. var msg = res.message || '请求失败';
  234. if (window.Bridge && window.Bridge.showToast) {
  235. window.Bridge.showToast(msg, 'none');
  236. } else {
  237. alert(msg);
  238. }
  239. throw new Error(msg);
  240. })
  241. .catch(function(err) { Logger.error('[API] Error:', err); throw err; });
  242. },
  243. // ==============================
  244. // 完整业务接口封装 (按原始 api.js 顺序)
  245. // ==============================
  246. // 1. 卡片基本信息查询
  247. getCardBase: function(ecId, pageName) { return this.request('CardBaseQuery', { ecId: ecId, pageName: pageName }); },
  248. // 2. 卡片对应活动或赛事详情查询
  249. getCardDetail: function(ecId) { return this.request('CardDetailQuery', { ecId: ecId }); },
  250. // 3. 卡片对应线上赛多个活动查询
  251. getMatchRsDetail: function(ecId) { return this.request('MatchRsDetailQuery', { ecId: ecId }); },
  252. // 4. 排名查询
  253. getRankDetail: function(mcIdListStr, mcType, dispArrStr) { return this.request('CardRankDetailQuery', { mcIdListStr: mcIdListStr, mcType: mcType, dispArrStr: dispArrStr }); },
  254. // 5. 卡片用户当前排名查询
  255. getUserCurrentRank: function(ecId) { return this.request('UserCurrentRankNumQuery', { ecId: ecId }); },
  256. // 6. 用户是否已经报名卡片对应赛事查询
  257. getUserJoinStatus: function(ecId) { return this.request('UserJoinCardQuery', { ecId: ecId }); },
  258. // 7. 用户在卡片对应赛事是否新用户
  259. isNewUserInCardComp: function(ecId) { return this.request('IsNewUserInCardComp', { ecId: ecId }); },
  260. // 8. 线上赛报名页面信息详情
  261. getOnlineMcSignUpDetail: function(ecId) { return this.request('OnlineMcSignUpDetail', { ecId: ecId }); },
  262. // 9. 线上赛报名(重新分组)
  263. signUpOnline: function(mcId, coiId, selectTeam, nickName) {
  264. return this.request('OnlineMcSignUp', { mcId: mcId, coiId: coiId, selectTeam: selectTeam, nickName: nickName });
  265. },
  266. // 10. 是否允许重新分组(报名)
  267. isAllowMcSignUp: function(ecId) { return this.request('IsAllowMcSignUp', { ecId: ecId }); },
  268. // 11. 玩家当前月挑战记录查询
  269. getCurrentMonthlyChallenge: function() { return this.request('CurrentMonthlyChallengeQuery', {}); },
  270. // 12. 卡片配置信息查询
  271. getCardConfig: function(ecId, pageName) { return this.request('CardConfigQuery', { ecId: ecId, pageName: pageName }); },
  272. // 13. 用户自定义配置信息查询
  273. getUserConfig: function(ecId, pageName) { return this.request('UserConfigQuery', { ecId: ecId, pageName: pageName }); },
  274. // 14. 玩家所有月挑战记录查询
  275. getMonthlyChallenge: function() { return this.request('MonthlyChallengeQuery', {}); },
  276. // 15. 月挑战排名查询
  277. getMonthRankDetail: function() { return this.request('MonthRankDetailQuery', {}); },
  278. // 16. 玩家活动成就查询
  279. getAchievement: function() { return this.request('AchievementQuery', {}); },
  280. // 17. 玩家兑换记录查询
  281. getExchangeList: function(ecId) { return this.request('ExchangeListQuery', { ecId: ecId }); },
  282. // 18. 玩家兑换详情查询
  283. getExchangeDetail: function(ecId, exchangeId) { return this.request('ExchangeDetailQuery', { ecId: ecId, exchangeId: exchangeId }); },
  284. // 19. 未读消息列表查询
  285. getUnReadMessages: function(relationId, relationType) { return this.request('UnReadMessageQuery', { relationId: relationId, relationType: relationType || 2 }); },
  286. // 20. 标记消息已读
  287. readMessage: function(mqIdListStr) { return this.request('ReadMessage', { mqIdListStr: mqIdListStr }); },
  288. // 21. 卡片对应地图列表详情查询
  289. getMapList: function(ecId) { return this.request('MapListQuery', { ecId: ecId }); },
  290. // 22. 赛事总成绩统计查询
  291. getCompStatistic: function(ecId) { return this.request('CompStatisticQuery', { ecId: ecId }); },
  292. // 23. 警告列表查询
  293. getWarnMessage: function(ecId) { return this.request('WarnMessageQuery', { ecId: ecId }); },
  294. // 24. 查询电子证书样式
  295. getCertStyle: function(ecId) { return this.request('CertStyleQuery', { ecId: ecId }); },
  296. // 25. 查询电子证书成就对应用户基本信息
  297. getUserBaseInCertificate: function(ecId) { return this.request('UserBaseQueryInCertificate', { ecId: ecId }); },
  298. // 26. 根据成就信息确认生成电子证书
  299. createCertificate: function(data) { return this.request('CertificateCreateByUserAi', data); },
  300. // 27. 卡片内可用积分查询
  301. getScore: function(ecId) { return this.request('OnlineScoreQuery', { ecId: ecId }); },
  302. // 28. 积分可兑换商品列表查询
  303. getGoodsList: function(ecId) { return this.request('CanExchangeGoodsList', { ecId: ecId }); },
  304. // 29. 积分可兑换商品详情
  305. getGoodsDetail: function(goodsId) { return this.request('CanExchangeGoodsDetail', { goodsId: goodsId }); },
  306. // 30. 积分兑换商品
  307. exchangeGoods: function(ecId, goodsId) { return this.request('ScoreExchangeGoods', { ecId: ecId, goodsId: goodsId }); },
  308. // 31. 用户基本信息查询
  309. getUserInfo: function() { return this.request('UserBasicInformationQuery', {}); },
  310. // 32. 网格卡片信息查询
  311. getGrids: function(ecId) { return this.request('GridsQuery', { ecId: ecId }); },
  312. // 33. 卡片URI查询
  313. getCardUri: function(ecId) { return this.request('CardUriQuery', { ecId: ecId }); },
  314. // 34. 赛事完赛信息查询
  315. getMatchFinishInfo: function(ecId) { return this.request('MatchFinishInfoQuery', { ecId: ecId }); },
  316. // 35. Redis 重建 (管理接口)
  317. redisRebuild: function(ecId) { return this.request('RedisRebuild', { ecId: ecId }); }
  318. };
  319. window.API = API;
  320. })(window);