@xybplugins/xyb-agent 0.0.26 → 0.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1,3271 @@
1
- const e=(e="",t="",i="log",n="")=>{const o={error:"错误",warn:"警告",info:"提示",log:"日志"}[i]||"日志",a=JSON.stringify(n);console.log(`\n=============🚀START - V${k} 🚀=============\n【事件名称】:${e} \n【日志类型】:${o} \n【日志信息】:${t} ${"error"===i?`【错误信息】:${JSON.stringify(a)}`:""} \n==============🚀END🚀==============`),console.log("")},t=(t={})=>{if("function"==typeof t)return e("deepClone","数据类型为function,无法执行深拷贝,请检查","error"),t;try{return JSON.parse(JSON.stringify(t))}catch(i){return e("deepClone","执行数据深拷贝异常","error",i),t}},i=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),n=(e={},t={})=>{for(let i in e)t[i]=e[i]},o=(t=!1)=>{let i={route:null,path:null,options:{}};try{const e="function"==typeof getCurrentPages?getCurrentPages():[],n=[];for(let t in e)n.push({route:e[t].route,path:e[t].$page?.fullPath,options:e[t].$page?.options});const o=n?.length||0;if(o){const e=n[o-1],a=n[o-2];i=(t?a:e)||{}}}catch(t){e("getCurrentPagePath","获取页面信息失败","error",t)}return i},a=e=>{try{return JSON.parse(e)}catch(t){return e}},s=(t={},i={})=>{let n=i;try{n=a(i)}catch(t){e("formatResponseData","格式化失败","error",t),n=i}t(n)},r=e=>null==e,c=(e="",t="")=>{let i=t||window?.location?.href;if(i=decodeURIComponent(i),i?.includes(e)){let t=i.split(`${e}=`)[1];return t?.includes("&")&&(t=t.split("&")[0]),t}return""},l=(e="",t="")=>{if(e)return new Promise(t=>{const i=document.createElement("script");i.src=e,i.onload=t,document.head.appendChild(i)})},u=(t,i)=>{window?.my?.navigateTo({url:t,fail:t=>{e("openAlipayMiniApp","跳转失败,请检查配置信息","error",t),i({code:-1,isSuccess:!1,message:"跳转失败,请检查配置信息"})}})},d=(t,i)=>{window?.wx?.miniProgram?.navigateTo({url:t,fail:t=>{e("executeAuthFaceInBrowser","跳转失败,请检查配置信息","error",t),i({code:-1,isSuccess:!1,message:"跳转失败,请检查配置信息"})}})};let m={finished:!1,result:!1},g={finished:!1,result:!1},h={finished:!1,result:!1},v={finished:!1,result:!1};const p=()=>w()?navigator.userAgent.toLowerCase():"",f=()=>{const e=p();return/android/i.test(e)?"android":/iphone|ipad|ipod|mac/i.test(e)&&!window.MSStream?"ios":/windows phone/i.test(e)?"windows":"harmony"},w=()=>window&&document,y=()=>{if(v.finished)return v.result;if(v.finished=!0,!w())return v.result=!1,!1;const t=p();return v.result=t.includes("uni-app"),e("checkIsMiniAppBrowserEnv",`当前是否为小程序的浏览器环境:${v.result}`),v.result},N=()=>{const{finished:t,result:i}=m;return t?i:(m.result=(()=>{if(h.finished)return h.result;if(h.finished=!0,!w())return h.result=!1,!1;const t=p();return h.result=t.includes("xybwebcomponent")||t.includes("uni-app"),e("checkIsXybBrowserEnv",`当前是否为湘易办浏览器环境:${h.result}`),h.result})()||y(),m.finished=!0,e("checkIsWebviewEnv",`当前是否为Webview环境:${m.result}`),m.result)},S=()=>{const{finished:t,result:i}=g;if(t)return i;if(g.finished=!0,!w())return g.result=!1,!1;const n=p();return g.result=n.includes("xybwebcomponent")&&!n.includes("uniminiapp"),e("checkIsAppWebviewEnv",`当前是否为APP的Webview环境:${g.result}`),g.result},C=()=>w()?p().includes("micromessenger"):"mp-weixin"===f(),I=()=>w()?p().includes("alipay"):"mp-alipay"===f(),M=()=>!!uni&&(!!uni.sendNativeEvent&&("function"==typeof uni.sendNativeEvent||"undefined"!=typeof uni&&Object.prototype.hasOwnProperty.call(uni,"sendNativeEvent"))),E=()=>window?.uni&&"function"==typeof window?.uni?.webView?.postMessage,A=()=>"function"==typeof window?.wx?.chooseImage,$=()=>"function"===Boolean(window?.my)?.chooseImage,b=(t,i)=>{const n=52.35987755982988,o=t-.0065,a=i-.006,s=Math.sqrt(o*o+a*a)-2e-5*Math.sin(a*n),r=Math.atan2(a,o)-3e-6*Math.cos(o*n),c=s*Math.cos(r).toFixed(6),l=s*Math.sin(r).toFixed(6);return e("BaiduToGCJ02",`已完成百度坐标系转换成国测坐标系的转换,转换后的值:lng:${c}, lat:${l}`),{lng:c,lat:l}},D=(t,i)=>{let n=null;try{n=Math.PI}catch(t){e("wgsToGCJ02","获取PI值失败","error",t)}if(o=i,(a=t)<72.004||a>137.8347||o<.8293||o>55.8271)return{lat:i,lon:t};var o,a;const s=6378245,r=.006693421622965943,c=((e,t)=>{let i=2*e-100+3*t+.2*t*t+.1*e*t+.2*Math.sqrt(Math.abs(e));return i+=2*(20*Math.sin(6*e*Math.PI)+20*Math.sin(2*e*Math.PI))/3,i+=2*(20*Math.sin(t*Math.PI)+40*Math.sin(t/3*Math.PI))/3,i+=2*(160*Math.sin(t/12*Math.PI)+320*Math.sin(t*Math.PI/30))/3,i})(t-105,i-35),l=((e,t)=>{let i=300+e+2*t+.1*e*e+.1*e*t+.1*Math.sqrt(Math.abs(e));return i+=2*(20*Math.sin(6*e*Math.PI)+20*Math.sin(2*e*Math.PI))/3,i+=2*(20*Math.sin(e*Math.PI)+40*Math.sin(e/3*Math.PI))/3,i+=2*(150*Math.sin(e/12*Math.PI)+300*Math.sin(e/30*Math.PI))/3,i})(t-105,i-35),u=i/180*Math.PI;let d=Math.sin(u);d=1-r*d*d;const m=Math.sqrt(d),g=i+180*c/(s*(1-r)/(d*m)*Math.PI),h=t+180*l/(s/m*Math.cos(u)*Math.PI);return{lat:parseFloat(g.toFixed(8)),lng:parseFloat(h.toFixed(8))}},x=t=>{const{dinateType:i,lat:n,lng:o,address:a}=t;if(e("replaceCoordinate",`坐标转换开始:${i}`,"log"),"BD09"===i){const e=b(o,n);return{destinationName:a,destinationLongitude:e?.lng,destinationLatitude:e?.lat}}if("WGS84"===i){const e=D(o,n);return{destinationName:a,destinationLongitude:e?.lng,destinationLatitude:e?.lat}}return e("replaceCoordinate",`坐标系转换异常,未在匹配规则内,传递的坐标系类型:${i}`,"log"),{destinationLatitude:t?.lat||"",destinationLongitude:t?.lng||"",destinationName:t?.address||"",dinateType:t?.dinateType||"",address:t?.address||"",name:t?.name||""}},P=[{isCustomEv:!0,eventName:"authFace",uniEvName:"Auth_face",description:"人脸识别功能",nativeEvName:"faceAuth",reqDataFormat:t=>{e("authFace",`执行人脸验证,参数信息:${JSON.stringify(t)}`);const{name:i,certNo:n,appId:o,sign:a,created:s,nonce:r}=t;return i&&n&&o&&a&&s&&r?t:(e("authFace","缺少必要参数:name, certNo, appId, sign, created, nonce","error","缺少必要参数"),!1)},resDataFormat:e=>({isSuccess:Boolean(e),certifyId:e}),resErrorFormat:e=>"harmony"===f().toLowerCase()?{isSuccess:!1,errorMsg:e}:e},{isCustomEv:!0,eventName:"startNavigation",uniEvName:"Start_navigation",description:"目的地导航",nativeEvName:"start_navigation",reqDataFormat:t=>{let i={};const{dinateType:n,lat:o,lng:a,address:s,destinationLatitude:r,destinationLongitude:c}=t;return r&&c?t:(e("replaceCoordinate",`坐标系值:LAT:${o},LNG:${a}`,"log"),i=n&&"GCJ02"!==n?x(t):{destinationLatitude:o,destinationLongitude:a,destinationName:s},e("replaceCoordinate",`转换后值:LAT:${i.destinationLatitude},LNG:${i.destinationLongitude}`,"log"),i)}},{isWindowEv:!0,eventName:"getLoginStatus",uniEvName:"Auth_checkLogin",description:"获取登录状态",nativeEvName:"CallNativeMethodGetUserInfo",resDataFormat:e=>{const i=t(e);return{logined:1===Number(i?.isLogin)}},resErrorFormat:()=>({logined:!1})},{isWindowEv:!0,eventName:"getLoginUserInfo",uniEvName:"Auth_getUserInfo",description:"获取登录用户数据信息",nativeEvName:"CallNativeMethodGetUserInfo",resDataFormat:e=>t(e),resErrorFormat:()=>({isSuccess:!1})},{isCustomEv:!0,eventName:"getAuthToken",uniEvName:"Auth_getToken",description:"获取授权token",nativeEvName:"get_token",resDataFormat:e=>{try{const i=t(e);return{token:i?.token,isSuccess:Boolean(i?.token)}}catch(t){return{token:e?.token,isSuccess:Boolean(e?.token)}}},resErrorFormat:()=>({isSuccess:!1})},{isWindowEv:!0,eventName:"getAccessLink",uniEvName:"Auth_getAccessLink",nativeEvName:"CallNativeMethodGetAccessLink",description:"获取授权链接",resDataFormat:e=>"ios"===f().toLowerCase()?{isSuccess:!0,accessLink:e}:t(e),resErrorFormat:()=>({isSuccess:!1})},{moduleName:"image",eventName:"chooseImg",uniEvName:"Image_choose",nativeEvName:"chooseImage",browserEvName:"chooseImage",description:"选择本地图片",reqDataFormat:e=>{const{count:t,sizeType:i,sourceType:n,isCircleCrop:o}=e||{};return{count:t||9,sizeType:i||["original","compressed"],sourceType:n||["album"],isCircleCrop:o||!1}},resDataFormat:e=>t(e),bResDataFormat:e=>{const{tempFiles:t}=e,i=[];for(let e in t){const{name:n,path:o,size:a,type:s}=t[e];i.push({name:n,path:o,size:a,type:s})}return{resultObj:i,isSuccess:!0,message:"选择图片功能操作完成"}}},{moduleName:"image",eventName:"imgPreview",uniEvName:"Image_preview",nativeEvName:"previewImage",browserEvName:"previewImage",description:"执行图片预览"},{moduleName:"image",eventName:"imgUpload",uniEvName:"Image_upload",nativeEvName:"uploadImage",description:"执行图片上传",resDataFormat:e=>t(e),resErrorFormat:e=>e},{eventName:"imgDownload",uniEvName:"Image_download",nativeEvName:"",browserEvName:"downloadImage",description:"执行图片下载"},{eventName:"fileUpload",uniEvName:"File_upload",nativeEvName:"",description:"执行文件上传"},{moduleName:"file",eventName:"fileDownload",uniEvName:"File_download",nativeEvName:"downloadFile",description:"执行文件下载",resDataFormat:e=>({isSuccess:Boolean(e),resultObj:{path:e}})},{moduleName:"file",eventName:"filePreview",uniEvName:"File_preview",nativeEvName:"previewFile",description:"执行文件预览"},{moduleName:"file",eventName:"openLocalFile",uniEvName:"File_openLocal",nativeEvName:"openLocalFile",description:"执行打开本地文件"},{moduleName:"file",eventName:"chooseLocalFile",uniEvName:"File_chooseLocal",nativeEvName:"chooseLocalFile",browserEvName:"chooseFile",description:"选择本地文件",resDataFormat:e=>t(e)},{moduleName:"file",eventName:"openThirdFile",uniEvName:"File_openThirdParty",nativeEvName:"openFileWithThirdParty",description:"执行打开第三方文件"},{eventName:"openApp",uniEvName:"Util_openApp",nativeEvName:"",description:"打开APP"},{isCustomEv:!0,eventName:"openXybApp",uniEvName:"Util_openXYBMiniApp",nativeEvName:"jumpToMiniApp",description:"打开湘易办融合APP小程序",reqDataFormat:e=>{if(S()){const{pageUrl:t}=e;return{...e,path:t}}return e}},{eventName:"postMsgToOtherApp",uniEvName:"Util_postMessageToXYBMiniApp",nativeEvName:"",description:"发送消息给其他小程序"},{isWindowEv:!0,eventName:"scanCode",uniEvName:"Scan_code",description:"扫描二维码",browserEvName:"scanQRCode",nativeEvName:"CallNativeMethodScanQRCode",resDataFormat:e=>({text:e}),bReqDataFormat:e=>({...e,needResult:1}),bResDataFormat:e=>({text:e?.resultStr||""})},{moduleName:"system",eventName:"getAppInfo",nativeEvName:"getAppInfo",description:"获取应用信息",uniEvName:"System_getAppInfo",resDataFormat:e=>t(e)},{moduleName:"util",eventName:"copyToClipboard",uniEvName:"Util_clipboardData",nativeEvName:"clipboardData",description:"复制内容到剪切板",reqDataFormat:e=>({text:e}),resDataFormat:e=>S()?{isSuccess:Boolean(e)}:{isSuccess:!0}},{moduleName:"util",eventName:"getCacheSize",uniEvName:"Util_getCacheSize",nativeEvName:"getCacheSize",description:"获取缓存大小",resDataFormat:e=>t(e)},{moduleName:"util",eventName:"clearCache",uniEvName:"Util_clearCache",nativeEvName:"clearCache",description:"执行缓存清除",resDataFormat:()=>({isSuccess:!0}),resErrorFormat:()=>({isSuccess:!1})},{moduleName:"telephone",eventName:"callPhone",uniEvName:"Util_callDesignateNumber",nativeEvName:"call",description:"拨打电话",browserEvName:"makePhoneCall",reqDataFormat:e=>"object"==typeof a(e)?a(e):S()?{phoneCode:"+86",phoneNumber:String(e).replace("+86","")}:{text:e}},{eventName:"forbidScreenShot",uniEvName:"Util_forbidScreenShot",nativeEvName:"",description:"执行禁止截屏"},{eventName:"setScreenLight",uniEvName:"Util_setScreenLight",nativeEvName:"",description:"设置屏幕是否常亮",reqDataFormat:e=>({idleTimerValue:e})},{eventName:"sendMatterId",uniEvName:"Param_MatterID",nativeEvName:"",description:"执行页面事件ID上报",reqDataFormat:e=>({matterID:e})},{isWindowEv:!0,description:"获取位置信息",eventName:"getLocationInfo",uniEvName:"Util_getLocationInformation",nativeEvName:"CallNativeMethodGetLocationInformation",resDataFormat:e=>{const{location:i,data:n}=e;let o=t(e);return i&&(o=t(e?.location)),n&&(o=t(e?.data)),f().toLowerCase(),{isSuccess:!0,location:o}},nativeResFormat:e=>{const{location:i,data:n}=e;let o=t(e);return i&&(o=t(e?.location)),n&&(o=t(e?.data)),{isSuccess:!0,location:o}},resErrorFormat:()=>({isSuccess:!1,location:{}})},{eventName:"checkPermission",uniEvName:"Auth_matterHandleAuthority",nativeEvName:"",description:"检查事项权限",reqDataFormat:e=>({matterCode:e})},{eventName:"showComment",uniEvName:"Util_jumpToComment",nativeEvName:"",description:"打开评价弹窗"},{isWindowEv:!0,description:"打开微信小程序",eventName:"openWechatMiniApp",uniEvName:"Util_openWechatMiniProgram",nativeEvName:"CallNativeMethodJumpToWechatMiniProgram",reqDataFormat:e=>{if(S()){const t={};for(let i in e)t[i]=String(e[i]);return JSON.stringify(t)}return e}},{isWindowEv:!0,description:"打开支付宝小程序",eventName:"openAliPayMiniApp",uniEvName:"Util_openAlipayMiniProgram",nativeEvName:"CallNativeMethodJumpToAliPay",reqDataFormat:e=>S()?JSON.stringify(e):e},{eventName:"showMenuPanel",uniEvName:"menu_present",nativeEvName:"",description:"显示菜单面板"},{isCustomEv:!0,eventName:"addCalendarEvent",uniEvName:"Util_addCalendarEvent",nativeEvName:"addCalendarEvent",description:"添加日历日程"},{isCustomEv:!0,eventName:"deleteCalendarEvent",uniEvName:"Util_deleteCalendarEvent",nativeEvName:"deleteCalendarEvent",description:"删除日历日程"},{isCustomEv:!0,eventName:"queryCalendarEvent",uniEvName:"Util_queryCalendarEvent",nativeEvName:"queryCalendarEvent",description:"查询日历日程"}],k="0.0.26",F={custom(t,i){e("custom",`通过custom调用${t}事件`);const n=P?.find(e=>e?.nativeEvName===t||e?.eventName===t);return new Promise((e,o)=>{const{reqDataFormat:a}=n||null,s=n||{isCustomEv:!0,moduleName:"custom",eventName:"call",description:"通过Custom调用的C2事件",nativeEvName:t};if(!S())return void e({code:-1,msg:"非APP环境的Webview环境,不支持该功能"});const r=a?a(i):i;this.executeSendMsgToApp({moduleName:"custom",eventName:"call",actionName:t,isCustomEv:!0,dataInfo:r,resolveInfo:e,evConfig:s})})}},O=e=>Number(e)>9?e:`0${e}`,L=()=>{const e=new Date;return`${e.getFullYear()}-${O(e.getMonth()+1)}-${O(e.getDate())} ${O(e.getHours())}:${O(e.getMinutes())}:${O(e.getSeconds())}`},T={trackStack:[],anaSDKLoadTimes:0,locationInfo:{},isProdEnv:!1,track(t="",n={}){if(t){if(n)return w()&&!this.anaSDKInit?(this.trackStack.push({id:i(),eventID:t,eventPro:n}),void e("track","埋点上报插件初始化未完成,本次数据在插件初始化后自动上报","log")):void this.executeTrack(t,n);e("track","埋点数据上报失败","error","请传入埋点数据")}else e("track","埋点数据上报失败","error","请传入埋点事件")},async executeTrack(t="",i={}){if("object"==typeof t)return void await this.track(t?.eventID,t?.eventPro);const n=await this.initTrackParams(i);if(e("track",`执行埋点数据上报,事件名称:${t},事项编码:${n.code},是否上报到生产环境:${this.isProdEnv},完整埋点数据:${JSON.stringify(n)}`,"log"),w()&&xybAgent?.AnalysysAgent)return e("track","通过浏览器插件执行埋点数据上报","log"),void window.xybAgent.AnalysysAgent.track(t,n);if(M())try{e("track",`埋点数据:${JSON.stringify(n)},埋点ID:${t}`,"log"),uni.sendNativeEvent("Analysis_common",{eventID:t,eventPro:n})}catch(t){e("track","执行数据埋点功能异常","error",t)}},trackSDKInit(t){return new Promise((i,n)=>{w()||(e("initTrack","非浏览器环境无需使用init执行初","error"),i(!0)),this.anaSDKInsert?this.configAnaSDK(t,i):l("https://mobile.zwfw.hunan.gov.cn:8088/AnalysysAgent_JS_SDK.min.js","极光").then(()=>{window.AnalysysAgent&&(xybAgent.AnalysysAgent=window.AnalysysAgent,this.anaSDKInsert=!0,this.configAnaSDK(t,i))})})},configAnaSDK(t,i){const n="800c298f0c42c94c",o="40d556c15f872084";let a=location?.host?.includes("hunan.gov.cn")?n:o;if("object"==typeof t)a=o;else{const e={production:n,development:o},i=[n,o];(e[t]||i.includes(t))&&(a=e[t]?e[t]:t)}this.isProdEnv=a===n,e("configAnaSDK",`配置信息:${JSON.stringify(t)},是否为生产环境:${this.isProdEnv},上报的key值:${a}`),w()?(window.xybAgent.AnalysysAgent&&(window.xybAgent.AnalysysAgent.init({appkey:a,uploadURL:"https://mobile.zwfw.hunan.gov.cn:8088/aurora-api"}),e("configAnaSDK","xybAgent已初始化完成,可正常执行埋点操作","log"),this.anaSDKInit=!0,this.isInit=!0,this.checkTrackStack(),i(!0)),!Boolean(window.xybAgent.AnalysysAgent)&&this.anaSDKLoadTimes<10&&setTimeout(()=>this.trackSDKInit(i),300),!Boolean(window.xybAgent.AnalysysAgent)&&this.anaSDKLoadTimes>=10&&(e("configAnaSDK","xybAgent初始化失败","error","请检查app key、uploadURL是否正确"),i(!1))):i(!1)},async initTrackParams(e={}){const{code:t,name:i,aff_city_code:n,aff_city_name:o,unit_code:a,area_code:s,unit_name:r,is_finish:c,category:l,user_id:u,miniAppCode:d,$url_domain:m}=e,g=this.getVisitSource(),h=this.getPageSource(),v=await this.getPositionInfo();return{code:t||void 0,name:i||void 0,aff_city_code:n||void 0,aff_city_name:o||void 0,unit_code:a||void 0,area_code:s||void 0,unit_name:r||void 0,is_finish:c||void 0,category:l||void 0,user_id:u||void 0,miniAppCode:d||void 0,$url_domain:m||void 0,curr_time:L(),source:g,page_source:h,location:v}},getVisitSource(){if(!w()){const e=uni?.getSystemInfoSync(),{uniPlatform:t}=e||{};return"mp-weixin"===t?"wx":"mp-alipay"===t?"alipay":"app"}return C()?"wx":I()?"alipay":"app"},checkTrackStack(){e("checkTrackStack","执行埋点数据堆栈检测","log");t(this.trackStack).forEach(t=>{const{eventID:i,eventPro:n,id:o}=t;e("checkTrackStack",`执行id值为${o} 的埋点数据再次上报`,"log"),this.track(i,n);const a=this.trackStack.findIndex(e=>e.id===o);a>-1&&this.trackStack.splice(a,1)})},getPageSource(){let e=null;e=w()?location.href:decodeURIComponent(o().path);const t=e?.includes("source=");if(!t)return"click";const i=e.split("source=")[1];let n="click";return n=i.includes("&")?i.split("&")[0]:i,["copy","share","click","search"].includes(n)?n:"click"},async getPositionInfo(){if(!this.locationInfo?.province)try{const{location:e}=await this.getLocationInfo()||{};this.locationInfo=e||""}catch(t){e("getLocationInfo","获取位置信息异常","error",t),this.locationInfo={}}return JSON.stringify(this.locationInfo)}},B={initMobileBridgeGlobalConfig(){const t=f();e("initMobileBridgeGlobalConfig",`开始初始化移动端桥链接配置,访问设备类型:${t}`),window.c2={},"ios"===t&&this.initIOSCallbackEvConfig(),"android"===t&&this.initAndroidCallbackEvConfig(),e("initMobileBridgeGlobalConfig","初始化移动端桥链接配置完成"),window.CreatorJsBridge=window.c2},initIOSCallbackEvConfig(){try{const t=this;window.c2.iOS={},window.c2.iOS.callJS=function(){window?.c2.iOS?.callJSCallback||(window.c2.iOS.callJSCallback={}),e("initIOSCallbackEvConfig",`开始处理IOS设备回调事件,回调数据:${JSON.stringify(arguments)}`),t.IOSCallbackEvFormat(arguments[0])}}catch(t){e("initIOSCallbackEvConfig","初始化IOS回调事件配置异常","error",t)}},initAndroidCallbackEvConfig(){window.c2.sendDataWarpToWeb=(e,t,i)=>{e(i)}},IOSCallbackEvFormat(i){const{returnValue:n,funcName:o}=i;let s=this.base64Decode(n);s=a(s),e("IOSCallbackEvFormat",`IOS设备回调事件处理开始,回调数据:${JSON.stringify(s)}, 格式:${typeof s}`);const r=o.split("_a")[0],c=o.replace(r,""),l=this.iosCallBackList.find(e=>e.id===r);if(!l)return;const{resolveInfo:u,configInfo:d}=l,{resDataFormat:m,resErrorFormat:g}=d;if(c.includes("onFail")&&g)return s=g({isSuccess:!1,errorMsg:t(n)}),void u(s);m&&(s=m(s)),e("IOSCallbackEvFormat",`IOS设备回调事件处理完成,返回数据:${JSON.stringify(s)}`),u(s);const h=this.iosCallBackList.findIndex(e=>e.id===r);this.iosCallBackList.splice(h,1)},base64Decode(e){let t,i,n,o,a,s,r,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l="",u=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");u<e.length;)o=c.indexOf(e.charAt(u++)),a=c.indexOf(e.charAt(u++)),s=c.indexOf(e.charAt(u++)),r=c.indexOf(e.charAt(u++)),t=o<<2|a>>4,i=(15&a)<<4|s>>2,n=(3&s)<<6|r,l+=String.fromCharCode(t),64!=s&&(l+=String.fromCharCode(i)),64!=r&&(l+=String.fromCharCode(n));return l=this._utf8_decode(l),l},_utf8_decode(e){let t="",i=0,n=0,o=0,a=0;for(;i<e.length;)n=e.charCodeAt(i),n<128?(t+=String.fromCharCode(n),i++):n>191&&n<224?(a=e.charCodeAt(i+1),t+=String.fromCharCode((31&n)<<6|63&a),i+=2):(a=e.charCodeAt(i+1),o=e.charCodeAt(i+2),t+=String.fromCharCode((15&n)<<12|(63&a)<<6|63&o),i+=3);return t},checkMobileModuleBack(e,t,i){const n=i?"custom":e,o=`${i?"call":t}Callback`;window.c2.hasOwnProperty(n)||(window.c2[n]={}),window.c2[n].hasOwnProperty(o)||(window.c2[n][o]={})}};let W=null,J=null,_=null;M()?(W=uni&&uni?.requireNativePlugin?uni?.requireNativePlugin("GCUniPlugin-RUM"):null,J=uni&&uni?.requireNativePlugin?uni?.requireNativePlugin("GCUniPlugin-Tracer"):null,_=uni&&uni?.getSystemInfoSync?uni.getSystemInfoSync().platform:null):e("请求插件初始化","未找到uni对象","warn");const q={defaults:{headers:{},baseURL:""},interceptor:{request:null,response:null},requestOb:!1,request(i={}){return new Promise((n,o)=>{let a=t(i);if(!this.interceptor.request||"function"!=typeof this.interceptor.request||i.ignore||(a=this.interceptor.request(i),a))if(M()&&this.requestOb&&Boolean(W)&&Boolean(J))try{e("request","走服务监控平台的请求配置","log"),this.executeCloudObRequest(a,n,o)}catch(t){e("request","走服务监控平台的请求配置失败","error",t)}else e("request","走uni的请求配置","log"),this.executeNormalRequest(a,n,o);else n(!1)})},executeCloudObRequest(t,n,o){let a=i();const s=this.checkCloudObRequestHeader(t,a);if(!s)return;const{traceHeader:c,filter:l}=s;let u,d,m;W.startResource({key:a}),uni.request({url:`${this.defaults.baseURL}${t.url}`,method:t.method,header:c,data:t.data,timeout:t.timeout,withCredentials:t?.withCredentials||void 0,success:i=>{if(e("executeCloudObRequest",`接口:${t.url},请求成功`,"log"),l||(u=i.header,d=i.data.toString(),m=i.statusCode),r(t.success)||t.success(i),this.interceptor.response&&"function"==typeof this.interceptor.response&&!t.ignore){const e=this.interceptor.response(i);return void n(e)}n(i)},fail:i=>{e("executeCloudObRequest",`接口:${t.url},请求失败`,"error",i),l||(d=i?.errMsg),r(t?.fail)||t.fail(i),o(i)},complete:()=>{if(e("executeCloudObRequest",`接口:${t.url},请求完成`,"log"),!l){e("executeCloudObRequest",`无filter配置的数据信息::::key值:${a};URL地址:${t.url};`),W.stopResource({key:a});const i={url:`${this.defaults.baseURL}${t.url}`,httpMethod:t.method,requestHeader:c,responseHeader:u,responseBody:d,resourceStatus:m};W.addResource({key:a,content:i})}Boolean(t?.complete)&&t?.complete()}})},checkCloudObRequestHeader(t,i){let n;r(t?.filterPlatform)?(e("executeCloudObRequest",`options.filterPlatform:${t.filterPlatform}`,"log"),n=!1):(n=t?.filterPlatform?.includes(_),e("executeCloudObRequest",`platform:${t.filterPlatform}`,"log")),e("executeCloudObRequest",`rum:${W},tracer:${J}`,"log");let o={};return n||(o=J?.getTraceHeader({key:i,url:t.url})),e("executeCloudObRequest",`是否读取到【tracer】插件配置:${Boolean(J)},是否读取到【rum】插件配置:${Boolean(W)}`,"log"),W&&J?(o=Object.assign({},o,t.header),o=Object.assign({},o,this.defaults.headers),{traceHeader:o,filter:n}):(e("executeCloudObRequest","请配置服务监控平台原生插件","log"),!1)},executeNormalRequest(t,i,n){const{url:o,header:a,data:s,method:r}=t||{},c=Object.assign({},this.defaults.headers,a);uni.request({url:`${this.defaults.baseURL}${o}`,header:c,data:s,method:r,withCredentials:t?.withCredentials||void 0,success:n=>{if(e("normalRequest",`接口:${o},请求成功`,"log"),this.interceptor.response&&"function"==typeof this.interceptor.response&&!t.ignore){const e=this.interceptor.response(n);return void i(e)}i(n)},fail:t=>{e("normalRequest",`接口:${o},请求异常`,"error",t),n(t)}})}},H={resetMenuBtnConfig(){e("hideNativeBtn","隐藏原生APP分享、评价按钮","log");const t={share:{show:!1},comment:{show:!1},favorite:{show:!0}};try{this.menuBtnConfig(t),this.pageChangeEv(i=>{if(!this.autoUpdate)return void e("resetMenuBtnConfig","业务侧设置不自动重置胶囊按钮,中断配置动作");const{options:n}=i,{xybModuleCode:o}=n||{};if(o&&this.autoConfigMenuBtn)return e("resetMenuBtnConfig",`页面拦截事件生效 自动设置原生APP分享、评价按钮,配置信息:${JSON.stringify(i)}`,"log"),void this.menuBtnConfig({share:{show:!0,code:o,type:4},comment:{show:!0,code:o,type:4},favorite:{show:!0}});e("resetMenuBtnConfig","页面拦截事件生效 自动重置原生APP分享、评价按钮配置信息","log"),this.menuBtnConfig(t)})}catch(t){e("resetMenuBtnConfig","配置APP的胶囊按钮清单显示失败,请检查参数是否正确","error",t)}},pageChangeEv(t){if(!uni)return;["navigateTo","redirectTo","switchTab","reLaunch","navigateBack","onBackPress"].forEach(i=>{try{uni.addInterceptor(i,{invoke(n){try{const{url:a}=n;let s={options:{},path:null,route:null},r=decodeURIComponent(a);s.path=r,s.route=r.split("?")[0],r?.includes("xybModuleCode=")&&(console.log(`🚀当前页面路径信息:${r}`),s.options.xybModuleCode=c("xybModuleCode",r)),r?.includes("?")&&(s.route=r.split("?")[0]),i?.includes("Back")&&(s=o(i?.includes("Back"))),e("pageChangeEv",`页面路径发生了变化,当前页面路径:${s.path}`,"log"),"function"==typeof t&&t(s)}catch(t){console.log("🚀 错误信息:::::",t),e("pageChangeEv","拦截路径变化时发生了异常","error",t)}return!0}})}catch(t){e("pageChangeEv","执行页面变化拦截异常","error",t)}})},menuBtnConfig(t={}){e("menuBtnConfig",`配置APP胶囊按钮清单显示,配置信息:${JSON.stringify(t)}`,"log");let i=!0;for(let n in t){if("object"!=typeof t[n]){i=!1,e("menuBtnConfig","配置参数错误","error","请传入一个Object配置数据");break}}if(i)if(N())this.miniAppH5SendMsgToApp(null,"menuBtnConfig",t,"配置APP的胶囊按钮清单显示");else if(!w()&&uni&&uni?.sendNativeEvent)try{e("menuBtnConfig","开始执行配置APP胶囊按钮清单显示","log"),uni?.sendNativeEvent("Util_MiniAppConfigMenu",t)}catch(t){e("menuBtnConfig","配置APP的胶囊按钮清单显示时发生异常","error",t)}else e("menuBtnConfig","配置APP胶囊按钮清单显示功能无法在非UNI环境运行","log")}},K={executeBrowserEvent(t,i={},n={},o={}){const a=C()?"微信小程序":I()?"支付宝小程序":"浏览器",{eventName:s,description:r,browserEvName:c,bResDataFormat:l,bReqDataFormat:u,reqDataFormat:d}=o,m="startNavigation"===s?n:i;e("normalEvDataTransition",`开始调用${a}嵌套H5的能力,事件名称:${s},入参:${JSON.stringify(m)},配置信息:${JSON.stringify(o)}`);const g={authFace:"executeAuthFaceInBrowser",getLocationInfo:"executeGetLocationInBrowser",startNavigation:"startNavigationInBrowser",fileUpload:"executeFileUploadInBrowser",chooseImg:"executeImageChooseInBrowser"}[s];if(g)return void this[g](t,m,o);if(!c)return void t({isSuccess:!1,code:-1,message:`非常抱歉,${r}功能无法在当前环境中使用`});const h=d?d(i):u?u(i):i;I()||C()?this.executeMPBrowserEvent(t,c,i,s):this.executeNativeBrowserEv(t,c,h,l)},executeMPBrowserEvent(i,n,o,a){e("executeMPBrowserEvent",`配置信息:${JSON.stringify(o)}`);let s=t(o);e("executeMPBrowserEvent",`配置信息:${JSON.stringify(s)}`),s.success=t=>{e("executeMPBrowserEvent",`执行:${a}事件完成,返回结果:${JSON.stringify(t)}`)},s.fail=t=>{e("executeMPBrowserEvent",`执行:${a}事件失败,错误信息:${JSON.stringify(t)}`)},e("executeWeChatBrowserEv",`${a},配置信息:${JSON.stringify(s)}`),C()?window.wx[n](s):window.my[n](s)},executeNativeBrowserEv(e,i){let n=t(i);n.success=function(e){console.log(e)},n.fail=function(e){console.error(e)},window.uni[e](n)}},R={executeAuthFaceInBrowser(t,i={},n={}){const o=function(i){let n=c("faceKey",window?.location?.href);if(e("executeAuthFaceInBrowser",`获取到的faceKey参数值::::${n}`),!window?.location?.href.includes("faceKey"))return;const a={isSuccess:Boolean(n),certifyId:`MINI_${n}`,portrait:null,errorMsg:Boolean(n)?null:"人脸验证失败,请检查参数信息"};window.removeEventListener("hashchange",o),setTimeout(()=>{e("executeAuthFaceInBrowser",`执行验证结果回抛给业务侧:${JSON.stringify(a)}`),t(a)},100)};window.addEventListener("hashchange",o);const a=encodeURIComponent(window.location.href),{certNo:s,name:r}=i;let l=`/pages/sdk/sdk?redirectUrl=${a}&type=authFace&idCard=${encodeURIComponent(s)}&name=${r}`;C()?d(l,t):I()?u(l,t):(e("executeAuthFaceInBrowser","当前环境不支持人脸识别","warning"),t({isSuccess:!1,code:-1,message:"当前环境下不支持人脸识别验证功能"}))}},U={locationCheck:!1,locationEvList:[],checkLocationEvStation(){this.locationEvList.forEach(e=>{this.getLocationInWeChat(e.resolveInfo,e.id)})},executeGetLocationInBrowser(t){e("executeGetLocationInBrowser","在微信/支付宝浏览器中获取定位信息"),I()?this.getLocationInAliPay(t):C()?this.getLocationInWeChat(t):t({code:-1,isSuccess:!1,message:"当前环境无法支持位置信息获取,请检查是否为湘易办相关环境"})},getLocationInWeChat(t,n){return this.weChatConfigReady?this.locationCheck?(e("getLocationInWeChat","已缓存签名信息,直接调用对应API获取位置信息"),void this.executeGetLocationInfoData(t,n)):void this.executeGetLocationInfoData(t,n):(e("getLocationInWeChat","微信SDK尚未初始化完毕,先行进行堆栈,待微信SDK初始化后,统一调用"),void this.locationEvList.push({id:i(),resolveInfo:t}))},executeGetLocationInfoData(t,i){e("executeGetLocationInfoData","在微信环境中获取位置信息"),window?.wx?.getLocation({type:"wgs84",success:e=>{this.locationCheck=!0;const i=D(e?.longitude,e?.latitude);t({isSuccess:!0,location:{longitude:i?.longitude,latitude:i?.latitude},message:"微信小程序下只提供经纬度"})},fail:i=>{t({isSuccess:!1,message:"调用微信获取位置信息失败,请联系管理员"}),e("executeGetLocationInfoData",`调用微信获取位置信息失败,信息是:${JSON.stringify(i)}`)}})},executeGetDetailLocation(t,i,n,o=!1){const a=i?.latitude,s=i?.longitude;uni.request({url:`https://api.map.baidu.com/reverse_geocoding/v3/?ak=fensaAMmxRxkRCadisCyAvZpwj6YCwtD&output=json&coordtype=wgs84ll&location=${a},${s}`,method:"GET",success:i=>{const{data:a}=i?.data||{};e("executeGetDetailLocation",`位置信息结果:${JSON.stringify(a)}`),a?.longitude||t(this.formatLocationData(a,o));const s=this.formatLocationData(a,o);if(t(s),n){e("executeGetDetailLocation",`已成功获取到定位信息,清除该事件的堆栈:${n}`);const t=this.locationEvList.findIndex(e=>e.id===n);-1!==t&&this.locationEvList.splice(t,1)}},fail:t=>{e("executeGetDetailLocation","获取位置信息失败","error",JSON.stringify(t))}})},formatLocationData(t={},i=!1){const n=t?.result||{},{lng:o,lat:a}=n?.location||{},{cityCode:s,formatted_address:r}=n||{},{district:c,city:l,country:u,adCode:d,province:m}=n?.addressComponent||{};console.log("formatLocationData",`是否为支付宝调用:${i}`);const g=i?n?.location:b(o,a),h={isSuccess:!0,location:{district:c,city:l,longitude:g?.lng,country:u,cityCode:s,adCode:d,address:r,latitude:g?.lat,province:m}};return e("executeGetDetailLocation",`获取位置信息调用完成,结果:${JSON.stringify(h)}`),h},getLocationInAliPay(i){window?.my?.getLocation({type:"wgs84",success:e=>{t(e),i({isSuccess:!0,location:{longitude:e?.longitude,latitude:e?.latitude},message:"支付宝小程序只提供经纬度"})},fail:t=>{e("getLocationInAliPay","获取位置信息失败","error",t),i({code:-1,isSuccess:!1,message:"获取位置信息失败"})}})}},G={executeImageChooseInBrowser(t,i,n){const{count:o,sizeType:a,sourceType:s}=i,{bResDataFormat:r}=n;if(C()||I()){const i={count:o||9,mediaType:["image"],sizeType:a||["original","compressed"],sourceType:s||["album"],success:i=>{i?.success&&t(r?r(i):i),e("executeChooseImageInWeChat",`微信/支付宝环境下执行选择图片API执行完毕,结果:${JSON.stringify(i)}`)},fail:t=>{e("executeChooseImageInWeChat",`微信/支付宝环境下执行选择图片API执行失败,结果:${JSON.stringify(t)}`)}};return void(I()?window.my.chooseImage(i):window.wx.chooseImage(i))}t({isSuccess:!1,code:-1,message:"目前环境暂不支持,敬请期待"})}},j={navigationCheck:!1,startNavigationInBrowser(t,i={}){const n=encodeURIComponent(window?.location?.href),{lat:o,lng:a,address:s,name:r,dinateType:c}=i;let l=`/pages/sdk/sdk?redirectUrl=${n}&type=navigation&latitude=${o}&longitude=${a}&address=${s}&name=${r}`;if(c&&"GCJ02"!==c){const e=x(i),{destinationLatitude:t,destinationLongitude:o}=e;l=`/pages/sdk/sdk?redirectUrl=${n}&type=navigation&latitude=${t}&longitude=${o}&address=${s}&name=${r}`}e("startNavigationInBrowser",`跳转目标URL:${l}`),C()?d(l,t):I()?u(l,t):(e("startNavigationInBrowser","导航功能无法在当前环境下执行"),t({isSuccess:!1,code:-1,message:"导航功能无法在当前环境下执行,请检查是否为微信/支付宝小程序的浏览器环境中"}))}},z={wvInfo:null,isHarmony:!1,isCheckDevice:!1,async initMessage(...t){const i=t[0];await this.checkDeviceInfo(),await this.initVMInfo(t[2]),w()?window.addEventListener("message",t=>{e("initMessage",`浏览器webview接收到的消息内容,${JSON.stringify(t)}`,"log"),this.getMsgFromH5(t)}):(e("initMessage",`非浏览器中的webview接收到的消息内容,${JSON.stringify(i)}`,"log"),this.getMsgFromH5(i))},checkDeviceInfo(){this.isCheckDevice||(this.isCheckDevice=!0,uni.sendNativeEvent("System_getAppInfo",{},e=>{this.isHarmony=e?.platform?.toLowerCase().includes("harmony")}))},initVMInfo(t){if(!this.wvInfo)if(this.isHarmony)this.wvInfo=uni.createWebviewContext("webview",t);else try{this.wvInfo=t,t?.$scope?.$getAppWebview()&&(this.wvInfo=t.$scope.$getAppWebview().children()[0])}catch(t){e("initMessage","初始化消息模块,是否包含wvInfo:"+typeof this.wvInfo?.evalJS)}},getMsgFromH5(t={}){let i=this.getMsgDataFromH5(t);const{origin:n}=t||{},{href:o}=location||{};if(w()&&o?.includes(n))return!1;const{isH5Send:a,methodName:s,methodData:r}=i||{};return!!a&&(s?null==r?(e("getMsgFromH5","请传入需要执行的事件数据","warn"),!1):(e("getMsgFromH5",`需要执行的事件名称【${s}】,需要执行的事件数据【${JSON.stringify(r)}】,是否为H5发送的消息【${a}】`,"log"),void(this[s]?this.executeH5MethodName(s,i):e("getMsgFromH5",`【${s}】事件不存在`,"warn"))):(e("getMsgFromH5","请传入需要执行的事件名称","warn"),!1))},executeH5MethodName(t,i){const{msgId:n,methodData:o}=i;try{const i=this[t].toString();if(e("executeH5MethodName",`【${t}】方法定义:${i}`,"log"),i.includes("Promise"))return void this[t](o).then(i=>{e("executeH5MethodName",`${t}方法执行结果:${JSON.stringify(i)}`,"log");let o=i;try{o=JSON.parse(i)}catch(t){e("executeH5MethodName","强制给数据进行序列化失败","error",t)}this.postMsgToH5({msgId:n,sourceMethod:t,resultInfo:o,isWebviewSend:!0,resultMessage:`执行${t}方法完成`})}).catch(i=>{e("executeH5MethodName",`${t}方法执行失败`,"error",i),this.postMsgToH5({msgId:n,sourceMethod:t,resultInfo:null,isWebviewSend:!0,resultMessage:`执行${t}方法失败,具体错误信息,请查看控制台`})});this[t](o),this.postMsgToH5({msgId:n,sourceMethod:t,resultInfo:null,isWebviewSend:!0,resultMessage:`执行${t}方法完成`})}catch(i){e("getMsgFromH5",`${t}方法执行失败`,"error",i)}},postMsgToH5(t){const i=JSON.stringify(t);if(e("postMsgToH5",`消息内容:${i}`,"log"),w()){e("postMsgToH5","父页面运行在浏览器","log");document.querySelector("iframe").contentWindow.postMessage(JSON.stringify(i),"*")}else try{e("postMsgToH5","父页面运行在非浏览器","log"),this.wvInfo.evalJS(`getMessageFromWebview('${i}')`)}catch(t){e("postMsgToH5","执行浏览器的webview回传异常","error",t)}},getMsgDataFromH5(t){let i=null;const{data:n}=t;try{i=w()?n?.data?.arg?n?.data?.arg:n?.data?n.data:n:t.detail?.data[0]}catch(t){return e("getMsgDataFromH5","处理消息内容时发生异常","error",t),!1}return e("getMsgDataFromH5",`获取到的消息内容:${JSON.stringify(i)}`,"log"),i}},V=(t,i,n)=>{if(e("_parseFunction",`${JSON.stringify(t)}`),"function"==typeof t)return n[i]=t,void(t="[Function]::"+i);if("object"!=typeof t)return;let o=null;for(let e in t)switch(typeof t[e]){case"object":o=i?i+"_"+e:e,V(t[e],o,n);break;case"function":o=i?i+"_"+e:e,n[o]=t[e],t[e]="[Function]::"+o}},Q=e=>{let t=0;return"string"==typeof e?t=1:"number"==typeof e?t=2:"boolean"==typeof e?t=3:"function"==typeof e?t=4:e instanceof Array?t=6:"object"==typeof e&&(t=5),t},X={appH5SendMsgToApp(e,t={},i={}){const{isWindowEv:n,moduleName:o,nativeEvName:a,isCustomEv:s}=t;if(n)return void this.h5SendMsgToAppByWindow(e,t,i);const r=s?"custom":o,c=s?"call":a;this.executeSendMsgToApp({resolveInfo:e,moduleName:r,eventName:c,actionName:a,dataInfo:i,isCustomEv:s,evConfig:t})},executeSendMsgToApp(i={}){const{moduleName:n,eventName:o,actionName:a,dataInfo:s,resolveInfo:r,isCustomEv:c,evConfig:l}=i||{},{description:u}=l,d=this;try{let i={};if(("object"==typeof s?Object.keys(s):[]).length>0&&(i=t(s)),c){const n=t(i);e("webviewSendMsgToApp",`${u}功能在是通过custom.call的方式调用,需要重新处理入参`),i.params=n,i.action=a}e("webviewSendMsgToApp",`${u}的完整参数:${JSON.stringify(i)}`),this.initEventCallbackEv(r,i,l);const m=function(){return d.formatBridgeData(window.c2[n][`${o}Callback`],arguments)}(i);e("webviewSendMsgToApp",`${u}功能在${f()}的Webview环境下执行,调用参数:${JSON.stringify(m)}`),this.h5SendMsgToAppByBrowser(r,l,m)}catch(t){console.log(`🚀发送消息给APP出现错误,错误信息:${t},${JSON.stringify(t)}`),e("webviewSendMsgToApp",`${u}执行数据处理失败`,"error",t)}},initEventCallbackEv(i,n,o={}){const{description:a,resDataFormat:s,resErrorFormat:r}=o;n.onSuccess=function(t){e("webviewSendMsgToApp",`${a}功能在App的Webview环境下执行完成`),i(s?s(t):t)},n.onFail=function(n){const o=t(n);e("webviewSendMsgToApp",`${a}功能在App的Webview环境下执行失败,收到的回调数据:::${JSON.stringify(o)}`),i(r?r(o):s?s(o):o)}},formatBridgeData(t,i){try{const n=Math.random().toString(32).slice(2),o=[];for(let e in i){const a=n+"_a"+e,s=i[e],r={};!1===/OpenHarmony ([5-9])|OpenHarmony (\d{2})/i.test(navigator.userAgent)&&V(s,a,r);for(let e in r)t[e]=r[e],this.C2ReceiveQueue.push(t);o.push({type:Q(s),name:a,value:s})}return e("formatBridgeData",`格式化后的参数:${JSON.stringify(o)}`),{params:o,id:n}}catch(t){e("formatBridgeData","消息通讯数据格式化异常","error",t)}},h5SendMsgToAppByWindow(t,i={},n={}){const{nativeEvName:o,description:s,resDataFormat:r}=i,c=f(),l=`${o}Back`;let u=n;e("h5SendMsgToAppByWindow",`给【${c}】APP发送【${s}】-【${o}】事件调用,回调函数名称:【${l}】`,"log"),window[l]=i=>{let n=i;e("h5SendMsgToAppByWindow",`收到【${c}】APP发送的${s}事件调用的回调值:${JSON.stringify(n)},回调数据类型::${typeof n}`,"log"),n=a(n),t(r?r(n):n)},setTimeout(()=>{"ios"!==c.toLowerCase()?"android"!==c.toLowerCase()?window.harmony[o](u):window.android[o](u):window.webkit.messageHandlers[o].postMessage(u)},100)},h5SendMsgToAppByBrowser(t,i={},n={}){const o=f();e("h5SendMsgToAppByBrowser",`给【${o}】APP发送【${i.nativeEvName}】事件调用,入参:${JSON.stringify(n)}`,"log");const{nativeEvName:a,moduleName:s,isCustomEv:r}=i,{id:c,params:l}=n;if("android"!==o)return"ios"===o?(this.iosCallBackList.push({id:c,resolveInfo:t,configInfo:i}),void this.h5SendMsgToIOS(c,s,a,l,r)):void("harmony"===o&&this.h5SendMsgToHarmony(c,s,a,l,r));this.h5SendMsgToAndroid(c,s,a,l,r)},h5SendMsgToAndroid(t,i,n,o,a){const s={id:t,module:a?"custom":i,method:a?"call":n,parameters:o};return e("h5SendMsgToAndroid",`发送给安卓APP的消息:${JSON.stringify(s)}`),JSON.parse(window.AndroidFunction.callAndroidFun(JSON.stringify(s)))},h5SendMsgToIOS(t,i,n,o,a){const s={id:t,module:a?"custom":i,method:a?"call":n,parameters:o};return e("h5SendMsgToIOS",`发送给IOS APP的消息:${JSON.stringify(s)}`),JSON.parse(prompt(JSON.stringify(s)))},h5SendMsgToHarmony(t,i,n,o,a){const s={id:t,module:a?"custom":i,method:a?"call":n,parameters:o};return e("h5SendMsgToHarmony",`发送给鸿蒙APP的消息:${JSON.stringify(s)}`),JSON.parse(window.harmonyFunction.callHarmonyFun(s))}},Y={msgList:[],msgStack:[],async miniAppH5SendMsgToApp(t,i,n){try{e("miniAppH5SendMsgToApp",`发送消息给webview:${i}`,"log");const o=await this.sendMsgToMiniApp({methodName:i,methodData:n});t(o?.resultInfo)}catch(n){e("miniAppH5SendMsgToApp",`执行${i}失败`,"error",n),t({isSuccess:!1,message:"执行事件失败,详情查看控制台"})}},sendMsgToMiniApp(t){return new Promise((n,o)=>{e("postMsgToWebview",`消息内容:${JSON.stringify(t)}`,"log");const{methodName:a,methodData:s}=t||{};if(!a)return void e("postMsgToWebview","请传入要调用的事件名称","warn");if(!s)return void e("postMsgToWebview","请传入要调用事件的数据信息","warn");const r=i(),c={data:{msgId:r,isH5Send:!0,...t}};if(this.msgList.push({id:r,resolveInfo:n,rejectInfo:o}),e("postMsgToWebview",`发送消息给父容器页面:${JSON.stringify(c)}`,"log"),!this.uniSDKInit)return e("postMsgToWebview","SDK尚未初始化完成,先行执行堆栈","log"),void this.msgStack.push({id:i(),msgContent:c,resolve:n,reject:o});uni?.webView?.postMessage?uni.webView.postMessage(c):uni?.postMessage(c)}).catch(t=>{e("postMsgToWebview","发生异常","error",t)})}},Z={getMessageFromWebview(t,i=!1){let n={};try{n=i?t:t?.data||"{}",n=a(n)}catch(t){e("getMessageFromWebview","解析数据异常","error",t)}if(e("getMessageFromWebview",`是否为webview发送的消息内容:${n?.isWebviewSend},消息内容:${JSON.stringify(n)}`,"log"),!n?.isWebviewSend)return;const{msgId:o}=n,s=this.msgList.findIndex(e=>e.id===o);if(-1===s)return;const r=this.msgList[s],{resolveInfo:c}=r;c(n),this.msgList.splice(s,1)}},ee=["getLoginUserInfo","getAuthToken"];let te=new class{version="";isInit=!1;isWebviewPage=!1;anaSDKInit=!1;uniSDKInit=!1;weChatInit=!1;alipayInit=!1;iosCallBackList=[];C2ReceiveQueue=[];autoUpdate=!0;autoConfigMenuBtn=!0;weChatConfigReady=!1;constructor(e,t){this.version=e,this.isInit=!1,this.isWebviewPage=t,this.iosCallBackList=[],this.initModuleMethod(),this.initSDKAPI(),this.initDefaultConfig()}initModuleMethod(){n(F,this),n(T,this),n(B,this),n(q,this),n(K,this),n(U,this),n(H,this),n(z,this),n(G,this),n(X,this),n(R,this),n(j,this),n(Z,this),n(Y,this)}init(t){e("init","SDK初始化任务执行处理"),w()?(N()&&this.initWebviewMsgFormat(),this.initSDKScriptFile(),this.trackSDKInit(t)):e("init","当前环境非浏览器环境,无需执行初始化动作","warn")}initSDKScriptFile(){e("initSDKScriptFile","挂载第三方SDK脚本文件"),this.initUNISDK(),C()?this.initWeChatSDK():this.initAliPaySDK()}initWebviewMsgFormat(){e("initWebviewMsgFormat","初始化被嵌套的页面消息通讯","log"),w()?(window.addEventListener("message",t=>{e("initWebviewMsgFormat","浏览器消息处理","log"),this.getMessageFromWebview(t)}),window.getMessageFromWebview=t=>{e("initWebviewMsgFormat","事件注入消息处理","log"),this.getMessageFromWebview(t,!0)}):e("initWebviewMsgFormat","该API仅支持在被webview嵌套的H5页面中使用","error","")}initUNISDK(){w()&&(E()||l("https://mobile.zwfw.hunan.gov.cn:8088/uni.webview.1.5.6.js","UNI").then(()=>{E()&&(this.uniSDKInit=!0,e("initUNISDK","UNI Webview SDK 挂载完成"))}))}initWeChatSDK(){if(e("initWeChatSDK","初始化weChat SDK"),w())return A()?(this.initWeChatConfig(),void e("initWeChatSDK","WeChat SDK已挂载完成,无需二次挂载")):void l("https://res.wx.qq.com/open/js/jweixin-1.6.0.js","微信").then(t=>{A()&&(this.weChatInit=!0,this.initWeChatConfig(),e("initWeChatSDK","WeChat SDK挂载完成"))})}initWeChatConfig(){this.weChatConfigReady||wx.request({url:"https://xybfw.zwfw.hunan.gov.cn/gateway3/api/auth/wechat/v1/getJsapiTicket",method:"POST",data:{url:window.location.href.split("#")[0]},success:t=>{const i=t?.data?.data;this.weChatConfigReady=!0,e("getLocationInWeChat","获取签名信息完成"),window?.wx?.config({appId:"wx44bc5d5e34ac0c01",timestamp:i?.timestamp,nonceStr:i?.noncestr,signature:i?.signature,jsApiList:["getLocation","openLocation","chooseImage","chooseFile","scanQRCode","previewImage","downloadImage"]}),this.checkLocationEvStation()},fail:t=>{e("initWeChatConfig",`获取签名信息失败,信息是:${JSON.stringify(t)}`)}})}initAliPaySDK(){e("initAliPaySDK","初始化Alipay SDK"),w()&&($()||I()&&l("https://appx/web-view.min.js","支付宝").then(t=>{$()&&(this.alipayInit=!0,e("initAliPaySDK","Alipay SDK挂载完成"))}))}initSDKAPI(){S()&&(e("initSDKAPI","App的Webview环境,初始化C2调用链的回调函数"),this.initMobileBridgeGlobalConfig()),e("initSDKAPI","开始初始化SDK API"),P.forEach(t=>{const{eventName:i,moduleName:n,nativeEvName:o,isCustomEv:a}=t;if((n&&o||a)&&S()&&(e("initSDKAPI",`初始化C2调用链的回调函数:${i}`),this.checkMobileModuleBack(n,o,a)),!ee?.includes(i))try{this[i]=e=>new Promise(i=>{this.normalEvDataTransition(i,e,t)})}catch(t){e("initSDKAPI","执行API初始化挂载异常","error",t)}})}normalEvDataTransition(t,i={},n={}){const{eventName:o,description:a,reqDataFormat:s}=n||{},r=f();let c=i;if(s&&(c=s(i)),c)return S()?(e("normalEvDataTransition",`开始调用APP的嵌套H5能力,事件名称:${o},入参:${JSON.stringify(c)}`),void this.appH5SendMsgToApp(t,n,c)):y()?(e("normalEvDataTransition",`开始调用小程序/H5嵌套的H5能力,事件名称:${o},入参:${JSON.stringify(c)}`),void this.miniAppH5SendMsgToApp(t,o,c,a)):void(C()||I()?this.executeBrowserEvent(t,c,i,n):this.executeEvByNative(t,c,n));e(o,`给【${r}】APP发送【${a}】-【${o}】事件失败,请检查数据格式是否正确`,"error")}executeEvByNative(t,i,n){const{description:o,uniEvName:a,eventName:r,nativeResFormat:c}=n;try{e("executeEvByNative",`开始调用原生${o}的能力,API名称:${a},格式化前的参数信息:${JSON.stringify(i)}`),uni.sendNativeEvent(a,i,async i=>{e("executeEvByNative",`调用原生${o}的能力完成,结果:${JSON.stringify(i)}`,"log");let n=i;c&&(n=c(n),e("executeEvByNative",`调用原生${o}的能力完成,格式化后的结果:${JSON.stringify(n)}`,"log")),"fileDownload"===r&&i.isSuccess&&s(t,n),"getLocationInfo"!==r?"fileDownload"!==r&&s(t,n):uni.sendNativeEvent("System_getAppInfo",{},e=>{if(e.platform.toLowerCase().includes("harmony")){const e=D(i?.location?.longitude,i?.location?.latitude);n.location.longitude=e?.lng,n.location.latitude=e?.lat}s(t,n)})})}catch(i){t({isSuccess:!1,message:`${o}API执行失败,具体错误信息请查看控制台`}),e("executeEvByNative",`${o}API执行异常`,"error",i)}}initDefaultConfig(){e("initDefaultConfig","默认胶囊按钮配置执行初始化处理"),this.autoUpdate?this.resetMenuBtnConfig():e("initDefaultConfig","业务侧配置无需自动重置胶囊按钮,不至于页面切换事件监听")}}(k,N());w()&&(window.xybAgent=te);export{te as default};
1
+ /**
2
+ * @description: 执行日志信息提示
3
+ * @param evName 事件名称
4
+ * @param msg 日志信息
5
+ * @param level 日志级别
6
+ * @param errorMsg 错误信息
7
+ */
8
+ const logMsgFormat = (evName = '', msg = '', level = 'log', errorMsg = '') => {
9
+ const levelList = {
10
+ "error": "错误",
11
+ "warn": "警告",
12
+ "info": "提示",
13
+ "log": "日志"
14
+ };
15
+ const levelName = levelList[level] || "日志";
16
+ const errMsg = JSON.stringify(errorMsg);
17
+ console.log(`\n=============🚀START - V${VERSION} 🚀=============\n【事件名称】:${evName} \n【日志类型】:${levelName} \n【日志信息】:${msg} ${level === 'error' ? `【错误信息】:${JSON.stringify(errMsg)}` : ''} \n==============🚀END🚀==============`);
18
+ console.log('');
19
+ };
20
+
21
+ /**
22
+ * @description: 执行数据深拷贝
23
+ */
24
+ const deepClone = (dataInfo = {}) => {
25
+ if (typeof dataInfo === 'function') {
26
+ logMsgFormat('deepClone', '数据类型为function,无法执行深拷贝,请检查', 'error');
27
+ return dataInfo;
28
+ }
29
+ try {
30
+ return JSON.parse(JSON.stringify(dataInfo));
31
+ } catch (e) {
32
+ logMsgFormat('deepClone', '执行数据深拷贝异常', 'error', e);
33
+ return dataInfo;
34
+ }
35
+ };
36
+
37
+
38
+ /**
39
+ * @description: 获取UUID
40
+ * @return {*}
41
+ */
42
+
43
+ const getUUID = () => {
44
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
45
+ var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
46
+ return v.toString(16);
47
+ });
48
+ };
49
+
50
+
51
+ /**
52
+ * @description: 对象合并
53
+ * @param {*} source
54
+ * @param {*} target
55
+ * @return {*}
56
+ */
57
+ const objIntegration = (source = {}, target = {}) => {
58
+ for (let i in source) {
59
+ target[i] = source[i];
60
+ }
61
+ };
62
+
63
+ /**
64
+ * @description: 获取当前页面路径
65
+ * @param isBack 是否为返回页面时触发该事件
66
+ */
67
+ const getCurrentPagePath = (isBack = false) => {
68
+ let path = {
69
+ route: null,
70
+ path: null,
71
+ options: {}
72
+ };
73
+ try {
74
+ const list = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
75
+ const routeList = [];
76
+ for (let i in list) {
77
+ routeList.push({
78
+ route: list[i].route,
79
+ path: list[i].$page?.fullPath,
80
+ options: list[i].$page?.options
81
+ });
82
+ }
83
+ const len = routeList?.length || 0;
84
+ if (len) {
85
+ const prev = routeList[len - 1];
86
+ const prevP = routeList[len - 2];
87
+ const routeInfo = isBack ? prevP : prev;
88
+ path = routeInfo || {};
89
+ }
90
+ } catch (e) {
91
+ logMsgFormat(`getCurrentPagePath`, '获取页面信息失败', 'error', e);
92
+ }
93
+ return path;
94
+ };
95
+
96
+ /**
97
+ * @description: 格式化返回数据
98
+ */
99
+ const parseResData = (data) => {
100
+ try {
101
+ return JSON.parse(data);
102
+ } catch (e) {
103
+ return data;
104
+ }
105
+ };
106
+
107
+ /**
108
+ * @description: 格式化返回体数据格式
109
+ */
110
+ const formatResponseData = (resolve = {}, res = {}) => {
111
+ let data = res;
112
+ try {
113
+ data = parseResData(res);
114
+ } catch (e) {
115
+ logMsgFormat('formatResponseData', `格式化失败`, 'error', e);
116
+ data = res;
117
+ }
118
+ resolve(data);
119
+ };
120
+
121
+
122
+ /**
123
+ * @description: 检测是否为空
124
+ */
125
+ const isEmpty = (value) => {
126
+ return value === null || value === undefined;
127
+ };
128
+
129
+
130
+ /**
131
+ * @description: 获取地址栏中的参数信息
132
+ * @param name 参数名
133
+ * @param url
134
+ * @returns {*} String
135
+ */
136
+ const getUrlParam = (name = '', url = '') => {
137
+ let urlInfo = url || window?.location?.href;
138
+ urlInfo = decodeURIComponent(urlInfo);
139
+ if (urlInfo?.includes(name)) {
140
+ let param = urlInfo.split(`${name}=`)[1];
141
+ if (param?.includes('&')) {
142
+ param = param.split('&')[0];
143
+ }
144
+ return param;
145
+ }
146
+ return '';
147
+ };
148
+
149
+
150
+ /**
151
+ * @description: 挂载JS脚本文件到window下
152
+ */
153
+ const mountScriptFile = (url = "", name = "") => {
154
+ if (!url) {
155
+ return;
156
+ }
157
+ return new Promise((resolve) => {
158
+ const script = document.createElement("script");
159
+ script.src = url;
160
+ script.onload = resolve;
161
+ document.head.appendChild(script);
162
+ });
163
+ };
164
+
165
+ /**
166
+ * @description 打开支付宝小程序跳转到中间页
167
+ * @param url
168
+ * @param resolve
169
+ */
170
+ const openAlipayMiniApp = (url, resolve) => {
171
+ window?.my?.navigateTo({
172
+ url: url,
173
+ fail: (err) => {
174
+ logMsgFormat(`openAlipayMiniApp`, `跳转失败,请检查配置信息`, 'error', err);
175
+ resolve({
176
+ code: -1,
177
+ isSuccess: false,
178
+ message: `跳转失败,请检查配置信息`
179
+ });
180
+ }
181
+ });
182
+ };
183
+
184
+
185
+ /**
186
+ * @description 打开微信小程序,跳转到目标页面
187
+ * @param url
188
+ * @param resolve
189
+ */
190
+ const openWeChatMiniApp = (url, resolve) => {
191
+ uni?.navigateTo({
192
+ url: url,
193
+ fail: (err) => {
194
+ logMsgFormat(`executeAuthFaceInBrowser`, `跳转失败,请检查配置信息`, 'error', err);
195
+ resolve({
196
+ code: -1,
197
+ isSuccess: false,
198
+ message: `跳转失败,请检查配置信息`
199
+ });
200
+ }
201
+ });
202
+ };
203
+
204
+ // 是否为Webview环境检测结果信息
205
+
206
+ const globalObj = typeof window !== 'undefined' ? window : typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : {};
207
+
208
+ let isWebviewCheckInfo = {
209
+ finished: false,
210
+ result: false
211
+ };
212
+
213
+ // 是否为APP的Webview环境检测结果信息
214
+ let isAppWebviewCheckInfo = {
215
+ finished: false,
216
+ result: false
217
+ };
218
+
219
+ // 是否为湘易办的浏览器环境监测结果信息
220
+ let isXybBrowserCheckInfo = {
221
+ finished: false,
222
+ result: false
223
+ };
224
+
225
+ // 是否为小程序的浏览器环境检测结果信息
226
+ let isMiniAppBrowserCheckInfo = {
227
+ finished: false,
228
+ result: false
229
+ };
230
+
231
+ /**
232
+ * @description: 获取浏览器内核信息
233
+ * @return {string}
234
+ */
235
+ const getUserAgentInfo = () => {
236
+ if (!checkIsBrowserEnv()) {
237
+ return '';
238
+ }
239
+ return navigator.userAgent.toLowerCase();
240
+ };
241
+
242
+ /**
243
+ * @description: 获取平台信息
244
+ * @return {string}
245
+ */
246
+ const getPlatformInfo = () => {
247
+ const ua = getUserAgentInfo();
248
+ if (/android/i.test(ua)) {
249
+ return "android";
250
+ }
251
+ if (/iphone|ipad|ipod|mac/i.test(ua) && !window.MSStream) {
252
+ return "ios"; // 排除 IE 伪造情况
253
+ }
254
+ if (/windows phone/i.test(ua)) {
255
+ return "windows";
256
+ }
257
+ return "harmony";
258
+ };
259
+
260
+ /**
261
+ * @description: 检测是否为浏览器环境
262
+ * @return {boolean}
263
+ */
264
+ const checkIsBrowserEnv = () => {
265
+ return window && document;
266
+ };
267
+
268
+ /**
269
+ * @description: 检测是否为湘易办下的浏览器环境
270
+ * @return {boolean}
271
+ */
272
+ const checkIsXybBrowserEnv = () => {
273
+ if (isXybBrowserCheckInfo.finished) {
274
+ return isXybBrowserCheckInfo.result;
275
+ }
276
+ isXybBrowserCheckInfo.finished = true;
277
+ if (!checkIsBrowserEnv()) {
278
+ isXybBrowserCheckInfo.result = false;
279
+ return false;
280
+ }
281
+ const ua = getUserAgentInfo();
282
+ isXybBrowserCheckInfo.result = ua.includes('xybwebcomponent') || ua.includes('uni-app');
283
+ logMsgFormat("checkIsXybBrowserEnv", `当前是否为湘易办浏览器环境:${isXybBrowserCheckInfo.result}`);
284
+ return isXybBrowserCheckInfo.result;
285
+ };
286
+
287
+
288
+ /**
289
+ * @description: 监测是否为湘易办小程序的浏览器环境
290
+ * @return {boolean}
291
+ */
292
+ const checkIsMiniAppBrowserEnv = () => {
293
+ if (isMiniAppBrowserCheckInfo.finished) {
294
+ return isMiniAppBrowserCheckInfo.result;
295
+ }
296
+ isMiniAppBrowserCheckInfo.finished = true;
297
+ if (!checkIsBrowserEnv()) {
298
+ isMiniAppBrowserCheckInfo.result = false;
299
+ return false;
300
+ }
301
+ const ua = getUserAgentInfo();
302
+ isMiniAppBrowserCheckInfo.result = ua.includes("uni-app");
303
+ logMsgFormat("checkIsMiniAppBrowserEnv", `当前是否为小程序的浏览器环境:${isMiniAppBrowserCheckInfo.result}`);
304
+ return isMiniAppBrowserCheckInfo.result;
305
+ };
306
+
307
+
308
+ /**
309
+ * @description: 检测是否为webview环境
310
+ * @return {boolean}
311
+ */
312
+ const checkIsWebviewEnv = () => {
313
+ const {finished, result} = isWebviewCheckInfo;
314
+ if (finished) {
315
+ return result;
316
+ }
317
+ isWebviewCheckInfo.result = checkIsXybBrowserEnv() || checkIsMiniAppBrowserEnv();
318
+ isWebviewCheckInfo.finished = true;
319
+ logMsgFormat("checkIsWebviewEnv", `当前是否为Webview环境:${isWebviewCheckInfo.result}`);
320
+ return isWebviewCheckInfo.result;
321
+ };
322
+
323
+
324
+ /**
325
+ * @description: 检测是否为APP的Webview环境
326
+ * @return {boolean}
327
+ */
328
+ const checkIsAppWebviewEnv = () => {
329
+ const {finished, result} = isAppWebviewCheckInfo;
330
+ if (finished) {
331
+ return result;
332
+ }
333
+ isAppWebviewCheckInfo.finished = true;
334
+ if (!checkIsBrowserEnv()) {
335
+ isAppWebviewCheckInfo.result = false;
336
+ return false;
337
+ }
338
+ const ua = getUserAgentInfo();
339
+ isAppWebviewCheckInfo.result = ua.includes('xybwebcomponent') && !ua.includes("uniminiapp");
340
+ logMsgFormat("checkIsAppWebviewEnv", `当前是否为APP的Webview环境:${isAppWebviewCheckInfo.result}`);
341
+ return isAppWebviewCheckInfo.result;
342
+ };
343
+
344
+ /**
345
+ * @description: 检测是否为微信环境
346
+ * @return {boolean}
347
+ */
348
+ const checkIsWeChatEnv = () => {
349
+ if (checkIsBrowserEnv()) {
350
+ return getUserAgentInfo().includes('micromessenger');
351
+ }
352
+ return getPlatformInfo() === 'mp-weixin'
353
+ };
354
+
355
+
356
+ /**
357
+ * @description: 检测是否为支付宝环境
358
+ * @return {boolean}
359
+ */
360
+ const checkIsAlipayEnv = () => {
361
+ if (checkIsBrowserEnv()) {
362
+ return getUserAgentInfo().includes('alipay');
363
+ }
364
+ return getPlatformInfo() === 'mp-alipay'
365
+ };
366
+
367
+
368
+ /**
369
+ * @description: 检测是否为APP的运行环境
370
+ * @return {boolean}
371
+ */
372
+ const checkIsAppEnv = () => {
373
+ if (typeof globalObj.uni === undefined) {
374
+ return false;
375
+ }
376
+ if (globalObj?.uni && typeof globalObj?.uni?.sendNativeEvent !== 'function') {
377
+ return false;
378
+ }
379
+ if (globalObj?.uni && typeof globalObj?.uni?.sendNativeEvent === 'function') {
380
+ return true;
381
+ }
382
+ return typeof globalObj?.uni !== 'undefined' && Object.prototype.hasOwnProperty.call(globalObj?.uni, 'sendNativeEvent')
383
+ };
384
+
385
+ /**
386
+ * @description: 检测UNI SDK是否挂载完成
387
+ * @return {boolean}
388
+ */
389
+ const checkUNIReady = () => {
390
+ return window?.uni && typeof window?.uni?.webView?.postMessage === 'function'
391
+ };
392
+
393
+ /**
394
+ * @description: 检测微信SDK是否挂载完成
395
+ */
396
+ const checkWeChatReady = () => {
397
+ return typeof window?.wx?.chooseImage === 'function';
398
+ };
399
+
400
+ /**
401
+ * @description: 检测支付宝SDK是否挂载完成
402
+ */
403
+ const checkAliPayReady = () => {
404
+ return Boolean(window?.my)?.chooseImage === 'function';
405
+ };
406
+
407
+ /**
408
+ *判断坐标是否在中国境内
409
+ * @param {number} lat - 纬度
410
+ * @param {number} lon - 经度
411
+ * @returns {boolean}
412
+ */
413
+ const outOfChina = (lat, lon) => {
414
+ if (lon < 72.004 || lon > 137.8347) {
415
+ return true;
416
+ }
417
+ return lat < 0.8293 || lat > 55.8271;
418
+
419
+ };
420
+ /**
421
+ * 转换纬度
422
+ * @param {number} x
423
+ * @param {number} y
424
+ * @returns {number}
425
+ */
426
+ const transformLat = (x, y) => {
427
+ let ret = -100 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
428
+ ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
429
+ ret += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
430
+ ret += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
431
+ return ret;
432
+ };
433
+
434
+ /**
435
+ * 转换经度
436
+ * @param {number} x
437
+ * @param {number} y
438
+ * @returns {number}
439
+ */
440
+ const transformLon = (x, y) => {
441
+ let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
442
+ ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
443
+ ret += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
444
+ ret += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;
445
+ return ret;
446
+ };
447
+
448
+ /**
449
+ * @description: Baidu坐标系转GCJ02坐标系
450
+ * @param lng
451
+ * @param lat
452
+ */
453
+ const BaiduToGCJ02 = (lng, lat) => {
454
+ const x_PI = (3.14159265358979324 * 3000.0) / 180.0;
455
+ // 1. 消除初始偏移
456
+ const x = lng - 0.0065;
457
+ const y = lat - 0.006;
458
+
459
+ // 2. 计算距离和角度,并应用校正因子
460
+ const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI);
461
+ const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI);
462
+
463
+ // 3. 计算转换后的GCJ02坐标
464
+ const gcj_lng = z * Math.cos(theta).toFixed(6);
465
+ const gcj_lat = z * Math.sin(theta).toFixed(6);
466
+ logMsgFormat(`BaiduToGCJ02`, `已完成百度坐标系转换成国测坐标系的转换,转换后的值:lng:${gcj_lng}, lat:${gcj_lat}`);
467
+ return {
468
+ lng: gcj_lng,
469
+ lat: gcj_lat
470
+ }
471
+ };
472
+
473
+ /**
474
+ * @description: WGS坐标系转WCJ02坐标系
475
+ */
476
+ const wgsToGCJ02 = (wgsLon, wgsLat) => {
477
+ let PI = null;
478
+ try {
479
+ PI = Math.PI;
480
+ } catch (e) {
481
+ logMsgFormat(`wgsToGCJ02`, `获取PI值失败`, 'error', e);
482
+ }
483
+ if (outOfChina(wgsLat, wgsLon)) {
484
+ return {lat: wgsLat, lon: wgsLon};
485
+ }
486
+ const a = 6378245.0; // 长半轴
487
+ const ee = 0.00669342162296594323; // 偏心率平方
488
+
489
+ const dLat = transformLat(wgsLon - 105.0, wgsLat - 35.0);
490
+ const dLon = transformLon(wgsLon - 105.0, wgsLat - 35.0);
491
+
492
+ const radLat = (wgsLat / 180.0) * Math.PI;
493
+ let magic = Math.sin(radLat);
494
+ magic = 1 - ee * magic * magic;
495
+ const sqrtMagic = Math.sqrt(magic);
496
+
497
+ const latResult = wgsLat + ((dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI));
498
+ const lonResult = wgsLon + ((dLon * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * Math.PI));
499
+
500
+ return {
501
+ lat: parseFloat(latResult.toFixed(8)),
502
+ lng: parseFloat(lonResult.toFixed(8))
503
+ };
504
+ };
505
+ /**
506
+ * @description: 坐标系转换
507
+ */
508
+ const replaceCoordinate = (data) => {
509
+ const {dinateType, lat, lng, address} = data;
510
+ logMsgFormat('replaceCoordinate', `坐标转换开始:${dinateType}`, 'log');
511
+ if (dinateType === "BD09") {
512
+ const res = BaiduToGCJ02(lng, lat);
513
+ return {
514
+ destinationName: address,
515
+ destinationLongitude: res?.lng,
516
+ destinationLatitude: res?.lat
517
+ }
518
+ }
519
+ if (dinateType === "WGS84") {
520
+ const res = wgsToGCJ02(lng, lat);
521
+ return {
522
+ destinationName: address,
523
+ destinationLongitude: res?.lng,
524
+ destinationLatitude: res?.lat
525
+ }
526
+ }
527
+ logMsgFormat('replaceCoordinate', `坐标系转换异常,未在匹配规则内,传递的坐标系类型:${dinateType}`, 'log');
528
+ return {
529
+ destinationLatitude: data?.lat || "",
530
+ destinationLongitude: data?.lng || "",
531
+ destinationName: data?.address || "",
532
+ dinateType: data?.dinateType || "",
533
+ address: data?.address || "",
534
+ name: data?.name || "",
535
+ }
536
+ };
537
+
538
+ // 是否为湘易办开发
539
+ const eventList = [
540
+ {
541
+ isCustomEv: true,
542
+ eventName: "authFace",
543
+ uniEvName: "Auth_face",
544
+ description: "人脸识别功能",
545
+ nativeEvName: "faceAuth",
546
+ reqDataFormat: config => {
547
+ logMsgFormat('authFace', `执行人脸验证,参数信息:${JSON.stringify(config)}`);
548
+ const {name, certNo, appId, sign, created, nonce} = config;
549
+ if (!name || !certNo || !appId || !sign || !created || !nonce) {
550
+ logMsgFormat('authFace', `缺少必要参数:name, certNo, appId, sign, created, nonce`, 'error', '缺少必要参数');
551
+ return false;
552
+ }
553
+ return config;
554
+ },
555
+ resDataFormat: res => {
556
+ return {
557
+ isSuccess: Boolean(res),
558
+ certifyId: res
559
+ }
560
+ },
561
+ resErrorFormat: errInfo => {
562
+ const device = getPlatformInfo().toLowerCase();
563
+ if (device === 'harmony') {
564
+ return {
565
+ isSuccess: false,
566
+ errorMsg: errInfo
567
+ }
568
+ }
569
+ return errInfo
570
+ }
571
+ },
572
+ {
573
+ isCustomEv: true,
574
+ eventName: "startNavigation",
575
+ uniEvName: "Start_navigation",
576
+ description: "目的地导航",
577
+ nativeEvName: "start_navigation",
578
+ reqDataFormat: (data) => {
579
+ let res = {};
580
+ const {dinateType, lat, lng, address, destinationLatitude, destinationLongitude} = data;
581
+ if (destinationLatitude && destinationLongitude) {
582
+ return data;
583
+ }
584
+ logMsgFormat('replaceCoordinate', `坐标系值:LAT:${lat},LNG:${lng}`, 'log');
585
+ if (!dinateType || dinateType === "GCJ02") {
586
+ res = {
587
+ destinationLatitude: lat,
588
+ destinationLongitude: lng,
589
+ destinationName: address,
590
+ };
591
+ } else {
592
+ res = replaceCoordinate(data);
593
+ }
594
+ logMsgFormat('replaceCoordinate', `转换后值:LAT:${res.destinationLatitude},LNG:${res.destinationLongitude}`, 'log');
595
+ return res;
596
+ }
597
+ },
598
+ {
599
+ isWindowEv: true,
600
+ eventName: 'getLoginStatus',
601
+ uniEvName: 'Auth_checkLogin',
602
+ description: '获取登录状态',
603
+ nativeEvName: 'CallNativeMethodGetUserInfo',
604
+ resDataFormat: res => {
605
+ const userInfo = deepClone(res);
606
+ return {
607
+ 'logined': Number(userInfo?.isLogin) === 1,
608
+ }
609
+ },
610
+ resErrorFormat: () => {
611
+ return {
612
+ 'logined': false
613
+ }
614
+ }
615
+ },
616
+ {
617
+ isWindowEv: true,
618
+ eventName: 'getLoginUserInfo',
619
+ uniEvName: 'Auth_getUserInfo',
620
+ description: '获取登录用户数据信息',
621
+ nativeEvName: 'CallNativeMethodGetUserInfo',
622
+ resDataFormat: res => {
623
+ return deepClone(res)
624
+ },
625
+ resErrorFormat: () => {
626
+ return {
627
+ isSuccess: false
628
+ }
629
+ }
630
+ },
631
+ {
632
+ isCustomEv: true,
633
+ eventName: 'getAuthToken',
634
+ uniEvName: 'Auth_getToken',
635
+ description: '获取授权token',
636
+ nativeEvName: 'get_token',
637
+ resDataFormat: res => {
638
+ try {
639
+ const tokenInfo = deepClone(res);
640
+ return {
641
+ token: tokenInfo?.token,
642
+ isSuccess: Boolean(tokenInfo?.token),
643
+ }
644
+ } catch (e) {
645
+ return {
646
+ token: res?.token,
647
+ isSuccess: Boolean(res?.token),
648
+ }
649
+ }
650
+ },
651
+ resErrorFormat: () => {
652
+ return {
653
+ isSuccess: false
654
+ }
655
+ }
656
+ },
657
+ {
658
+ isWindowEv: true,
659
+ eventName: 'getAccessLink',
660
+ uniEvName: 'Auth_getAccessLink',
661
+ nativeEvName: 'CallNativeMethodGetAccessLink',
662
+ description: '获取授权链接',
663
+ resDataFormat: (res) => {
664
+ const device = getPlatformInfo().toLowerCase();
665
+ if (device === 'ios') {
666
+ return {
667
+ isSuccess: true,
668
+ accessLink: res
669
+ }
670
+ }
671
+ return deepClone(res)
672
+ },
673
+ resErrorFormat: () => {
674
+ return {
675
+ isSuccess: false
676
+ }
677
+ }
678
+ },
679
+ {
680
+ moduleName: 'image',
681
+ eventName: 'chooseImg',
682
+ uniEvName: 'Image_choose',
683
+ nativeEvName: 'chooseImage',
684
+ browserEvName: 'chooseImage',
685
+ description: '选择本地图片',
686
+ reqDataFormat: (data) => {
687
+ const {count, sizeType, sourceType, isCircleCrop} = data || {};
688
+ return {
689
+ count: count || 9, //默认9
690
+ sizeType: sizeType || ['original', 'compressed'], // 是否需要原图,默认二者都有
691
+ sourceType: sourceType || ['album'], // 图片来源
692
+ isCircleCrop: isCircleCrop || false, //圆形头像裁剪
693
+ }
694
+ },
695
+ resDataFormat: res => {
696
+ return deepClone(res);
697
+ },
698
+ bResDataFormat: res => {
699
+ const {tempFiles} = res;
700
+ const arr = [];
701
+ for (let i in tempFiles) {
702
+ const {name, path, size, type} = tempFiles[i];
703
+ arr.push({
704
+ name,
705
+ path,
706
+ size,
707
+ type
708
+ });
709
+ }
710
+ return {
711
+ resultObj: arr,
712
+ isSuccess: true,
713
+ message: "选择图片功能操作完成"
714
+ };
715
+ }
716
+ },
717
+ {
718
+ moduleName: 'image',
719
+ eventName: 'imgPreview',
720
+ uniEvName: 'Image_preview',
721
+ nativeEvName: 'previewImage',
722
+ browserEvName: "previewImage",
723
+ description: '执行图片预览'
724
+ },
725
+ {
726
+ moduleName: 'image',
727
+ eventName: 'imgUpload',
728
+ uniEvName: 'Image_upload',
729
+ nativeEvName: 'uploadImage',
730
+ description: '执行图片上传',
731
+ resDataFormat: res => {
732
+ return deepClone(res);
733
+ },
734
+ resErrorFormat: err => {
735
+ return err
736
+ }
737
+ },
738
+ {
739
+ eventName: 'imgDownload',
740
+ uniEvName: 'Image_download',
741
+ nativeEvName: '',
742
+ browserEvName: "downloadImage",
743
+ description: '执行图片下载'
744
+ },
745
+ {
746
+ eventName: 'fileUpload',
747
+ uniEvName: 'File_upload',
748
+ nativeEvName: '',
749
+ description: '执行文件上传'
750
+ },
751
+ {
752
+ moduleName: 'file',
753
+ eventName: 'fileDownload',
754
+ uniEvName: 'File_download',
755
+ nativeEvName: 'downloadFile',
756
+ description: '执行文件下载',
757
+ resDataFormat: res => {
758
+ return {
759
+ isSuccess: Boolean(res),
760
+ resultObj: {
761
+ path: res
762
+ }
763
+ }
764
+ }
765
+ },
766
+ {
767
+ moduleName: 'file',
768
+ eventName: 'filePreview',
769
+ uniEvName: 'File_preview',
770
+ nativeEvName: 'previewFile',
771
+ description: '执行文件预览'
772
+ },
773
+ {
774
+ moduleName: 'file',
775
+ eventName: 'openLocalFile',
776
+ uniEvName: 'File_openLocal',
777
+ nativeEvName: 'openLocalFile',
778
+ description: '执行打开本地文件'
779
+ },
780
+ {
781
+ moduleName: 'file',
782
+ eventName: 'chooseLocalFile',
783
+ uniEvName: 'File_chooseLocal',
784
+ nativeEvName: 'chooseLocalFile',
785
+ browserEvName: "chooseFile",
786
+ description: '选择本地文件',
787
+ resDataFormat: res => {
788
+ return deepClone(res);
789
+ }
790
+ },
791
+ {
792
+ moduleName: 'file',
793
+ eventName: 'openThirdFile',
794
+ uniEvName: 'File_openThirdParty',
795
+ nativeEvName: 'openFileWithThirdParty',
796
+ description: '执行打开第三方文件'
797
+ },
798
+ {
799
+ eventName: 'openApp',
800
+ uniEvName: 'Util_openApp',
801
+ nativeEvName: '',
802
+ description: '打开APP'
803
+ },
804
+ {
805
+ isCustomEv: true,
806
+ eventName: 'openXybApp',
807
+ uniEvName: 'Util_openXYBMiniApp',
808
+ nativeEvName: 'jumpToMiniApp',
809
+ description: '打开湘易办融合APP小程序',
810
+ reqDataFormat: (data) => {
811
+ if (checkIsAppWebviewEnv()) {
812
+ const {pageUrl} = data;
813
+ return {
814
+ ...data,
815
+ ...{
816
+ path: pageUrl,
817
+ }
818
+ }
819
+ }
820
+ return data;
821
+ },
822
+ },
823
+ {
824
+ eventName: 'postMsgToOtherApp',
825
+ uniEvName: 'Util_postMessageToXYBMiniApp',
826
+ nativeEvName: '',
827
+ description: '发送消息给其他小程序'
828
+ },
829
+ {
830
+ isWindowEv: true,
831
+ eventName: 'scanCode',
832
+ uniEvName: 'Scan_code',
833
+ description: '扫描二维码',
834
+ browserEvName: 'scanQRCode',
835
+ nativeEvName: 'CallNativeMethodScanQRCode',
836
+ resDataFormat: res => {
837
+ return {
838
+ text: res
839
+ }
840
+ },
841
+ bReqDataFormat: data => {
842
+ return {
843
+ ...data,
844
+ ...{
845
+ needResult: 1
846
+ }
847
+ }
848
+ },
849
+ bResDataFormat: res => {
850
+ return {
851
+ text: res?.resultStr || ""
852
+ }
853
+ }
854
+ },
855
+ {
856
+ moduleName: 'system',
857
+ eventName: 'getAppInfo',
858
+ nativeEvName: 'getAppInfo',
859
+ description: '获取应用信息',
860
+ uniEvName: 'System_getAppInfo',
861
+ resDataFormat: res => {
862
+ return deepClone(res);
863
+ }
864
+ },
865
+ {
866
+ moduleName: 'util',
867
+ eventName: 'copyToClipboard',
868
+ uniEvName: 'Util_clipboardData',
869
+ nativeEvName: 'clipboardData',
870
+ description: '复制内容到剪切板',
871
+ reqDataFormat: (data) => {
872
+ return {
873
+ text: data
874
+ }
875
+ },
876
+ resDataFormat: res => {
877
+ if (checkIsAppWebviewEnv()) {
878
+ return {
879
+ isSuccess: Boolean(res),
880
+ }
881
+ }
882
+ return {
883
+ isSuccess: true
884
+ }
885
+ }
886
+ },
887
+ {
888
+ moduleName: 'util',
889
+ eventName: 'getCacheSize',
890
+ uniEvName: 'Util_getCacheSize',
891
+ nativeEvName: 'getCacheSize',
892
+ description: '获取缓存大小',
893
+ resDataFormat: res => {
894
+ return deepClone(res);
895
+ }
896
+ },
897
+ {
898
+ moduleName: 'util',
899
+ eventName: 'clearCache',
900
+ uniEvName: 'Util_clearCache',
901
+ nativeEvName: 'clearCache',
902
+ description: '执行缓存清除',
903
+ resDataFormat: () => {
904
+ return {
905
+ isSuccess: true
906
+ }
907
+ },
908
+ resErrorFormat: () => {
909
+ return {
910
+ isSuccess: false
911
+ }
912
+ }
913
+ },
914
+ {
915
+ moduleName: 'telephone',
916
+ eventName: 'callPhone',
917
+ uniEvName: 'Util_callDesignateNumber',
918
+ nativeEvName: 'call',
919
+ description: '拨打电话',
920
+ browserEvName: "makePhoneCall",
921
+ reqDataFormat: (data) => {
922
+ if (typeof parseResData(data) === 'object') {
923
+ return parseResData(data);
924
+ }
925
+ if (checkIsAppWebviewEnv()) {
926
+ return {
927
+ phoneCode: '+86',
928
+ phoneNumber: String(data).replace('+86', '')
929
+ }
930
+ }
931
+ return {
932
+ text: data
933
+ }
934
+ }
935
+ },
936
+ {
937
+ eventName: 'forbidScreenShot',
938
+ uniEvName: 'Util_forbidScreenShot',
939
+ nativeEvName: '',
940
+ description: '执行禁止截屏'
941
+ },
942
+ {
943
+ eventName: 'setScreenLight',
944
+ uniEvName: 'Util_setScreenLight',
945
+ nativeEvName: '',
946
+ description: '设置屏幕是否常亮',
947
+ reqDataFormat: (data) => {
948
+ return {
949
+ idleTimerValue: data
950
+ }
951
+ }
952
+ },
953
+ {
954
+ eventName: 'sendMatterId',
955
+ uniEvName: 'Param_MatterID',
956
+ nativeEvName: '',
957
+ description: '执行页面事件ID上报',
958
+ reqDataFormat: (data) => {
959
+ return {
960
+ matterID: data
961
+ }
962
+ }
963
+ },
964
+ {
965
+ isWindowEv: true,
966
+ description: '获取位置信息',
967
+ eventName: 'getLocationInfo',
968
+ uniEvName: 'Util_getLocationInformation',
969
+ nativeEvName: 'CallNativeMethodGetLocationInformation',
970
+ resDataFormat: (res) => {
971
+ const {location, data} = res;
972
+ let locationInfo = deepClone(res);
973
+ if (location) {
974
+ locationInfo = deepClone(res?.location);
975
+ }
976
+ if (data) {
977
+ locationInfo = deepClone(res?.data);
978
+ }
979
+ getPlatformInfo().toLowerCase();
980
+
981
+ return {
982
+ isSuccess: true,
983
+ location: locationInfo
984
+ }
985
+ },
986
+ nativeResFormat: res => {
987
+ const {location, data} = res;
988
+ let locationInfo = deepClone(res);
989
+ if (location) {
990
+ locationInfo = deepClone(res?.location);
991
+ }
992
+ if (data) {
993
+ locationInfo = deepClone(res?.data);
994
+ }
995
+ return {
996
+ isSuccess: true,
997
+ location: locationInfo
998
+ }
999
+ },
1000
+ resErrorFormat: () => {
1001
+ return {
1002
+ isSuccess: false,
1003
+ location: {}
1004
+ }
1005
+ }
1006
+ },
1007
+ {
1008
+ eventName: 'checkPermission',
1009
+ uniEvName: 'Auth_matterHandleAuthority',
1010
+ nativeEvName: '',
1011
+ description: '检查事项权限',
1012
+ reqDataFormat: (data) => {
1013
+ return {
1014
+ matterCode: data
1015
+ }
1016
+ }
1017
+ },
1018
+ {
1019
+ eventName: 'showComment',
1020
+ uniEvName: 'Util_jumpToComment',
1021
+ nativeEvName: '',
1022
+ description: '打开评价弹窗'
1023
+ },
1024
+ {
1025
+ isWindowEv: true,
1026
+ description: '打开微信小程序',
1027
+ eventName: 'openWechatMiniApp',
1028
+ uniEvName: 'Util_openWechatMiniProgram',
1029
+ nativeEvName: 'CallNativeMethodJumpToWechatMiniProgram',
1030
+ reqDataFormat: data => {
1031
+ if (checkIsAppWebviewEnv()) {
1032
+ const target = {};
1033
+ for (let i in data) {
1034
+ target[i] = String(data[i]);
1035
+ }
1036
+ return JSON.stringify(target)
1037
+ }
1038
+ return data;
1039
+ }
1040
+ },
1041
+ {
1042
+ isWindowEv: true,
1043
+ description: '打开支付宝小程序',
1044
+ eventName: 'openAliPayMiniApp',
1045
+ uniEvName: 'Util_openAlipayMiniProgram',
1046
+ nativeEvName: 'CallNativeMethodJumpToAliPay',
1047
+ reqDataFormat: data => {
1048
+ if (checkIsAppWebviewEnv()) {
1049
+ return JSON.stringify(data)
1050
+ }
1051
+ return data;
1052
+ }
1053
+ },
1054
+ {
1055
+ eventName: 'showMenuPanel',
1056
+ uniEvName: 'menu_present',
1057
+ nativeEvName: '',
1058
+ description: '显示菜单面板'
1059
+ },
1060
+ {
1061
+ isCustomEv: true,
1062
+ eventName: "addCalendarEvent",
1063
+ uniEvName: "Util_addCalendarEvent",
1064
+ nativeEvName: "addCalendarEvent",
1065
+ description: "添加日历日程"
1066
+ },
1067
+ {
1068
+ isCustomEv: true,
1069
+ eventName: "deleteCalendarEvent",
1070
+ uniEvName: "Util_deleteCalendarEvent",
1071
+ nativeEvName: "deleteCalendarEvent",
1072
+ description: "删除日历日程"
1073
+ },
1074
+ {
1075
+ isCustomEv: true,
1076
+ eventName: "queryCalendarEvent",
1077
+ uniEvName: "Util_queryCalendarEvent",
1078
+ nativeEvName: "queryCalendarEvent",
1079
+ description: "查询日历日程"
1080
+ }
1081
+ ];
1082
+
1083
+ // 事件列表
1084
+
1085
+ const VERSION = "0.0.27";
1086
+
1087
+ // 接口基础路径
1088
+ const baseURL = "https://xybfw.zwfw.hunan.gov.cn/gateway3";
1089
+
1090
+ const custom = {
1091
+
1092
+ custom(actionName, params) {
1093
+ logMsgFormat("custom", `通过custom调用${actionName}事件`);
1094
+ const eventInfo = eventList?.find(item => item?.nativeEvName === actionName || item?.eventName === actionName);
1095
+ return new Promise((resolve, reject) => {
1096
+ const {reqDataFormat} = eventInfo || null;
1097
+ const evConfig = eventInfo || {
1098
+ isCustomEv: true,
1099
+ moduleName: 'custom',
1100
+ eventName: 'call',
1101
+ description: '通过Custom调用的C2事件',
1102
+ nativeEvName: actionName
1103
+ };
1104
+ // 如果是非APP直接嵌套的H5,则不处理
1105
+ if (!checkIsAppWebviewEnv()) {
1106
+ resolve({
1107
+ code: -1,
1108
+ msg: '非APP环境的Webview环境,不支持该功能',
1109
+ });
1110
+ return;
1111
+ }
1112
+ const dataInfo = reqDataFormat ? reqDataFormat(params) : params;
1113
+ this.executeSendMsgToApp({
1114
+ moduleName: 'custom',
1115
+ eventName: 'call',
1116
+ actionName,
1117
+ isCustomEv: true,
1118
+ dataInfo: dataInfo,
1119
+ resolveInfo: resolve,
1120
+ evConfig
1121
+ });
1122
+ });
1123
+ }
1124
+ };
1125
+
1126
+ /**
1127
+ * @description: 填充前缀0
1128
+ */
1129
+ const supZero = (num) => {
1130
+ return Number(num) > 9 ? num : `0${num}`;
1131
+ };
1132
+
1133
+ /**
1134
+ * @description: 获取当前时间值
1135
+ */
1136
+ const getCurrentDateTime = () => {
1137
+ const d = new Date();
1138
+ const y = d.getFullYear();
1139
+ const m = supZero(d.getMonth() + 1);
1140
+ const day = supZero(d.getDate());
1141
+ const h = supZero(d.getHours());
1142
+ const M = supZero(d.getMinutes());
1143
+ const s = supZero(d.getSeconds());
1144
+ return `${y}-${m}-${day} ${h}:${M}:${s}`;
1145
+ };
1146
+
1147
+ const trackInfo = {
1148
+ // 埋点堆栈数据
1149
+ trackStack: [],
1150
+ // 极光SDK加载次数
1151
+ anaSDKLoadTimes: 0,
1152
+ // 定位信息
1153
+ locationInfo: {},
1154
+ // 是否为生产环境
1155
+ isProdEnv: false,
1156
+ /**
1157
+ * @description: 上报埋点数据
1158
+ * @param {*} eventID 埋点事件
1159
+ * @param {*} eventPro 埋点参数
1160
+ * @return {*}
1161
+ */
1162
+ track(eventID = "", eventPro = {}) {
1163
+ if (!eventID) {
1164
+ logMsgFormat('track', `埋点数据上报失败`, 'error', '请传入埋点事件');
1165
+ return;
1166
+ }
1167
+ if (!eventPro) {
1168
+ logMsgFormat('track', `埋点数据上报失败`, 'error', '请传入埋点数据');
1169
+ return;
1170
+ }
1171
+ // 如果是浏览器环境,插件未完成初始化操作,则将数据暂存,待初始化完成后自动上报
1172
+ if (checkIsBrowserEnv() && !this.anaSDKInit) {
1173
+ this.trackStack.push({
1174
+ id: getUUID(), // 消息ID
1175
+ eventID, // 事件ID
1176
+ eventPro // 事件参数
1177
+ });
1178
+ logMsgFormat('track', `埋点上报插件初始化未完成,本次数据在插件初始化后自动上报`, 'log');
1179
+ return;
1180
+ }
1181
+ this.executeTrack(eventID, eventPro);
1182
+ },
1183
+
1184
+ /**
1185
+ * @description: 执行埋点数据上报
1186
+ * @param {*} eventID 埋点事件
1187
+ * @param {*} eventPro 埋点参数
1188
+ * @return {*}
1189
+ */
1190
+ async executeTrack(eventID = "", eventPro = {}) {
1191
+ // 如果是SDK内部自行调用,会存在eventID字段为对象的情况,所以需要自身再次内部调用
1192
+ if (typeof eventID === 'object') {
1193
+ await this.track(eventID?.eventID, eventID?.eventPro);
1194
+ return;
1195
+ }
1196
+ const params = await this.initTrackParams(eventPro);
1197
+ logMsgFormat('track', `执行埋点数据上报,事件名称:${eventID},事项编码:${params.code},是否上报到生产环境:${this.isProdEnv},完整埋点数据:${JSON.stringify(params)}`, 'log');
1198
+ if (checkIsBrowserEnv() && xybAgent?.AnalysysAgent) {
1199
+ logMsgFormat('track', `通过浏览器插件执行埋点数据上报`, 'log');
1200
+ window.xybAgent.AnalysysAgent.track(eventID, params);
1201
+ return;
1202
+ }
1203
+ if (checkIsAppEnv()) {
1204
+ try {
1205
+ logMsgFormat('track', `埋点数据:${JSON.stringify(params)},埋点ID:${eventID}`, 'log');
1206
+ uni.sendNativeEvent('Analysis_common', {eventID, eventPro: params});
1207
+ } catch (e) {
1208
+ logMsgFormat('track', `执行数据埋点功能异常`, 'error', e);
1209
+ }
1210
+ }
1211
+ },
1212
+
1213
+ /**
1214
+ * @description: 埋点环境初始化
1215
+ */
1216
+ trackSDKInit(config) {
1217
+ return new Promise((resolve, reject) => {
1218
+ if (!checkIsBrowserEnv()) {
1219
+ logMsgFormat('initTrack', `非浏览器环境无需使用init执行初`, 'error');
1220
+ resolve(true);
1221
+ }
1222
+ if (!this.anaSDKInsert) {
1223
+ mountScriptFile('https://mobile.zwfw.hunan.gov.cn:8088/AnalysysAgent_JS_SDK.min.js', '极光').then(() => {
1224
+ if (window.AnalysysAgent) {
1225
+ xybAgent.AnalysysAgent = window.AnalysysAgent;
1226
+ this.anaSDKInsert = true;
1227
+ this.configAnaSDK(config, resolve);
1228
+ }
1229
+ });
1230
+ } else {
1231
+ this.configAnaSDK(config, resolve);
1232
+ }
1233
+ });
1234
+ },
1235
+
1236
+ /**
1237
+ * @description: 配置极光SDK插件
1238
+ * @param {*} config 配置参数
1239
+ * @param {*} resolve 初始化成功回调
1240
+ * @return {*}
1241
+ */
1242
+ configAnaSDK(config, resolve) {
1243
+ const prodKey = '800c298f0c42c94c';
1244
+ const testKey = '40d556c15f872084';
1245
+ let keyVal = location?.host?.includes('hunan.gov.cn') ? prodKey : testKey;
1246
+ if (typeof config === 'object') {
1247
+ keyVal = testKey;
1248
+ } else {
1249
+ const envMap = {
1250
+ "production": prodKey, "development": testKey
1251
+ };
1252
+ const keyList = [prodKey, testKey];
1253
+ if (envMap[config] || keyList.includes(config)) {
1254
+ keyVal = envMap[config] ? envMap[config] : config;
1255
+ }
1256
+ }
1257
+ this.isProdEnv = keyVal === prodKey;
1258
+ logMsgFormat("configAnaSDK", `配置信息:${JSON.stringify(config)},是否为生产环境:${this.isProdEnv},上报的key值:${keyVal}`);
1259
+ if (!checkIsBrowserEnv()) {
1260
+ resolve(false);
1261
+ return;
1262
+ }
1263
+ if (window.xybAgent.AnalysysAgent) {
1264
+ window.xybAgent.AnalysysAgent.init({
1265
+ appkey: keyVal, // 极光SDK的Key值
1266
+ uploadURL: 'https://mobile.zwfw.hunan.gov.cn:8088/aurora-api'
1267
+ });
1268
+ logMsgFormat('configAnaSDK', `xybAgent已初始化完成,可正常执行埋点操作`, 'log');
1269
+ this.anaSDKInit = true;
1270
+ this.isInit = true;
1271
+ this.checkTrackStack();
1272
+ resolve(true);
1273
+ }
1274
+ if (!Boolean(window.xybAgent.AnalysysAgent) && this.anaSDKLoadTimes < 10) {
1275
+ setTimeout(() => this.trackSDKInit(resolve), 300);
1276
+ }
1277
+ if (!Boolean(window.xybAgent.AnalysysAgent) && this.anaSDKLoadTimes >= 10) {
1278
+ logMsgFormat('configAnaSDK', `xybAgent初始化失败`, 'error', '请检查app key、uploadURL是否正确');
1279
+ resolve(false);
1280
+ }
1281
+ },
1282
+
1283
+ /**
1284
+ * @description: 初始化埋点上报参数
1285
+ * @param {*} trackData 埋点参数
1286
+ * @return {*}
1287
+ */
1288
+ async initTrackParams(trackData = {}) {
1289
+ const {
1290
+ code,
1291
+ name,
1292
+ aff_city_code,
1293
+ aff_city_name,
1294
+ unit_code,
1295
+ area_code,
1296
+ unit_name,
1297
+ is_finish,
1298
+ category,
1299
+ user_id,
1300
+ miniAppCode,
1301
+ $url_domain
1302
+ } = trackData;
1303
+ const visitSource = this.getVisitSource();
1304
+ const pageSource = this.getPageSource();
1305
+ const positionInfo = await this.getPositionInfo();
1306
+ return {
1307
+ code: code || undefined,
1308
+ name: name || undefined,
1309
+ aff_city_code: aff_city_code || undefined,
1310
+ aff_city_name: aff_city_name || undefined,
1311
+ unit_code: unit_code || undefined,
1312
+ area_code: area_code || undefined,
1313
+ unit_name: unit_name || undefined,
1314
+ is_finish: is_finish || undefined,
1315
+ category: category || undefined,
1316
+ user_id: user_id || undefined,
1317
+ miniAppCode: miniAppCode || undefined,
1318
+ $url_domain: $url_domain || undefined, // 当前时间值
1319
+ curr_time: getCurrentDateTime(), // 访问渠道
1320
+ source: visitSource, // 访问来源
1321
+ page_source: pageSource, // 定位信息
1322
+ location: positionInfo
1323
+ };
1324
+ },
1325
+
1326
+
1327
+ /**
1328
+ * @description: 获取用户访问来源
1329
+ * @return {*}
1330
+ */
1331
+ getVisitSource() {
1332
+ if (!checkIsBrowserEnv()) {
1333
+ const sysInfo = uni?.getSystemInfoSync();
1334
+ const {uniPlatform} = sysInfo || {};
1335
+ if (uniPlatform === 'mp-weixin') {
1336
+ return 'wx'
1337
+ }
1338
+ if (uniPlatform === 'mp-alipay') {
1339
+ return 'alipay'
1340
+ }
1341
+ return 'app';
1342
+ }
1343
+ if (checkIsWeChatEnv()) {
1344
+ return 'wx'
1345
+ }
1346
+ if (checkIsAlipayEnv()) {
1347
+ return 'alipay'
1348
+ }
1349
+ return 'app';
1350
+ },
1351
+
1352
+
1353
+ /**
1354
+ * @description: 检测埋点堆栈
1355
+ */
1356
+ checkTrackStack() {
1357
+ logMsgFormat('checkTrackStack', `执行埋点数据堆栈检测`, 'log');
1358
+ const list = deepClone(this.trackStack);
1359
+ list.forEach(item => {
1360
+ const {eventID, eventPro, id} = item;
1361
+ logMsgFormat('checkTrackStack', `执行id值为${id} 的埋点数据再次上报`, 'log');
1362
+ this.track(eventID, eventPro);
1363
+ const index = this.trackStack.findIndex(cItem => cItem.id === id);
1364
+ if (index > -1) {
1365
+ this.trackStack.splice(index, 1);
1366
+ }
1367
+ });
1368
+ },
1369
+
1370
+
1371
+ /**
1372
+ * @description: 获取页面来源
1373
+ * @return {*}
1374
+ */
1375
+ getPageSource() {
1376
+ let path = null;
1377
+ if (checkIsBrowserEnv()) {
1378
+ path = location.href;
1379
+ } else {
1380
+ path = decodeURIComponent(getCurrentPagePath().path);
1381
+ }
1382
+ const withSource = path?.includes('source=');
1383
+ if (!withSource) {
1384
+ return 'click'
1385
+ }
1386
+ const validSource = ['copy', 'share', 'click', 'search'];
1387
+ const val = path.split('source=')[1];
1388
+ let source = 'click';
1389
+ if (val.includes('&')) {
1390
+ source = val.split('&')[0];
1391
+ } else {
1392
+ source = val;
1393
+ }
1394
+ if (validSource.includes(source)) {
1395
+ return source;
1396
+ }
1397
+ return 'click';
1398
+ },
1399
+
1400
+
1401
+ /**
1402
+ * @description: 获取当前位置信息
1403
+ */
1404
+ async getPositionInfo() {
1405
+ if (!this.locationInfo?.province) {
1406
+ try {
1407
+ const {location} = await this.getLocationInfo() || {};
1408
+ this.locationInfo = location || "";
1409
+ } catch (e) {
1410
+ logMsgFormat(`getLocationInfo`, '获取位置信息异常', 'error', e);
1411
+ this.locationInfo = {};
1412
+ }
1413
+ }
1414
+ return JSON.stringify(this.locationInfo);
1415
+ }
1416
+ };
1417
+
1418
+ const BridgeInfo = {
1419
+
1420
+ /**
1421
+ * @description: 初始化与移动端建立桥链接配置
1422
+ */
1423
+ initMobileBridgeGlobalConfig() {
1424
+ const device = getPlatformInfo();
1425
+ logMsgFormat('initMobileBridgeGlobalConfig', `开始初始化移动端桥链接配置,访问设备类型:${device}`);
1426
+ window["c2"] = {};
1427
+ if (device === 'ios') {
1428
+ this.initIOSCallbackEvConfig();
1429
+ }
1430
+ if (device === 'android') {
1431
+ this.initAndroidCallbackEvConfig();
1432
+ }
1433
+ logMsgFormat('initMobileBridgeGlobalConfig', `初始化移动端桥链接配置完成`);
1434
+ window.CreatorJsBridge = window.c2;
1435
+ },
1436
+
1437
+ /**
1438
+ * @description: 初始化IOS回调事件配置
1439
+ */
1440
+ initIOSCallbackEvConfig() {
1441
+ try {
1442
+ const _this = this;
1443
+ window.c2['iOS'] = {};
1444
+ window.c2['iOS']['callJS'] = function () {
1445
+ if (!window?.c2.iOS?.callJSCallback) {
1446
+ window.c2.iOS['callJSCallback'] = {};
1447
+ }
1448
+ logMsgFormat('initIOSCallbackEvConfig', `开始处理IOS设备回调事件,回调数据:${JSON.stringify(arguments)}`);
1449
+ _this.IOSCallbackEvFormat(arguments[0]);
1450
+ };
1451
+ } catch (e) {
1452
+ logMsgFormat('initIOSCallbackEvConfig', `初始化IOS回调事件配置异常`, 'error', e);
1453
+ }
1454
+ },
1455
+
1456
+ /**
1457
+ * @description: 初始化安卓回调事件配置
1458
+ */
1459
+ initAndroidCallbackEvConfig() {
1460
+ window.c2['sendDataWarpToWeb'] = (realCallback, callback, data) => {
1461
+ realCallback(data);
1462
+ };
1463
+ },
1464
+
1465
+ /**
1466
+ * @description: IOS设备回调事件处理
1467
+ */
1468
+ IOSCallbackEvFormat(res) {
1469
+ const {returnValue, funcName} = res;
1470
+ let returnVal = this.base64Decode(returnValue);
1471
+ returnVal = parseResData(returnVal);
1472
+ logMsgFormat('IOSCallbackEvFormat', `IOS设备回调事件处理开始,回调数据:${JSON.stringify(returnVal)}, 格式:${typeof returnVal}`);
1473
+ const fnId = funcName.split('_a')[0];
1474
+ const fnName = funcName.replace(fnId, '');
1475
+ const eventInfo = this.iosCallBackList.find(item => item.id === fnId);
1476
+ if (!eventInfo) {
1477
+ return;
1478
+ }
1479
+ const {resolveInfo, configInfo} = eventInfo;
1480
+ const {resDataFormat, resErrorFormat} = configInfo;
1481
+ if (fnName.includes('onFail') && resErrorFormat) {
1482
+ returnVal = resErrorFormat({
1483
+ isSuccess: false,
1484
+ errorMsg: deepClone(returnValue)
1485
+ });
1486
+ resolveInfo(returnVal);
1487
+ return;
1488
+ }
1489
+ if (resDataFormat) {
1490
+ returnVal = resDataFormat(returnVal);
1491
+ }
1492
+
1493
+ logMsgFormat('IOSCallbackEvFormat', `IOS设备回调事件处理完成,返回数据:${JSON.stringify(returnVal)}`);
1494
+ // 执行数据回传
1495
+ resolveInfo(returnVal);
1496
+
1497
+ // 从回执清单内剔除该数据
1498
+ const index = this.iosCallBackList.findIndex(item => item.id === fnId);
1499
+ this.iosCallBackList.splice(index, 1);
1500
+ },
1501
+
1502
+ /**
1503
+ * @description: 执行Base64编码
1504
+ * @param str 需要执行编码的字符串内容
1505
+ * @return {string}
1506
+ */
1507
+ base64Decode(str) {
1508
+ let keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
1509
+ let output = '';
1510
+ let chr1, chr2, chr3;
1511
+ let enc1, enc2, enc3, enc4;
1512
+ let i = 0;
1513
+ str = str.replace(/[^A-Za-z0-9\+\/\=]/g, '');
1514
+ while (i < str.length) {
1515
+ enc1 = keyStr.indexOf(str.charAt(i++));
1516
+ enc2 = keyStr.indexOf(str.charAt(i++));
1517
+ enc3 = keyStr.indexOf(str.charAt(i++));
1518
+ enc4 = keyStr.indexOf(str.charAt(i++));
1519
+ chr1 = (enc1 << 2) | (enc2 >> 4);
1520
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
1521
+ chr3 = ((enc3 & 3) << 6) | enc4;
1522
+ output = output + String.fromCharCode(chr1);
1523
+ if (enc3 != 64) {
1524
+ output = output + String.fromCharCode(chr2);
1525
+ }
1526
+ if (enc4 != 64) {
1527
+ output = output + String.fromCharCode(chr3);
1528
+ }
1529
+ }
1530
+ output = this._utf8_decode(output);
1531
+ return output;
1532
+ },
1533
+
1534
+ /**
1535
+ * @description: 执行UTF8编码
1536
+ * @param str 需要执行编码的字符串内容
1537
+ * @return {string}
1538
+ */
1539
+ _utf8_decode(str) {
1540
+ let string = '';
1541
+ let i = 0;
1542
+ let c = 0;
1543
+ let c3 = 0;
1544
+ let c2 = 0;
1545
+ while (i < str.length) {
1546
+ c = str.charCodeAt(i);
1547
+ if (c < 128) {
1548
+ string += String.fromCharCode(c);
1549
+ i++;
1550
+ } else if (c > 191 && c < 224) {
1551
+ c2 = str.charCodeAt(i + 1);
1552
+ string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
1553
+ i += 2;
1554
+ } else {
1555
+ c2 = str.charCodeAt(i + 1);
1556
+ c3 = str.charCodeAt(i + 2);
1557
+ string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
1558
+ i += 3;
1559
+ }
1560
+ }
1561
+ return string;
1562
+ },
1563
+
1564
+
1565
+ /**
1566
+ * @description: 检测移动端的模块回调处理
1567
+ */
1568
+ checkMobileModuleBack(moduleName, nativeEvName, isCustomEv) {
1569
+ const mName = isCustomEv ? 'custom' : moduleName;
1570
+ const evName = isCustomEv ? 'call' : nativeEvName;
1571
+ const callbackName = `${evName}Callback`;
1572
+ if (!window.c2.hasOwnProperty(mName)) {
1573
+ window.c2[mName] = {};
1574
+ }
1575
+ if (!window.c2[mName].hasOwnProperty(callbackName)) {
1576
+ window.c2[mName][callbackName] = {};
1577
+ }
1578
+ }
1579
+ };
1580
+
1581
+ let rum = null;
1582
+ let tracer = null;
1583
+ let platform = null;
1584
+ if (checkIsAppEnv()) {
1585
+ rum = uni && uni?.requireNativePlugin ? uni?.requireNativePlugin("GCUniPlugin-RUM") : null;
1586
+ tracer = uni && uni?.requireNativePlugin ? uni?.requireNativePlugin("GCUniPlugin-Tracer") : null;
1587
+ platform = uni && uni?.getSystemInfoSync ? uni.getSystemInfoSync().platform : null;
1588
+ } else {
1589
+ logMsgFormat('请求插件初始化', '未找到uni对象', 'warn');
1590
+ }
1591
+
1592
+
1593
+ const requestInfo = {
1594
+ defaults: {
1595
+ headers: {},
1596
+ baseURL: '',
1597
+ },
1598
+ interceptor: {
1599
+ request: null,
1600
+ response: null
1601
+ },
1602
+ requestOb: false,
1603
+
1604
+ /**
1605
+ * @description: 接口请求
1606
+ */
1607
+ request(options = {}) {
1608
+ return new Promise((resolve, reject) => {
1609
+ let requestConfig = deepClone(options);
1610
+ if (this.interceptor.request && typeof this.interceptor.request === 'function' && !options.ignore) {
1611
+ requestConfig = this.interceptor.request(options);
1612
+ // 若拦截器返回false则不发送请求
1613
+ if (!requestConfig) {
1614
+ resolve(false);
1615
+ return;
1616
+ }
1617
+ }
1618
+ // 如果是APP请求,走观测云的请求处理
1619
+ if (checkIsAppEnv() && this.requestOb && Boolean(rum) && Boolean(tracer)) {
1620
+ try {
1621
+ logMsgFormat('request', `走服务监控平台的请求配置`, 'log');
1622
+ this.executeCloudObRequest(requestConfig, resolve, reject);
1623
+ } catch (e) {
1624
+ logMsgFormat('request', `走服务监控平台的请求配置失败`, 'error', e);
1625
+ }
1626
+ } else {
1627
+ logMsgFormat('request', `走uni的请求配置`, 'log');
1628
+ this.executeNormalRequest(requestConfig, resolve, reject);
1629
+ }
1630
+ });
1631
+ },
1632
+
1633
+ /**
1634
+ * @description: 执行接口服务监控
1635
+ */
1636
+ executeCloudObRequest(options, resolve, reject) {
1637
+ let key = getUUID();
1638
+ const result = this.checkCloudObRequestHeader(options, key);
1639
+ if (!result) {
1640
+ return;
1641
+ }
1642
+ const {traceHeader, filter} = result;
1643
+ rum.startResource({
1644
+ 'key': key,
1645
+ });
1646
+ let responseHeader;
1647
+ let responseBody;
1648
+ let resourceStatus;
1649
+ uni.request({
1650
+ url: `${this.defaults.baseURL}${options.url}`,
1651
+ method: options.method,
1652
+ header: traceHeader,
1653
+ data: options.data,
1654
+ timeout: options.timeout,
1655
+ withCredentials: options?.withCredentials || undefined,
1656
+ success: (res) => {
1657
+ logMsgFormat('executeCloudObRequest', `接口:${options.url},请求成功`, 'log');
1658
+ if (!filter) {
1659
+ responseHeader = res.header;
1660
+ responseBody = res.data.toString();
1661
+ resourceStatus = res.statusCode;
1662
+ }
1663
+ if (!isEmpty(options.success)) {
1664
+ options.success(res);
1665
+ }
1666
+ if (this.interceptor.response && typeof this.interceptor.response === 'function' && !options.ignore) {
1667
+ const result = this.interceptor.response(res);
1668
+ resolve(result);
1669
+ return;
1670
+ }
1671
+ resolve(res);
1672
+ },
1673
+ fail: (err) => {
1674
+ logMsgFormat('executeCloudObRequest', `接口:${options.url},请求失败`, 'error', err);
1675
+ if (!filter) {
1676
+ responseBody = err?.errMsg;
1677
+ }
1678
+ if (!isEmpty(options?.fail)) {
1679
+ options.fail(err);
1680
+ }
1681
+ reject(err);
1682
+ },
1683
+ complete: () => {
1684
+ logMsgFormat('executeCloudObRequest', `接口:${options.url},请求完成`, 'log');
1685
+ if (!filter) {
1686
+ logMsgFormat('executeCloudObRequest', `无filter配置的数据信息::::key值:${key};URL地址:${options.url};`);
1687
+ rum.stopResource({
1688
+ 'key': key,
1689
+ });
1690
+ const resourceData = {
1691
+ 'url': `${this.defaults.baseURL}${options.url}`,
1692
+ 'httpMethod': options.method,
1693
+ 'requestHeader': traceHeader,
1694
+ 'responseHeader': responseHeader,
1695
+ 'responseBody': responseBody,
1696
+ 'resourceStatus': resourceStatus,
1697
+ };
1698
+ rum.addResource({
1699
+ 'key': key, 'content': resourceData
1700
+ });
1701
+ }
1702
+ if (Boolean(options?.complete)) {
1703
+ options?.complete();
1704
+ }
1705
+ }
1706
+ });
1707
+ },
1708
+
1709
+ /**
1710
+ * @description: 检测服务请求监控配置请求头
1711
+ */
1712
+ checkCloudObRequestHeader(options, key) {
1713
+ let filter;
1714
+ if (isEmpty(options?.filterPlatform)) {
1715
+ logMsgFormat('executeCloudObRequest', `options.filterPlatform:${options.filterPlatform}`, 'log');
1716
+ filter = false;
1717
+ } else {
1718
+ filter = options?.filterPlatform?.includes(platform);
1719
+ logMsgFormat('executeCloudObRequest', `platform:${options.filterPlatform}`, 'log');
1720
+ }
1721
+ logMsgFormat('executeCloudObRequest', `rum:${rum},tracer:${tracer}`, 'log');
1722
+ let traceHeader = {};
1723
+ if (!filter) {
1724
+ // trace 关联 RUM
1725
+ traceHeader = tracer?.getTraceHeader({
1726
+ 'key': key,
1727
+ 'url': options.url,
1728
+ });
1729
+ }
1730
+ logMsgFormat('executeCloudObRequest', `是否读取到【tracer】插件配置:${Boolean(tracer)},是否读取到【rum】插件配置:${Boolean(rum)}`, 'log');
1731
+ if (!rum || !tracer) {
1732
+ logMsgFormat('executeCloudObRequest', `请配置服务监控平台原生插件`, 'log');
1733
+ return false;
1734
+ }
1735
+ traceHeader = Object.assign({}, traceHeader, options.header);
1736
+ traceHeader = Object.assign({}, traceHeader, this.defaults.headers);
1737
+ return {
1738
+ traceHeader,
1739
+ filter
1740
+ }
1741
+ },
1742
+
1743
+ /**
1744
+ * @description: 执行常规接口请求
1745
+ * @param {*} options
1746
+ * @param {*} resolve
1747
+ * @param {*} reject
1748
+ * @return {*}
1749
+ */
1750
+ executeNormalRequest(options, resolve, reject) {
1751
+ const {url, header, data, method} = options || {};
1752
+ const headers = Object.assign({}, this.defaults.headers, header);
1753
+ uni.request({
1754
+ url: `${this.defaults.baseURL}${url}`,
1755
+ header: headers,
1756
+ data,
1757
+ method,
1758
+ withCredentials: options?.withCredentials || undefined,
1759
+ success: (res) => {
1760
+ logMsgFormat('normalRequest', `接口:${url},请求成功`, 'log');
1761
+ if (this.interceptor.response && typeof this.interceptor.response === 'function' && !options.ignore) {
1762
+ const result = this.interceptor.response(res);
1763
+ resolve(result);
1764
+ return;
1765
+ }
1766
+ resolve(res);
1767
+ },
1768
+ fail: err => {
1769
+ logMsgFormat('normalRequest', `接口:${url},请求异常`, 'error', err);
1770
+ reject(err);
1771
+ }
1772
+ });
1773
+ },
1774
+
1775
+ };
1776
+
1777
+ const publicMethod = {
1778
+
1779
+ /**
1780
+ * @description: 自动隐藏原生APP分享、评价按钮
1781
+ */
1782
+ resetMenuBtnConfig() {
1783
+ logMsgFormat('hideNativeBtn', `隐藏原生APP分享、评价按钮`, 'log');
1784
+ const config = {
1785
+ share: {
1786
+ show: false,
1787
+ },
1788
+ comment: {
1789
+ show: false,
1790
+ },
1791
+ favorite: {
1792
+ show: true
1793
+ }
1794
+ };
1795
+ try {
1796
+ this.menuBtnConfig(config);
1797
+ this.pageChangeEv((routeInfo) => {
1798
+ if (!this.autoUpdate) {
1799
+ logMsgFormat(`resetMenuBtnConfig`, `业务侧设置不自动重置胶囊按钮,中断配置动作`);
1800
+ return;
1801
+ }
1802
+ const {options} = routeInfo;
1803
+ const {xybModuleCode} = options || {};
1804
+ if (xybModuleCode && this.autoConfigMenuBtn) {
1805
+ logMsgFormat('resetMenuBtnConfig', `页面拦截事件生效 自动设置原生APP分享、评价按钮,配置信息:${JSON.stringify(routeInfo)}`, 'log');
1806
+ this.menuBtnConfig({
1807
+ share: {
1808
+ show: true,
1809
+ code: xybModuleCode,
1810
+ type: 4
1811
+ },
1812
+ comment: {
1813
+ show: true,
1814
+ code: xybModuleCode,
1815
+ type: 4
1816
+ },
1817
+ favorite: {
1818
+ show: true
1819
+ }
1820
+ });
1821
+ return;
1822
+ }
1823
+ logMsgFormat('resetMenuBtnConfig', `页面拦截事件生效 自动重置原生APP分享、评价按钮配置信息`, 'log');
1824
+ this.menuBtnConfig(config);
1825
+ });
1826
+ } catch (e) {
1827
+ logMsgFormat('resetMenuBtnConfig', `配置APP的胶囊按钮清单显示失败,请检查参数是否正确`, 'error', e);
1828
+ }
1829
+ },
1830
+
1831
+ /**
1832
+ * @description: 页面路径变化事件监听
1833
+ */
1834
+ pageChangeEv(fn) {
1835
+ if (!uni) {
1836
+ return;
1837
+ }
1838
+ const list = ['navigateTo', 'redirectTo', 'switchTab', 'reLaunch', 'navigateBack', 'onBackPress'];
1839
+ list.forEach(item => {
1840
+ try {
1841
+ uni.addInterceptor(item, {
1842
+ invoke(res) {
1843
+ try {
1844
+ const {url} = res;
1845
+ let routeInfo = {
1846
+ options: {},
1847
+ path: null,
1848
+ route: null,
1849
+ };
1850
+ let urlInfo = decodeURIComponent(url);
1851
+ routeInfo.path = urlInfo;
1852
+ routeInfo.route = urlInfo.split('?')[0];
1853
+ if (urlInfo?.includes('xybModuleCode=')) {
1854
+ console.log(`🚀当前页面路径信息:${urlInfo}`);
1855
+ routeInfo.options.xybModuleCode = getUrlParam('xybModuleCode', urlInfo);
1856
+ }
1857
+ if (urlInfo?.includes('?')) {
1858
+ routeInfo.route = urlInfo.split('?')[0];
1859
+ }
1860
+ if (item?.includes('Back')) {
1861
+ routeInfo = getCurrentPagePath(item?.includes('Back'));
1862
+ }
1863
+ logMsgFormat('pageChangeEv', `页面路径发生了变化,当前页面路径:${routeInfo.path}`, 'log');
1864
+ if (typeof fn === 'function') {
1865
+ fn(routeInfo);
1866
+ }
1867
+ } catch (e) {
1868
+ console.log(`🚀 错误信息:::::`, e);
1869
+ logMsgFormat('pageChangeEv', `拦截路径变化时发生了异常`, 'error', e);
1870
+ }
1871
+ return true;
1872
+ }
1873
+ });
1874
+ } catch (e) {
1875
+ logMsgFormat('pageChangeEv', `执行页面变化拦截异常`, 'error', e);
1876
+ }
1877
+ });
1878
+ },
1879
+
1880
+ /**
1881
+ * @description: 配置APP的胶囊按钮清单显示
1882
+ */
1883
+ menuBtnConfig(config = {}) {
1884
+ logMsgFormat('menuBtnConfig', `配置APP胶囊按钮清单显示,配置信息:${JSON.stringify(config)}`, 'log');
1885
+ let flag = true;
1886
+ for (let i in config) {
1887
+ const item = config[i];
1888
+ if (typeof item !== 'object') {
1889
+ flag = false;
1890
+ logMsgFormat('menuBtnConfig', `配置参数错误`, 'error', '请传入一个Object配置数据');
1891
+ break;
1892
+ }
1893
+ }
1894
+ if (!flag) {
1895
+ return;
1896
+ }
1897
+ if (checkIsWebviewEnv()) {
1898
+ this.miniAppH5SendMsgToApp(null, 'menuBtnConfig', config, '配置APP的胶囊按钮清单显示');
1899
+ return;
1900
+ }
1901
+ if (checkIsBrowserEnv() || !uni || !uni?.sendNativeEvent) {
1902
+ logMsgFormat('menuBtnConfig', `配置APP胶囊按钮清单显示功能无法在非UNI环境运行`, 'log');
1903
+ return;
1904
+ }
1905
+ try {
1906
+ logMsgFormat('menuBtnConfig', `开始执行配置APP胶囊按钮清单显示`, 'log');
1907
+ uni?.sendNativeEvent('Util_MiniAppConfigMenu', config);
1908
+ } catch (e) {
1909
+ logMsgFormat('menuBtnConfig', `配置APP的胶囊按钮清单显示时发生异常`, 'error', e);
1910
+ }
1911
+ },
1912
+ };
1913
+
1914
+ const browserInfo = {
1915
+
1916
+ /**
1917
+ * @description: 执行浏览器的原生事件
1918
+ * @param resolve Promise
1919
+ * @param dataInfo
1920
+ * @param evData
1921
+ * @param evConfig
1922
+ */
1923
+ executeBrowserEvent(resolve, dataInfo = {}, evData = {}, evConfig = {}) {
1924
+ const envName = checkIsWeChatEnv() ? '微信小程序' : checkIsAlipayEnv() ? '支付宝小程序' : "浏览器";
1925
+ const {eventName, description, browserEvName, bResDataFormat, bReqDataFormat, reqDataFormat} = evConfig;
1926
+ const evFormatMap = {
1927
+ "authFace": "executeAuthFaceInBrowser",
1928
+ "getLocationInfo": "executeGetLocationInBrowser",
1929
+ "startNavigation": "startNavigationInBrowser",
1930
+ "fileUpload": "executeFileUploadInBrowser",
1931
+ "chooseImg": "executeImageChooseInBrowser",
1932
+ "executePayment": "executePayment",
1933
+ };
1934
+ const isNavigation = eventName === 'startNavigation';
1935
+ const reqParams = isNavigation ? evData : dataInfo;
1936
+ logMsgFormat("normalEvDataTransition", `开始调用${envName}嵌套H5的能力,事件名称:${eventName},入参:${JSON.stringify(reqParams)},配置信息:${JSON.stringify(evConfig)}`);
1937
+ const evName = evFormatMap[eventName];
1938
+ if (evName) {
1939
+ this[evName](resolve, reqParams, evConfig);
1940
+ return;
1941
+ }
1942
+ if (!browserEvName) {
1943
+ resolve({
1944
+ isSuccess: false,
1945
+ code: -1,
1946
+ message: `非常抱歉,${description}功能无法在当前环境中使用`
1947
+ });
1948
+ return;
1949
+ }
1950
+ const reqData = reqDataFormat ? reqDataFormat(dataInfo) : bReqDataFormat ? bReqDataFormat(dataInfo) : dataInfo;
1951
+ if (checkIsAlipayEnv() || checkIsWeChatEnv()) {
1952
+ this.executeMPBrowserEvent(resolve, browserEvName, dataInfo, eventName);
1953
+ return;
1954
+ }
1955
+ this.executeNativeBrowserEv(resolve, browserEvName, reqData, bResDataFormat);
1956
+ },
1957
+
1958
+ /**
1959
+ * @description: 执行微信/支付宝小程序的事件
1960
+ */
1961
+ executeMPBrowserEvent(resolve, browserEvName, dataInfo, eventName) {
1962
+ logMsgFormat(`executeMPBrowserEvent`, `配置信息:${JSON.stringify(dataInfo)}`);
1963
+ let config = deepClone(dataInfo);
1964
+ logMsgFormat(`executeMPBrowserEvent`, `配置信息:${JSON.stringify(config)}`);
1965
+
1966
+ config['success'] = (res) => {
1967
+ logMsgFormat(`executeMPBrowserEvent`, `执行:${eventName}事件完成,返回结果:${JSON.stringify(res)}`);
1968
+ };
1969
+ config['fail'] = (err) => {
1970
+ logMsgFormat(`executeMPBrowserEvent`, `执行:${eventName}事件失败,错误信息:${JSON.stringify(err)}`);
1971
+ };
1972
+ logMsgFormat(`executeWeChatBrowserEv`, `${eventName},配置信息:${JSON.stringify(config)}`);
1973
+ checkIsWeChatEnv() ? window.wx[browserEvName](config) : window.my[browserEvName](config);
1974
+ },
1975
+
1976
+ /**
1977
+ * @description: 执行浏览器原生事件
1978
+ */
1979
+ executeNativeBrowserEv(evName, dataInfo) {
1980
+ let config = deepClone(dataInfo);
1981
+ config['success'] = function (res) {
1982
+ console.log(res);
1983
+ };
1984
+ config['fail'] = function (err) {
1985
+ console.error(err);
1986
+ };
1987
+ window.uni[evName](config);
1988
+ }
1989
+ };
1990
+
1991
+ const authFaceInfo = {
1992
+
1993
+ /**
1994
+ * @description 在微信/支付宝环境下执行人脸验证操作
1995
+ * @param resolve
1996
+ * @param dataInfo
1997
+ * @param evConfig
1998
+ */
1999
+ executeAuthFaceInBrowser(resolve, dataInfo = {}, evConfig = {}) {
2000
+ const hashChangeEv = function (val) {
2001
+ // 从URL获取 faceKey(优先从 hash 获取,然后从 query 获取)
2002
+ let faceKey = getUrlParam('faceKey', window?.location?.href);
2003
+ logMsgFormat(`executeAuthFaceInBrowser`, `获取到的faceKey参数值::::${faceKey}`);
2004
+ if (!window?.location?.href.includes('faceKey')) {
2005
+ return;
2006
+ }
2007
+ // 向 webview 发送消息
2008
+ const resultData = {
2009
+ isSuccess: Boolean(faceKey),
2010
+ certifyId: faceKey ? `MINI_${faceKey}` : null,
2011
+ portrait: null,
2012
+ errorMsg: Boolean(faceKey) ? null : '人脸验证失败,请检查参数信息'
2013
+ };
2014
+ // 执行监听器移除
2015
+ window.removeEventListener('hashchange', hashChangeEv);
2016
+ // 返回结果
2017
+ setTimeout(() => {
2018
+ logMsgFormat(`executeAuthFaceInBrowser`, `执行验证结果回抛给业务侧:${JSON.stringify(resultData)}`);
2019
+ resolve(resultData);
2020
+ }, 100);
2021
+ };
2022
+ // 添加监听器
2023
+ window.addEventListener('hashchange', hashChangeEv);
2024
+
2025
+ // 构建跳转URL
2026
+ const encodedReturnUrl = encodeURIComponent(window.location.href);
2027
+
2028
+ // 构建参数
2029
+ const {certNo, name} = dataInfo;
2030
+ const encodedIdCard = encodeURIComponent(certNo);
2031
+ let jumpUrl = `/pages/sdk/sdk?redirectUrl=${encodedReturnUrl}&type=authFace&idCard=${encodedIdCard}&name=${name}`;
2032
+ // 根据环境跳转
2033
+ if (checkIsWeChatEnv()) {
2034
+ openWeChatMiniApp(jumpUrl, resolve);
2035
+ return;
2036
+ }
2037
+ if (checkIsAlipayEnv()) {
2038
+ openAlipayMiniApp(jumpUrl, resolve);
2039
+ return;
2040
+ }
2041
+ logMsgFormat(`executeAuthFaceInBrowser`, `当前环境不支持人脸识别`, 'warning');
2042
+ resolve({
2043
+ isSuccess: false,
2044
+ code: -1,
2045
+ message: `当前环境下不支持人脸识别验证功能`
2046
+ });
2047
+ },
2048
+
2049
+ };
2050
+
2051
+ const locationInfo = {
2052
+ locationCheck: false,
2053
+ locationEvList: [],
2054
+
2055
+
2056
+ /**
2057
+ * @description: 检测获取定位的堆栈信息
2058
+ */
2059
+ checkLocationEvStation() {
2060
+ this.locationEvList.forEach(item => {
2061
+ this.getLocationInWeChat(item.resolveInfo, item.id);
2062
+ });
2063
+ },
2064
+
2065
+ /**
2066
+ * @description 在微信/支付宝环境中获取位置信息
2067
+ * @param resolve
2068
+ */
2069
+ executeGetLocationInBrowser(resolve) {
2070
+ logMsgFormat(`executeGetLocationInBrowser`, `在微信/支付宝浏览器中获取定位信息`);
2071
+
2072
+ if (checkIsAlipayEnv()) {
2073
+ this.getLocationInAliPay(resolve);
2074
+ return;
2075
+ }
2076
+ if (checkIsWeChatEnv()) {
2077
+ this.getLocationInWeChat(resolve);
2078
+ return;
2079
+ }
2080
+ resolve({
2081
+ code: -1,
2082
+ isSuccess: false,
2083
+ message: "当前环境无法支持位置信息获取,请检查是否为湘易办相关环境"
2084
+ });
2085
+ },
2086
+
2087
+ /**
2088
+ * @description 在微信下获取位置信息
2089
+ * @param resolve
2090
+ * @param evId
2091
+ */
2092
+ getLocationInWeChat(resolve, evId) {
2093
+ if (!this.weChatConfigReady) {
2094
+ logMsgFormat(`getLocationInWeChat`, `微信SDK尚未初始化完毕,先行进行堆栈,待微信SDK初始化后,统一调用`);
2095
+ this.locationEvList.push({
2096
+ id: getUUID(),
2097
+ resolveInfo: resolve
2098
+ });
2099
+ return;
2100
+ }
2101
+ if (this.locationCheck) {
2102
+ logMsgFormat(`getLocationInWeChat`, `已缓存签名信息,直接调用对应API获取位置信息`);
2103
+ this.executeGetLocationInfoData(resolve, evId);
2104
+ return;
2105
+ }
2106
+ this.executeGetLocationInfoData(resolve, evId);
2107
+ },
2108
+
2109
+
2110
+ /**
2111
+ * @description 执行位置数据获取
2112
+ * @param resolve
2113
+ * @param evId
2114
+ */
2115
+ executeGetLocationInfoData(resolve, evId) {
2116
+ logMsgFormat(`executeGetLocationInfoData`, `在微信环境中获取位置信息`);
2117
+ window?.wx?.getLocation({
2118
+ type: 'wgs84',
2119
+ success: res => {
2120
+ this.locationCheck = true;
2121
+ const addInfo = wgsToGCJ02(res?.longitude, res?.latitude);
2122
+ resolve({
2123
+ isSuccess: true,
2124
+ location: {
2125
+ longitude: addInfo?.longitude,
2126
+ latitude: addInfo?.latitude
2127
+ },
2128
+ message: "微信小程序下只提供经纬度"
2129
+ });
2130
+ // logMsgFormat(`executeGetLocationInfoData`, `调用微信获取位置信息完成,结果是:${JSON.stringify(res)}`);
2131
+ // this.executeGetDetailLocation(resolve, res, evId);
2132
+ },
2133
+ fail: err => {
2134
+ resolve({
2135
+ isSuccess: false,
2136
+ message: "调用微信获取位置信息失败,请联系管理员"
2137
+ });
2138
+ logMsgFormat(`executeGetLocationInfoData`, `调用微信获取位置信息失败,信息是:${JSON.stringify(err)}`);
2139
+ }
2140
+ });
2141
+ },
2142
+
2143
+ /**
2144
+ * @description 获取详细位置信息
2145
+ * @param resolve
2146
+ * @param res
2147
+ * @param evId
2148
+ * @param isAlipay
2149
+ */
2150
+ executeGetDetailLocation(resolve, res, evId, isAlipay = false) {
2151
+ const lat = res?.latitude;
2152
+ const lng = res?.longitude;
2153
+ uni.request({
2154
+ url: `https://api.map.baidu.com/reverse_geocoding/v3/?ak=fensaAMmxRxkRCadisCyAvZpwj6YCwtD&output=json&coordtype=wgs84ll&location=${lat},${lng}`,
2155
+ method: "GET",
2156
+ success: dataInfo => {
2157
+ const {data} = dataInfo?.data || {};
2158
+ logMsgFormat(`executeGetDetailLocation`, `位置信息结果:${JSON.stringify(data)}`);
2159
+ if (!data?.longitude) {
2160
+ resolve(this.formatLocationData(data, isAlipay));
2161
+ }
2162
+ const resultInfo = this.formatLocationData(data, isAlipay);
2163
+ resolve(resultInfo);
2164
+ if (evId) {
2165
+ logMsgFormat(`executeGetDetailLocation`, `已成功获取到定位信息,清除该事件的堆栈:${evId}`);
2166
+ const index = this.locationEvList.findIndex(item => item.id === evId);
2167
+ if (index !== -1) {
2168
+ this.locationEvList.splice(index, 1);
2169
+ }
2170
+ }
2171
+ },
2172
+ fail: err => {
2173
+ logMsgFormat(`executeGetDetailLocation`, `获取位置信息失败`, 'error', JSON.stringify(err));
2174
+ }
2175
+ });
2176
+ },
2177
+
2178
+ /**
2179
+ * @description: 格式化位置信息数据
2180
+ */
2181
+ formatLocationData(dataInfo = {}, isAlipay = false) {
2182
+ const addressInfo = dataInfo?.result || {};
2183
+ const {lng, lat} = addressInfo?.location || {};
2184
+ const {cityCode, formatted_address} = addressInfo || {};
2185
+ const {district, city, country, adCode, province} = addressInfo?.addressComponent || {};
2186
+ console.log(`formatLocationData`, `是否为支付宝调用:${isAlipay}`);
2187
+ const replaceAdd = isAlipay ? addressInfo?.location : BaiduToGCJ02(lng, lat);
2188
+ const resultInfo = {
2189
+ isSuccess: true,
2190
+ location: {
2191
+ district,
2192
+ city,
2193
+ longitude: replaceAdd?.lng,
2194
+ country,
2195
+ cityCode,
2196
+ adCode,
2197
+ address: formatted_address,
2198
+ latitude: replaceAdd?.lat,
2199
+ province
2200
+ }
2201
+ };
2202
+ logMsgFormat(`executeGetDetailLocation`, `获取位置信息调用完成,结果:${JSON.stringify(resultInfo)}`);
2203
+ return resultInfo;
2204
+ },
2205
+
2206
+
2207
+ /**
2208
+ * @description 在支付宝下获取位置信息
2209
+ * @param resolve
2210
+ */
2211
+ getLocationInAliPay(resolve) {
2212
+ window?.my?.getLocation({
2213
+ type: 'wgs84',
2214
+ success: (res) => {
2215
+ deepClone(res);
2216
+ resolve({
2217
+ isSuccess: true,
2218
+ location: {
2219
+ longitude: res?.longitude,
2220
+ latitude: res?.latitude,
2221
+ },
2222
+ message: "支付宝小程序只提供经纬度"
2223
+ });
2224
+ // logMsgFormat(`getLocationInAliPay`, `支付宝下获取位置信息完成:::${JSON.stringify(dataInfo)}`);
2225
+ // const addInfo = GCJ02ToWGS84(res.longitude, res?.latitude);
2226
+ // logMsgFormat(`getLocationInAliPay`, `GCJ02转WGS84后的坐标值:${JSON.stringify(addInfo)}`);
2227
+ // dataInfo.longitude = addInfo?.lat;
2228
+ // dataInfo.latitude = addInfo?.lng;
2229
+ // this.executeGetDetailLocation(resolve, dataInfo, null, true);
2230
+ },
2231
+ fail: (err) => {
2232
+ logMsgFormat(`getLocationInAliPay`, `获取位置信息失败`, 'error', err);
2233
+ resolve({
2234
+ code: -1,
2235
+ isSuccess: false,
2236
+ message: "获取位置信息失败"
2237
+ });
2238
+ }
2239
+ });
2240
+ },
2241
+ };
2242
+
2243
+ const imgChooseInfo = {
2244
+
2245
+ /**
2246
+ * @description: 执行浏览器下的图片选择功能
2247
+ */
2248
+ executeImageChooseInBrowser(resolve, dataInfo, evConfig) {
2249
+ const {count, sizeType, sourceType} = dataInfo;
2250
+ const {bResDataFormat} = evConfig;
2251
+ if (checkIsWeChatEnv() || checkIsAlipayEnv()) {
2252
+ const config = {
2253
+ count: count || 9,
2254
+ mediaType: ['image'],
2255
+ sizeType: sizeType || ['original', 'compressed'],
2256
+ sourceType: sourceType || ['album'],
2257
+ success: res => {
2258
+ if (res?.success) {
2259
+ bResDataFormat ? resolve(bResDataFormat(res)) : resolve(res);
2260
+ }
2261
+ logMsgFormat(`executeChooseImageInWeChat`, `微信/支付宝环境下执行选择图片API执行完毕,结果:${JSON.stringify(res)}`);
2262
+ },
2263
+ fail: err => {
2264
+ logMsgFormat(`executeChooseImageInWeChat`, `微信/支付宝环境下执行选择图片API执行失败,结果:${JSON.stringify(err)}`);
2265
+ }
2266
+ };
2267
+ checkIsAlipayEnv() ? window.my.chooseImage(config) : window.wx.chooseImage(config);
2268
+ return;
2269
+ }
2270
+
2271
+ resolve({
2272
+ isSuccess: false,
2273
+ code: -1,
2274
+ message: "目前环境暂不支持,敬请期待"
2275
+ });
2276
+ },
2277
+ };
2278
+
2279
+ const navigationInfo = {
2280
+ navigationCheck: false,
2281
+
2282
+ /**
2283
+ * @description 执行导航功能
2284
+ * @param resolve
2285
+ * @param dataInfo
2286
+ */
2287
+ startNavigationInBrowser(resolve, dataInfo = {}) {
2288
+ const returnUrl = encodeURIComponent(window?.location?.href);
2289
+ const {lat, lng, address, name, dinateType} = dataInfo;
2290
+ let jumpUrl = `/pages/sdk/sdk?redirectUrl=${returnUrl}&type=navigation&latitude=${lat}&longitude=${lng}&address=${address}&name=${name}`;
2291
+ if (dinateType && dinateType !== 'GCJ02') {
2292
+ const addressInfo = replaceCoordinate(dataInfo);
2293
+ const {destinationLatitude, destinationLongitude} = addressInfo;
2294
+ jumpUrl = `/pages/sdk/sdk?redirectUrl=${returnUrl}&type=navigation&latitude=${destinationLatitude}&longitude=${destinationLongitude}&address=${address}&name=${name}`;
2295
+ }
2296
+ logMsgFormat('startNavigationInBrowser', `跳转目标URL:${jumpUrl}`);
2297
+ if (checkIsWeChatEnv()) {
2298
+ openWeChatMiniApp(jumpUrl, resolve);
2299
+ return;
2300
+ }
2301
+ if (checkIsAlipayEnv()) {
2302
+ openAlipayMiniApp(jumpUrl, resolve);
2303
+ return;
2304
+ }
2305
+ logMsgFormat(`startNavigationInBrowser`, `导航功能无法在当前环境下执行`);
2306
+ resolve({
2307
+ isSuccess: false,
2308
+ code: -1,
2309
+ message: `导航功能无法在当前环境下执行,请检查是否为微信/支付宝小程序的浏览器环境中`
2310
+ });
2311
+ }
2312
+ };
2313
+
2314
+ const getMsgFromH5 = {
2315
+ // 实例信息
2316
+ wvInfo: null,
2317
+ // 是否为鸿蒙设备
2318
+ isHarmony: false,
2319
+ // 是否完成了设备类型检测
2320
+ isCheckDevice: false,
2321
+
2322
+ /**
2323
+ * @description: 初始化消息通讯
2324
+ * @param args 参数
2325
+ * @return
2326
+ */
2327
+ async initMessage(...args) {
2328
+ const evInfo = args[0];
2329
+ await this.checkDeviceInfo();
2330
+ await this.initVMInfo(args[2]);
2331
+ if (checkIsBrowserEnv()) {
2332
+ window.addEventListener('message', e => {
2333
+ logMsgFormat('initMessage', `浏览器webview接收到的消息内容,${JSON.stringify(e)}`, 'log');
2334
+ this.getMsgFromH5(e);
2335
+ });
2336
+ } else {
2337
+ logMsgFormat('initMessage', `非浏览器中的webview接收到的消息内容,${JSON.stringify(evInfo)}`, 'log');
2338
+ this.getMsgFromH5(evInfo);
2339
+ }
2340
+ },
2341
+
2342
+ /**
2343
+ * @description: 检测设备信息
2344
+ */
2345
+ checkDeviceInfo() {
2346
+ if (this.isCheckDevice) {
2347
+ return;
2348
+ }
2349
+ this.isCheckDevice = true;
2350
+ uni.sendNativeEvent("System_getAppInfo", {}, res => {
2351
+ this.isHarmony = res?.platform?.toLowerCase().includes('harmony');
2352
+ });
2353
+ },
2354
+
2355
+ /**
2356
+ * @description: 初始化实例信息
2357
+ */
2358
+ initVMInfo(vmInfo) {
2359
+ if (this.wvInfo) {
2360
+ return;
2361
+ }
2362
+ if (this.isHarmony) {
2363
+ this.wvInfo = uni.createWebviewContext("webview", vmInfo);
2364
+ return;
2365
+ }
2366
+ try {
2367
+ this.wvInfo = vmInfo;
2368
+ if (vmInfo?.$scope?.$getAppWebview()) {
2369
+ this.wvInfo = vmInfo.$scope.$getAppWebview().children()[0];
2370
+ }
2371
+ } catch (e) {
2372
+ logMsgFormat('initMessage', `初始化消息模块,是否包含wvInfo:${typeof this.wvInfo?.evalJS}`);
2373
+ }
2374
+ },
2375
+
2376
+
2377
+ /**
2378
+ * @description: 从H5获取消息内容
2379
+ * @param evInfo 消息内容
2380
+ * @return
2381
+ */
2382
+ getMsgFromH5(evInfo = {}) {
2383
+ let msgData = this.getMsgDataFromH5(evInfo);
2384
+ const {origin} = evInfo || {};
2385
+ const {href} = location || {};
2386
+ if (checkIsBrowserEnv() && href?.includes(origin)) {
2387
+ return false;
2388
+ }
2389
+ const {isH5Send, methodName, methodData} = msgData || {};
2390
+ if (!isH5Send) {
2391
+ return false;
2392
+ }
2393
+ if (!methodName) {
2394
+ logMsgFormat('getMsgFromH5', `请传入需要执行的事件名称`, 'warn');
2395
+ return false;
2396
+ }
2397
+ if (methodData === null || methodData === undefined) {
2398
+ logMsgFormat('getMsgFromH5', `请传入需要执行的事件数据`, 'warn');
2399
+ return false;
2400
+ }
2401
+ logMsgFormat('getMsgFromH5', `需要执行的事件名称【${methodName}】,需要执行的事件数据【${JSON.stringify(methodData)}】,是否为H5发送的消息【${isH5Send}】`, 'log');
2402
+ if (!this[methodName]) {
2403
+ logMsgFormat('getMsgFromH5', `【${methodName}】事件不存在`, 'warn');
2404
+ return;
2405
+ }
2406
+ this.executeH5MethodName(methodName, msgData);
2407
+ },
2408
+
2409
+ /**
2410
+ * @description: 执行H5想调用的事件
2411
+ * @param methodName 事件名称
2412
+ * @param msgData 消息数据
2413
+ * @return
2414
+ */
2415
+ executeH5MethodName(methodName, msgData) {
2416
+ const {msgId, methodData} = msgData;
2417
+ try {
2418
+ const str = this[methodName].toString();
2419
+ logMsgFormat('executeH5MethodName', `【${methodName}】方法定义:${str}`, 'log');
2420
+ if (str.includes('Promise')) {
2421
+ this[methodName](methodData).then(res => {
2422
+ logMsgFormat('executeH5MethodName', `${methodName}方法执行结果:${JSON.stringify(res)}`, 'log');
2423
+ let data = res;
2424
+ try {
2425
+ data = JSON.parse(res);
2426
+ } catch (e) {
2427
+ logMsgFormat('executeH5MethodName', `强制给数据进行序列化失败`, 'error', e);
2428
+ }
2429
+ this.postMsgToH5({
2430
+ msgId,
2431
+ sourceMethod: methodName,
2432
+ resultInfo: data,
2433
+ isWebviewSend: true,
2434
+ resultMessage: `执行${methodName}方法完成`
2435
+ });
2436
+ }).catch(e => {
2437
+ logMsgFormat('executeH5MethodName', `${methodName}方法执行失败`, 'error', e);
2438
+ this.postMsgToH5({
2439
+ msgId,
2440
+ sourceMethod: methodName,
2441
+ resultInfo: null,
2442
+ isWebviewSend: true,
2443
+ resultMessage: `执行${methodName}方法失败,具体错误信息,请查看控制台`
2444
+ });
2445
+ });
2446
+ return;
2447
+ }
2448
+ this[methodName](methodData);
2449
+ this.postMsgToH5({
2450
+ msgId,
2451
+ sourceMethod: methodName,
2452
+ resultInfo: null,
2453
+ isWebviewSend: true,
2454
+ resultMessage: `执行${methodName}方法完成`
2455
+ });
2456
+ } catch (e) {
2457
+ logMsgFormat('getMsgFromH5', `${methodName}方法执行失败`, 'error', e);
2458
+ }
2459
+ },
2460
+
2461
+ /**
2462
+ * @description: 发送消息给H5
2463
+ */
2464
+ postMsgToH5(msgInfo) {
2465
+ const msgBody = JSON.stringify(msgInfo);
2466
+ logMsgFormat('postMsgToH5', `消息内容:${msgBody}`, 'log');
2467
+ // 执行浏览器的webview回传
2468
+ if (checkIsBrowserEnv()) {
2469
+ logMsgFormat('postMsgToH5', `父页面运行在浏览器`, 'log');
2470
+ const iframe = document.querySelector('iframe');
2471
+ iframe.contentWindow.postMessage(JSON.stringify(msgBody), '*');
2472
+ } else {
2473
+ try {
2474
+ logMsgFormat('postMsgToH5', `父页面运行在非浏览器`, 'log');
2475
+ this.wvInfo.evalJS(`getMessageFromWebview('${msgBody}')`);
2476
+ } catch (e) {
2477
+ logMsgFormat('postMsgToH5', `执行浏览器的webview回传异常`, 'error', e);
2478
+ }
2479
+ }
2480
+ },
2481
+
2482
+ /**
2483
+ * @description: 从H5发送的消息内容中,获取消息数据信息
2484
+ * @param e 消息内容
2485
+ * @returns 消息数据信息
2486
+ */
2487
+ getMsgDataFromH5(e) {
2488
+ let msgData = null;
2489
+ const {data} = e;
2490
+ try {
2491
+ if (checkIsBrowserEnv()) {
2492
+ msgData = data?.data?.arg ? data?.data?.arg : data?.data ? data.data : data;
2493
+ } else {
2494
+ msgData = e.detail?.data[0];
2495
+ }
2496
+ } catch (e) {
2497
+ logMsgFormat('getMsgDataFromH5', `处理消息内容时发生异常`, 'error', e);
2498
+ return false;
2499
+ }
2500
+ logMsgFormat('getMsgDataFromH5', `获取到的消息内容:${JSON.stringify(msgData)}`, 'log');
2501
+ return msgData;
2502
+ }
2503
+ };
2504
+
2505
+ /**
2506
+ * @description: 执行序列化处理
2507
+ */
2508
+ const _parseFunction = (obj, name, callback) => {
2509
+ logMsgFormat('_parseFunction', `${JSON.stringify(obj)}`);
2510
+ if (typeof obj === 'function') {
2511
+ callback[name] = obj;
2512
+ obj = '[Function]::' + name;
2513
+ return;
2514
+ }
2515
+ if (typeof obj !== 'object') {
2516
+ return;
2517
+ }
2518
+ let ret = null;
2519
+ for (let p in obj) {
2520
+ switch (typeof obj[p]) {
2521
+ case 'object':
2522
+ ret = name ? name + '_' + p : p;
2523
+ _parseFunction(obj[p], ret, callback);
2524
+ break;
2525
+ case 'function':
2526
+ ret = name ? name + '_' + p : p;
2527
+ callback[ret] = obj[p];
2528
+ obj[p] = '[Function]::' + ret;
2529
+ break;
2530
+ }
2531
+ }
2532
+ };
2533
+
2534
+ /**
2535
+ * @description: 获取数据类型
2536
+ * @param {*}
2537
+ * @return {*}
2538
+ */
2539
+ const _getType = (args) => {
2540
+ let type = 0;
2541
+ if (typeof args === 'string') {
2542
+ type = 1;
2543
+ } else if (typeof args === 'number') {
2544
+ type = 2;
2545
+ } else if (typeof args === 'boolean') {
2546
+ type = 3;
2547
+ } else if (typeof args === 'function') {
2548
+ type = 4;
2549
+ } else if (args instanceof Array) {
2550
+ type = 6;
2551
+ } else if (typeof args === 'object') {
2552
+ type = 5;
2553
+ }
2554
+ return type;
2555
+ };
2556
+
2557
+ const appWebviewMsg = {
2558
+
2559
+ /**
2560
+ * @description: APP嵌套的H5调用原生能力
2561
+ * @param resolve 消息回执事件
2562
+ * @param evConfig 事件配置信息
2563
+ * @param dataInfo 请求入参
2564
+ */
2565
+ appH5SendMsgToApp(resolve, evConfig = {}, dataInfo = {}) {
2566
+ const {isWindowEv, moduleName, nativeEvName, isCustomEv} = evConfig;
2567
+
2568
+ // 部分方法是挂载在Windows上的调用模式,所以需要特殊处理
2569
+ if (isWindowEv) {
2570
+ this.h5SendMsgToAppByWindow(resolve, evConfig, dataInfo);
2571
+ return;
2572
+ }
2573
+
2574
+ const mName = isCustomEv ? 'custom' : moduleName;
2575
+ const evName = isCustomEv ? 'call' : nativeEvName;
2576
+ this.executeSendMsgToApp({
2577
+ resolveInfo: resolve,
2578
+ moduleName: mName,
2579
+ eventName: evName,
2580
+ actionName: nativeEvName,
2581
+ dataInfo,
2582
+ isCustomEv,
2583
+ evConfig
2584
+ });
2585
+ },
2586
+
2587
+
2588
+ /**
2589
+ * @description: 执行发送消息给APP
2590
+ * @param reqParams 请求参数
2591
+ */
2592
+ executeSendMsgToApp(reqParams = {}) {
2593
+
2594
+ const {moduleName, eventName, actionName, dataInfo, resolveInfo, isCustomEv, evConfig} = reqParams || {};
2595
+
2596
+ const {description} = evConfig;
2597
+
2598
+ /**
2599
+ * @description: 格式化请求入参
2600
+ */
2601
+ const _this = this;
2602
+ const formatReqParams = function () {
2603
+ return _this.formatBridgeData(window.c2[moduleName][`${eventName}Callback`], arguments)
2604
+ };
2605
+
2606
+ try {
2607
+ let data = {};
2608
+ const keys = typeof dataInfo === 'object' ? Object.keys(dataInfo) : [];
2609
+ if (keys.length > 0) {
2610
+ data = deepClone(dataInfo);
2611
+ }
2612
+ // 是否为Custom.call事件
2613
+ if (isCustomEv) {
2614
+ const reqData = deepClone(data);
2615
+ logMsgFormat('webviewSendMsgToApp', `${description}功能在是通过custom.call的方式调用,需要重新处理入参`);
2616
+ data['params'] = reqData;
2617
+ data['action'] = actionName;
2618
+ }
2619
+ logMsgFormat('webviewSendMsgToApp', `${description}的完整参数:${JSON.stringify(data)}`);
2620
+ this.initEventCallbackEv(resolveInfo, data, evConfig);
2621
+ // 格式化调用参数
2622
+ const args = formatReqParams(data);
2623
+ logMsgFormat('webviewSendMsgToApp', `${description}功能在${getPlatformInfo()}的Webview环境下执行,调用参数:${JSON.stringify(args)}`);
2624
+ // 执行事件调用发送
2625
+ this.h5SendMsgToAppByBrowser(resolveInfo, evConfig, args);
2626
+ } catch (e) {
2627
+ console.log(`🚀发送消息给APP出现错误,错误信息:${e},${JSON.stringify(e)}`);
2628
+ logMsgFormat('webviewSendMsgToApp', `${description}执行数据处理失败`, 'error', e);
2629
+ }
2630
+ },
2631
+
2632
+ /**
2633
+ * @description: 初始化事件回调机制
2634
+ * @param resolve
2635
+ * @param data
2636
+ * @param evConfig
2637
+ * @return
2638
+ */
2639
+ initEventCallbackEv(resolve, data, evConfig = {}) {
2640
+ const {description, resDataFormat, resErrorFormat} = evConfig;
2641
+ // 成功的回调,无需业务侧传递,由组件侧默认进行塞入,通过resolve执行回抛
2642
+ data['onSuccess'] = function (res) {
2643
+ logMsgFormat('webviewSendMsgToApp', `${description}功能在App的Webview环境下执行完成`);
2644
+ // 如果有返回数据需要格式化,则进行格式化处理
2645
+ if (resDataFormat) {
2646
+ resolve(resDataFormat(res));
2647
+ } else {
2648
+ resolve(res);
2649
+ }
2650
+ };
2651
+ data['onFail'] = function (res) {
2652
+ const dataInfo = deepClone(res);
2653
+ logMsgFormat('webviewSendMsgToApp', `${description}功能在App的Webview环境下执行失败,收到的回调数据:::${JSON.stringify(dataInfo)}`);
2654
+ // 执行失败,通过resolve抛出失败信息
2655
+ if (resErrorFormat) {
2656
+ resolve(resErrorFormat(dataInfo));
2657
+ return;
2658
+ }
2659
+ if (resDataFormat) {
2660
+ resolve(resDataFormat(dataInfo));
2661
+ return;
2662
+ }
2663
+ resolve(dataInfo);
2664
+ };
2665
+ },
2666
+
2667
+ /**
2668
+ * @description: 格式化
2669
+ * @param callback
2670
+ * @param dataInfo
2671
+ * @return
2672
+ */
2673
+ formatBridgeData(callback, dataInfo) {
2674
+ try {
2675
+ const id = Math.random().toString(32).slice(2);
2676
+ const params = [];
2677
+ for (let i in dataInfo) {
2678
+ const name = id + '_a' + i;
2679
+ const item = dataInfo[i];
2680
+ const l = {};
2681
+ if (/OpenHarmony ([5-9])|OpenHarmony (\d{2})/i.test(navigator.userAgent) === false) {
2682
+ _parseFunction(item, name, l);
2683
+ }
2684
+ for (let k in l) {
2685
+ callback[k] = l[k];
2686
+ this.C2ReceiveQueue.push(callback);
2687
+ }
2688
+ params.push({
2689
+ type: _getType(item),
2690
+ name: name,
2691
+ value: item
2692
+ });
2693
+ }
2694
+ logMsgFormat(`formatBridgeData`, `格式化后的参数:${JSON.stringify(params)}`);
2695
+ return {
2696
+ params: params,
2697
+ id: id
2698
+ };
2699
+ } catch (e) {
2700
+ logMsgFormat('formatBridgeData', `消息通讯数据格式化异常`, 'error', e);
2701
+ }
2702
+ },
2703
+
2704
+ /**
2705
+ * @description: H5通过Window属性给APP发送事件
2706
+ */
2707
+ h5SendMsgToAppByWindow(resolve, evConfig = {}, dataInfo = {}) {
2708
+ const {nativeEvName, description, resDataFormat} = evConfig;
2709
+ const deviceType = getPlatformInfo();
2710
+ const callbackName = `${nativeEvName}Back`;
2711
+ let reqData = dataInfo;
2712
+ logMsgFormat('h5SendMsgToAppByWindow', `给【${deviceType}】APP发送【${description}】-【${nativeEvName}】事件调用,回调函数名称:【${callbackName}】`, 'log');
2713
+
2714
+ window[callbackName] = (res) => {
2715
+ let resultData = res;
2716
+ logMsgFormat('h5SendMsgToAppByWindow', `收到【${deviceType}】APP发送的${description}事件调用的回调值:${JSON.stringify(resultData)},回调数据类型::${typeof resultData}`, 'log');
2717
+
2718
+ // 执行数据格式化处理
2719
+ resultData = parseResData(resultData);
2720
+
2721
+ if (resDataFormat) {
2722
+ resolve(resDataFormat(resultData));
2723
+ return;
2724
+ }
2725
+ resolve(resultData);
2726
+ };
2727
+
2728
+ setTimeout(() => {
2729
+ if (deviceType.toLowerCase() === 'ios') {
2730
+ window.webkit.messageHandlers[nativeEvName].postMessage(reqData);
2731
+ return;
2732
+ }
2733
+ if (deviceType.toLowerCase() === 'android') {
2734
+ window.android[nativeEvName](reqData);
2735
+ return
2736
+ }
2737
+ window.harmony[nativeEvName](reqData);
2738
+ }, 100);
2739
+ },
2740
+
2741
+ /**
2742
+ * @description: H5通过浏览器的promt给APP发消息
2743
+ */
2744
+ h5SendMsgToAppByBrowser(resolve, evConfig = {}, dataInfo = {}) {
2745
+
2746
+ const deviceType = getPlatformInfo();
2747
+ logMsgFormat('h5SendMsgToAppByBrowser', `给【${deviceType}】APP发送【${evConfig.nativeEvName}】事件调用,入参:${JSON.stringify(dataInfo)}`, 'log');
2748
+
2749
+ const {nativeEvName, moduleName, isCustomEv} = evConfig;
2750
+ const {id, params} = dataInfo;
2751
+ if (deviceType === 'android') {
2752
+ this.h5SendMsgToAndroid(id, moduleName, nativeEvName, params, isCustomEv);
2753
+ return;
2754
+ }
2755
+ if (deviceType === 'ios') {
2756
+ this.iosCallBackList.push({
2757
+ id,
2758
+ resolveInfo: resolve,
2759
+ configInfo: evConfig
2760
+ });
2761
+ this.h5SendMsgToIOS(id, moduleName, nativeEvName, params, isCustomEv);
2762
+ return;
2763
+ }
2764
+ if (deviceType === 'harmony') {
2765
+ this.h5SendMsgToHarmony(id, moduleName, nativeEvName, params, isCustomEv);
2766
+ }
2767
+ },
2768
+
2769
+ /**
2770
+ * @description: H5发送消息给安卓APP
2771
+ * @param id
2772
+ * @param module
2773
+ * @param method
2774
+ * @param args
2775
+ * @param isCustom
2776
+ * @return
2777
+ */
2778
+ h5SendMsgToAndroid(id, module, method, args, isCustom) {
2779
+ const req = {
2780
+ id: id,
2781
+ module: isCustom ? 'custom' : module,
2782
+ method: isCustom ? 'call' : method,
2783
+ parameters: args
2784
+ };
2785
+ logMsgFormat('h5SendMsgToAndroid', `发送给安卓APP的消息:${JSON.stringify(req)}`);
2786
+ return JSON.parse(window.AndroidFunction.callAndroidFun(JSON.stringify(req)));
2787
+ },
2788
+
2789
+ /**
2790
+ * @description: H5发送消息给IOS APP
2791
+ * @param id
2792
+ * @param module
2793
+ * @param method
2794
+ * @param args
2795
+ * @param isCustom
2796
+ */
2797
+ h5SendMsgToIOS(id, module, method, args, isCustom) {
2798
+ const req = {
2799
+ id: id,
2800
+ module: isCustom ? 'custom' : module,
2801
+ method: isCustom ? 'call' : method,
2802
+ parameters: args
2803
+ };
2804
+ logMsgFormat('h5SendMsgToIOS', `发送给IOS APP的消息:${JSON.stringify(req)}`);
2805
+ return JSON.parse(prompt(JSON.stringify(req)));
2806
+ },
2807
+
2808
+ /**
2809
+ * @description: H5发送消息给Harmony APP
2810
+ * @param id
2811
+ * @param module
2812
+ * @param method
2813
+ * @param args
2814
+ * @param isCustom
2815
+ */
2816
+ h5SendMsgToHarmony(id, module, method, args, isCustom) {
2817
+ const req = {
2818
+ id: id,
2819
+ module: isCustom ? 'custom' : module,
2820
+ method: isCustom ? 'call' : method,
2821
+ parameters: args
2822
+ };
2823
+ logMsgFormat('h5SendMsgToHarmony', `发送给鸿蒙APP的消息:${JSON.stringify(req)}`);
2824
+ return JSON.parse(window.harmonyFunction.callHarmonyFun(req));
2825
+ }
2826
+ };
2827
+
2828
+ const miniAppWebviewMsg = {
2829
+ // 消息列表
2830
+ msgList: [],
2831
+ // 消息堆栈
2832
+ msgStack: [],
2833
+
2834
+ /**
2835
+ * @description: 小程序H5发送消息调用原生能力
2836
+ * @param resolve Promise resolve
2837
+ * @param eventName 事件名称
2838
+ * @param dataInfo 参数信息
2839
+ * @return
2840
+ */
2841
+ async miniAppH5SendMsgToApp(resolve, eventName, dataInfo) {
2842
+ try {
2843
+ logMsgFormat('miniAppH5SendMsgToApp', `发送消息给webview:${eventName}`, 'log');
2844
+ const result = await this.sendMsgToMiniApp({
2845
+ methodName: eventName,
2846
+ methodData: dataInfo
2847
+ });
2848
+ resolve(result?.resultInfo);
2849
+ } catch (e) {
2850
+ logMsgFormat('miniAppH5SendMsgToApp', `执行${eventName}失败`, 'error', e);
2851
+ resolve({
2852
+ isSuccess: false, message: "执行事件失败,详情查看控制台"
2853
+ });
2854
+ }
2855
+ },
2856
+
2857
+ /**
2858
+ * @description: 发送消息给小程序
2859
+ * @param msgInfo 消息内容
2860
+ * @return
2861
+ */
2862
+ sendMsgToMiniApp(msgInfo) {
2863
+ return new Promise((resolve, reject) => {
2864
+ logMsgFormat('postMsgToWebview', `消息内容:${JSON.stringify(msgInfo)}`, 'log');
2865
+ const {methodName, methodData} = msgInfo || {};
2866
+ if (!methodName) {
2867
+ logMsgFormat('postMsgToWebview', `请传入要调用的事件名称`, 'warn');
2868
+ return
2869
+ }
2870
+ if (!methodData) {
2871
+ logMsgFormat('postMsgToWebview', `请传入要调用事件的数据信息`, 'warn');
2872
+ return;
2873
+ }
2874
+ const msgId = getUUID();
2875
+ const msgContent = {
2876
+ data: {
2877
+ ...{
2878
+ msgId,
2879
+ isH5Send: true
2880
+ },
2881
+ ...msgInfo,
2882
+ }
2883
+ };
2884
+ this.msgList.push({
2885
+ id: msgId,
2886
+ resolveInfo: resolve,
2887
+ rejectInfo: reject
2888
+ });
2889
+ logMsgFormat('postMsgToWebview', `发送消息给父容器页面:${JSON.stringify(msgContent)}`, 'log');
2890
+ if (!this.uniSDKInit) {
2891
+ logMsgFormat('postMsgToWebview', `SDK尚未初始化完成,先行执行堆栈`, 'log');
2892
+ this.msgStack.push({
2893
+ id: getUUID(),
2894
+ msgContent,
2895
+ resolve,
2896
+ reject
2897
+ });
2898
+ return;
2899
+ }
2900
+ uni?.webView?.postMessage ? uni.webView.postMessage(msgContent) : uni?.postMessage(msgContent);
2901
+ }).catch(err => {
2902
+ logMsgFormat('postMsgToWebview', `发生异常`, 'error', err);
2903
+ });
2904
+ }
2905
+ };
2906
+
2907
+ const getMsgFromParent = {
2908
+
2909
+ /**
2910
+ * @description: 从Webview接收消息
2911
+ * @param {*} e 消息内容体
2912
+ * @param {*} isApp
2913
+ */
2914
+ getMessageFromWebview(e, isApp = false) {
2915
+ let data = {};
2916
+ try {
2917
+ data = isApp ? e : e?.data || '{}';
2918
+ data = parseResData(data);
2919
+ } catch (e) {
2920
+ logMsgFormat('getMessageFromWebview', `解析数据异常`, 'error', e);
2921
+ }
2922
+ logMsgFormat('getMessageFromWebview', `是否为webview发送的消息内容:${data?.isWebviewSend},消息内容:${JSON.stringify(data)}`, 'log');
2923
+ if (!data?.isWebviewSend) {
2924
+ return;
2925
+ }
2926
+ const {msgId} = data;
2927
+ const msgIndex = this.msgList.findIndex(item => item.id === msgId);
2928
+ if (msgIndex === -1) {
2929
+ return;
2930
+ }
2931
+ const msgInfo = this.msgList[msgIndex];
2932
+ const {resolveInfo} = msgInfo;
2933
+ resolveInfo(data);
2934
+ this.msgList.splice(msgIndex, 1);
2935
+ },
2936
+ };
2937
+
2938
+ const blackList = ['getLoginUserInfo', 'getAuthToken'];
2939
+ class XybAgent {
2940
+ version = "";
2941
+ isInit = false;
2942
+ isWebviewPage = false;
2943
+ anaSDKInit = false;
2944
+ uniSDKInit = false;
2945
+ weChatInit = false;
2946
+ alipayInit = false;
2947
+ iosCallBackList = [];
2948
+ C2ReceiveQueue = [];
2949
+ autoUpdate = true;
2950
+ autoConfigMenuBtn = true;
2951
+ weChatConfigReady = false;
2952
+
2953
+ constructor(version, isWebviewPage) {
2954
+ this.version = version;
2955
+ this.isInit = false;
2956
+ this.isWebviewPage = isWebviewPage;
2957
+ this.iosCallBackList = [];
2958
+ this.initModuleMethod();
2959
+ this.initSDKAPI();
2960
+ this.initDefaultConfig();
2961
+ }
2962
+
2963
+ /**
2964
+ * @description: 初始化合并模块方法到xybAgent
2965
+ */
2966
+ initModuleMethod() {
2967
+ // 将子模块的方法挂载到主模块上
2968
+ objIntegration(custom, this);
2969
+ objIntegration(trackInfo, this);
2970
+ objIntegration(BridgeInfo, this);
2971
+ objIntegration(requestInfo, this);
2972
+ // objIntegration(paymentInfo, this);
2973
+ objIntegration(browserInfo, this);
2974
+ objIntegration(locationInfo, this);
2975
+ objIntegration(publicMethod, this);
2976
+ objIntegration(getMsgFromH5, this);
2977
+ objIntegration(imgChooseInfo, this);
2978
+ objIntegration(appWebviewMsg, this);
2979
+ objIntegration(authFaceInfo, this);
2980
+ objIntegration(navigationInfo, this);
2981
+ objIntegration(getMsgFromParent, this);
2982
+ objIntegration(miniAppWebviewMsg, this);
2983
+ }
2984
+
2985
+ /**
2986
+ * @description: 执行配置初始化
2987
+ */
2988
+ init(config) {
2989
+ return new Promise(async (resolve, reject) => {
2990
+ logMsgFormat(`init`, `SDK初始化任务执行处理`);
2991
+ if (!checkIsBrowserEnv()) {
2992
+ logMsgFormat('init', '当前环境非浏览器环境,无需执行初始化动作', 'warn');
2993
+ reject('当前环境非浏览器环境,无需执行初始化动作');
2994
+ return;
2995
+ }
2996
+ if (checkIsWebviewEnv()) {
2997
+ this.initWebviewMsgFormat();
2998
+ }
2999
+ this.initSDKScriptFile();
3000
+ await this.trackSDKInit(config);
3001
+ resolve(this.isInit);
3002
+ })
3003
+ }
3004
+
3005
+ /**
3006
+ * @description: 挂载第三方SDK文件
3007
+ */
3008
+ initSDKScriptFile() {
3009
+ logMsgFormat(`initSDKScriptFile`, `挂载第三方SDK脚本文件`);
3010
+ this.initUNISDK();
3011
+ if (checkIsWeChatEnv()) {
3012
+ this.initWeChatSDK();
3013
+ return;
3014
+ }
3015
+ this.initAliPaySDK();
3016
+ }
3017
+
3018
+ /**
3019
+ * @description: 初始化WEBVIEW页面消息内容格式化处理
3020
+ */
3021
+ initWebviewMsgFormat() {
3022
+ logMsgFormat('initWebviewMsgFormat', `初始化被嵌套的页面消息通讯`, 'log');
3023
+ if (checkIsBrowserEnv()) {
3024
+ window.addEventListener('message', e => {
3025
+ logMsgFormat('initWebviewMsgFormat', `浏览器消息处理`, 'log');
3026
+ this.getMessageFromWebview(e);
3027
+ });
3028
+ window.getMessageFromWebview = (e) => {
3029
+ logMsgFormat('initWebviewMsgFormat', `事件注入消息处理`, 'log');
3030
+ this.getMessageFromWebview(e, true);
3031
+ };
3032
+ } else {
3033
+ logMsgFormat('initWebviewMsgFormat', `该API仅支持在被webview嵌套的H5页面中使用`, 'error', '');
3034
+ }
3035
+ }
3036
+
3037
+ /**
3038
+ * @description: 初始化挂载UNI-WEBVIEW 的SDK
3039
+ */
3040
+ initUNISDK() {
3041
+ if (!checkIsBrowserEnv()) {
3042
+ return;
3043
+ }
3044
+ if (checkUNIReady()) {
3045
+ return;
3046
+ }
3047
+ mountScriptFile('https://mobile.zwfw.hunan.gov.cn:8088/uni.webview.1.5.6.js', "UNI").then(() => {
3048
+ if (checkUNIReady()) {
3049
+ this.uniSDKInit = true;
3050
+ logMsgFormat("initUNISDK", "UNI Webview SDK 挂载完成");
3051
+ }
3052
+ });
3053
+ }
3054
+
3055
+ /**
3056
+ * @description: 初始化微信SDK
3057
+ */
3058
+ initWeChatSDK() {
3059
+ logMsgFormat("initWeChatSDK", "初始化weChat SDK");
3060
+ if (!checkIsBrowserEnv()) {
3061
+ return;
3062
+ }
3063
+ if (checkWeChatReady()) {
3064
+ this.initWeChatConfig();
3065
+ logMsgFormat("initWeChatSDK", "WeChat SDK已挂载完成,无需二次挂载");
3066
+ return;
3067
+ }
3068
+ mountScriptFile("https://res.wx.qq.com/open/js/jweixin-1.6.0.js", "微信").then(res => {
3069
+ if (checkWeChatReady()) {
3070
+ this.weChatInit = true;
3071
+ this.initWeChatConfig();
3072
+ logMsgFormat("initWeChatSDK", "WeChat SDK挂载完成");
3073
+ }
3074
+ });
3075
+ }
3076
+
3077
+ /**
3078
+ * @description: 初始化微信的配置
3079
+ */
3080
+ initWeChatConfig() {
3081
+ if (this.weChatConfigReady) {
3082
+ return;
3083
+ }
3084
+ wx.request({
3085
+ url: `${baseURL}/api/auth/wechat/v1/getJsapiTicket`,
3086
+ method: "POST",
3087
+ data: {
3088
+ url: window.location.href.split('#')[0]
3089
+ },
3090
+ success: res => {
3091
+ const configInfo = res?.data?.data;
3092
+ this.weChatConfigReady = true;
3093
+ logMsgFormat(`getLocationInWeChat`, `获取签名信息完成`);
3094
+ window?.wx?.config({
3095
+ appId: "wx44bc5d5e34ac0c01",
3096
+ timestamp: configInfo?.timestamp,
3097
+ nonceStr: configInfo?.noncestr,
3098
+ signature: configInfo?.signature,
3099
+ jsApiList: [
3100
+ "getLocation",
3101
+ "openLocation",
3102
+ "chooseImage",
3103
+ "chooseFile",
3104
+ "scanQRCode",
3105
+ "previewImage",
3106
+ "downloadImage"
3107
+ ],
3108
+ });
3109
+ this.checkLocationEvStation();
3110
+ },
3111
+ fail: err => {
3112
+ logMsgFormat(`initWeChatConfig`, `获取签名信息失败,信息是:${JSON.stringify(err)}`);
3113
+ }
3114
+ });
3115
+ }
3116
+
3117
+ /**
3118
+ * @description: 挂载支付宝的SDK文件
3119
+ */
3120
+ initAliPaySDK() {
3121
+ logMsgFormat("initAliPaySDK", "初始化Alipay SDK");
3122
+
3123
+ if (!checkIsBrowserEnv()) {
3124
+ return;
3125
+ }
3126
+ if (checkAliPayReady()) {
3127
+ return;
3128
+ }
3129
+ if (!checkIsAlipayEnv()) {
3130
+ return;
3131
+ }
3132
+ mountScriptFile("https://appx/web-view.min.js", "支付宝").then(res => {
3133
+ if (checkAliPayReady()) {
3134
+ this.alipayInit = true;
3135
+ logMsgFormat(`initAliPaySDK`, `Alipay SDK挂载完成`);
3136
+ }
3137
+ });
3138
+ }
3139
+
3140
+ /**
3141
+ * @description: 初始化挂载事件清单
3142
+ */
3143
+ initSDKAPI() {
3144
+ if (checkIsAppWebviewEnv()) {
3145
+ logMsgFormat('initSDKAPI', 'App的Webview环境,初始化C2调用链的回调函数');
3146
+ this.initMobileBridgeGlobalConfig();
3147
+ }
3148
+ logMsgFormat('initSDKAPI', '开始初始化SDK API');
3149
+ eventList.forEach(item => {
3150
+ const {eventName, moduleName, nativeEvName, isCustomEv} = item;
3151
+ if (((moduleName && nativeEvName) || isCustomEv) && checkIsAppWebviewEnv()) {
3152
+ logMsgFormat('initSDKAPI', `初始化C2调用链的回调函数:${eventName}`);
3153
+ this.checkMobileModuleBack(moduleName, nativeEvName, isCustomEv);
3154
+ }
3155
+ if (blackList?.includes(eventName)) {
3156
+ return;
3157
+ }
3158
+ try {
3159
+ this[eventName] = (config) => {
3160
+ return new Promise(resolve => {
3161
+ this.normalEvDataTransition(resolve, config, item);
3162
+ });
3163
+ };
3164
+ } catch (e) {
3165
+ logMsgFormat("initSDKAPI", "执行API初始化挂载异常", "error", e);
3166
+ }
3167
+ });
3168
+ }
3169
+
3170
+ /**
3171
+ * @description: 常规事件集中处理
3172
+ * @param resolve Promise resolve
3173
+ * @param evData 参数信息
3174
+ * @param evConfig 事件配置信息
3175
+ * @return
3176
+ */
3177
+ normalEvDataTransition(resolve, evData = {}, evConfig = {}) {
3178
+ const {eventName, description, reqDataFormat} = evConfig || {};
3179
+ const deviceType = getPlatformInfo();
3180
+ let dataInfo = evData;
3181
+ if (reqDataFormat) {
3182
+ dataInfo = reqDataFormat(evData);
3183
+ }
3184
+
3185
+ if (!dataInfo) {
3186
+ logMsgFormat(eventName, `给【${deviceType}】APP发送【${description}】-【${eventName}】事件失败,请检查数据格式是否正确`, 'error');
3187
+ return;
3188
+ }
3189
+
3190
+ if (checkIsAppWebviewEnv()) {
3191
+ logMsgFormat("normalEvDataTransition", `开始调用APP的嵌套H5能力,事件名称:${eventName},入参:${JSON.stringify(dataInfo)}`);
3192
+ this.appH5SendMsgToApp(resolve, evConfig, dataInfo);
3193
+ return;
3194
+ }
3195
+
3196
+ if (checkIsMiniAppBrowserEnv()) {
3197
+ logMsgFormat("normalEvDataTransition", `开始调用小程序/H5嵌套的H5能力,事件名称:${eventName},入参:${JSON.stringify(dataInfo)}`);
3198
+ this.miniAppH5SendMsgToApp(resolve, eventName, dataInfo, description);
3199
+ return;
3200
+ }
3201
+
3202
+ if (checkIsWeChatEnv() || checkIsAlipayEnv()) {
3203
+ logMsgFormat(`normalEvDataTransition`, `微信/支付宝小程序事件调用,事件名称:${eventName}, 入参:${JSON.stringify(dataInfo)}`);
3204
+ this.executeBrowserEvent(resolve, dataInfo, evData, evConfig);
3205
+ return;
3206
+ }
3207
+ this.executeEvByNative(resolve, dataInfo, evConfig);
3208
+ }
3209
+
3210
+ /**
3211
+ * @description: 通过Native调用原生能力
3212
+ * @param resolve Promise resolve
3213
+ * @param dataInfo 参数信息
3214
+ * @param evConfig 事件配置信息
3215
+ */
3216
+ executeEvByNative(resolve, dataInfo, evConfig) {
3217
+ const {description, uniEvName, eventName, nativeResFormat} = evConfig;
3218
+ try {
3219
+ logMsgFormat('executeEvByNative', `开始调用原生${description}的能力,API名称:${uniEvName},格式化前的参数信息:${JSON.stringify(dataInfo)}`);
3220
+ uni.sendNativeEvent(uniEvName, dataInfo, res => {
3221
+ logMsgFormat('executeEvByNative', `调用原生${description}的能力完成,结果:${JSON.stringify(res)}`, 'log');
3222
+ let result = res;
3223
+ if (nativeResFormat) {
3224
+ result = nativeResFormat(result);
3225
+ logMsgFormat('executeEvByNative', `调用原生${description}的能力完成,格式化后的结果:${JSON.stringify(result)}`, 'log');
3226
+ }
3227
+ if (eventName === 'fileDownload' && res['isSuccess']) {
3228
+ formatResponseData(resolve, result);
3229
+ }
3230
+ // 鸿蒙设备需要将坐标系进行转换
3231
+ if (eventName === 'getLocationInfo') {
3232
+ uni.sendNativeEvent('System_getAppInfo', {}, resultData => {
3233
+ // 鸿蒙设备返回的是WGS84,需要转换为GCJ02
3234
+ if (resultData.platform.toLowerCase().includes('harmony')) {
3235
+ const addInfo = wgsToGCJ02(res?.location?.longitude, res?.location?.latitude);
3236
+ result['location']['longitude'] = addInfo?.lng;
3237
+ result['location']['latitude'] = addInfo?.lat;
3238
+ }
3239
+ formatResponseData(resolve, result);
3240
+ });
3241
+ return;
3242
+ }
3243
+ if (eventName !== 'fileDownload') {
3244
+ formatResponseData(resolve, result);
3245
+ }
3246
+ });
3247
+ } catch (e) {
3248
+ resolve({
3249
+ isSuccess: false,
3250
+ message: `${description}API执行失败,具体错误信息请查看控制台`
3251
+ });
3252
+ logMsgFormat('executeEvByNative', `${description}API执行异常`, 'error', e);
3253
+ }
3254
+ }
3255
+
3256
+ /**
3257
+ * @description: 初始化基础配置
3258
+ */
3259
+ initDefaultConfig() {
3260
+ logMsgFormat(`initDefaultConfig`, `默认胶囊按钮配置执行初始化处理`);
3261
+ if (!this.autoUpdate) {
3262
+ logMsgFormat(`initDefaultConfig`, `业务侧配置无需自动重置胶囊按钮,不至于页面切换事件监听`);
3263
+ return;
3264
+ }
3265
+ this.resetMenuBtnConfig();
3266
+ }
3267
+ }
3268
+
3269
+ let xybAgent$1 = new XybAgent(VERSION, checkIsWebviewEnv());
3270
+
3271
+ export { xybAgent$1 as default };