123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890 |
- /*
- * 描述:shr命名空间构造器
- * @class 用来构建js 对象的命名空间
- * @constructor
- * @return 返回构造完成的命名空间(JS对象)
- */
- var Namespace = {
- /*
- * 描述:注册命名空间
- * @param {String} fullNS 命名空间名称
- * @return 返回造建完成的命名空间
- */
- register : function(fullNS) {
- var nsArray = fullNS.split('.');
- var sEval = "";
- var sNS = "";
- for (var i = 0; i < nsArray.length; i++) {
- if (i != 0)
- sNS += ".";
- sNS += nsArray[i];
- sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS
- + " = new Object();"
- }
- if (sEval != "")
- return eval(sEval);
- }
- };
- /**
- * 重写jquery init方法来过滤下selector中的特殊字符
- * 不能处理"#test1,#test2"多个选择器的情况
- */
- var selector_special_char_regex = /[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g;
- var waf = $;
- var shr = $;
- var _top = getTop();
- var _ajaxFnCache = $.ajax;
- $.ajax = function (url, options){
- // toodo 参考 jquery.js ajax实现
- if ( typeof url === "object" ) {
- options = url;
- url = undefined;
- }
- options = options || {};
- //shr.dealPostParam会修改options,防止影响外部参数引用
- var newOptions = $.extend(true,{},options);
- shr.dealPostParam( newOptions );
- return _ajaxFnCache(url, newOptions);
- };
- function detectBrowser () {
- // Useragent RegExp
- var rwebkit = /(webkit)[ \/]([\w.]+)/;
- var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/;
- var rmsie = /(msie) ([\w.]+)/;
- var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;
- var browser = {};
- // Use of jQuery.browser is frowned upon.
- // More details: http://docs.jquery.com/Utilities/jQuery.browser
- var uaMatch = function( ua ) {
- ua = ua.toLowerCase();
- var match = rwebkit.exec( ua ) ||
- ropera.exec( ua ) ||
- rmsie.exec( ua ) ||
- ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
- [];
- return { browser: match[1] || "", version: match[2] || "0" };
- }
- var browserMatch = uaMatch( window.navigator.userAgent );
- if ( browserMatch.browser ) {
- browser[ browserMatch.browser ] = true;
- browser.version = browserMatch.version;
- }
- // Deprecated, use jQuery.browser.webkit instead
- if ( browser.webkit ) {
- browser.safari = true;
- }
- return browser;
- }
- shr.extend({
- /**
- * 解决jQuery高版本下不支持浏览器检测问题
- */
- browser: jQuery.browser || detectBrowser(),
- initPrivacyAgreement: function(options){
- var $mask = $('<div id="shr-mask-agreement"><div>').appendTo($('body'));
- $mask.css({
- "display" : "block",
- "color" : "#fff",
- "position" : "fixed",
- "top" : "0px",
- "left" : "0px",
- "background-color" : 'black',
- "opacity" : 0.4,
- "-moz-opacity" : 0.4,
- "filter" : "alpha(opacity=" + (0.4 * 100) + ")",
- "width" : "100%",
- "height" : "100%",
- "z-index": "1024"
- });
- $('html').css({'overflow':'hidden'});
- var tpl = [
- '<div class="privacyPolicy">',
- '<div class="title" title="${name}">${name}</div>',
- '<div class="content">$${content}</div>',
- '<div class="privacyPolicyFoot">',
- '<button id="privacyAgree" type="button" class="shrbtn">' + $.shrI18n.privacy.msg2 +'</button>',
- '<button id="privacyReject" type="button" class="shrbtn">' + $.shrI18n.privacy.msg14 +'</button>',
- '</div>',
- '</div>'
- ].join('');
- var privacyHtml = juicer(tpl,options.data);
- $("body").append(privacyHtml);
- $('#privacyAgree').click(function(){
- if (typeof options.agree !== "function") return;
- options.agree();
- });
- $('#privacyReject').click(function(){
- if (typeof options.reject !== "function") return;
- options.reject();
- });
- },
- hidePrivacyAgreement: function(){
- var iframes = top.document.getElementsByTagName('iframe');
- if(iframes.length > 0) {
- for(var i = 0;i < iframes.length;i++) {
- mask = iframes[i].contentWindow.document.getElementById('shr-mask-agreement');
- $(mask).remove();
- }
- }
- $("div#shr-mask-agreement").remove();
- $("div#shr-mask-agreement", top.parent.document).remove();
- $('html').css({'overflow':'visible'});
- $('.privacyPolicy').remove();
- },
- startMask: function(opacity, load){
- opacity = (opacity || 0.16);
- if(load) {
- var $mask = $('<div id="shr-mask"><img src="/shr/styles/images/loading.gif" style="position:absolute;left:50%;top:50%;margin-left:-40px;margin-top:-40px;"><div>').appendTo($('body'));
- $mask.css({
- "display" : "block",
- "color" : "#fff",
- "position" : "fixed",
- "top" : "0px",
- "left" : "0px",
- "background-color" : 'gray',
- "opacity" : opacity,
- "-moz-opacity" : opacity,
- "filter" : "alpha(opacity=" + (opacity * 100) + ")",
- "width" : "100%",
- "height" : "100%",
- "z-index": "9999"
- });
- return;
- }
- var $mask = $('<div id="shr-mask"><div>').appendTo($('body'));
- $mask.css({
- "display" : "block",
- "color" : "#fff",
- "position" : "fixed",
- "top" : "0px",
- "left" : "0px",
- "background-color" : 'black',
- "opacity" : opacity,
- "-moz-opacity" : opacity,
- "filter" : "alpha(opacity=" + (opacity * 100) + ")",
- "width" : "100%",
- "height" : "100%",
- "z-index": "1024"
- });
- },
- //重写eval方法
- codeEval: function ( code ){
- var script;
- if ( code ) {
- var data_key = '_process_json_data_'+parseInt(shr.randMath());
- code = 'window["'+data_key+'"]=('+code+');'
- script = document.createElement("script");
- script.text = code;
- document.head.appendChild( script ).parentNode.removeChild( script );
- return window[data_key];
- }
- return null;
- },
- //附件上传中需要用到的fileUUID
- getAttachmentFileUUID: function(){
- if( $(".attachmentUploadArea").length > 0
- && $(".attachmentUploadArea").hasClass('standardAttachment')){
- var mainPageDom = $(".attachmentUploadArea").closest(".view_mainPage");
- var uuid = '';
- //多行表单的时候需要取view_mainPage上的uuid去拿viewPage
- if(mainPageDom.length && mainPageDom.attr('id')){
- uuid = mainPageDom.attr('id');
- }
- var currentPage = shr.getCurrentViewPage(uuid);
- var attachmentFileUUID = currentPage ? currentPage.attachmentFileUUID: '';
- return attachmentFileUUID;
- }
- },
- //生成附件fileUUID
- generateAttachmentFileUUID : function(){
- var attachmentFileUUID = '';
- if ($(".attachmentUploadArea").length > 0) {
- attachmentFileUUID = shr.generateUUID();
- }
- return attachmentFileUUID;
- },
- //在接口中设置附件上传中需要用到的UUID
- _addAttachmentFileUUID : function(data){
- if(data){
- var attachmentFileUUID = shr.getAttachmentFileUUID();
- if( $(".attachmentUploadArea").length > 0
- && $(".attachmentUploadArea").hasClass('standardAttachment')
- && attachmentFileUUID ){
- data.fileUUID = attachmentFileUUID;
- }
- }
- },
-
- //生成UUID
- generateUUID: function() {
- var uuid = '';
- var d = new Date().getTime();
- if (window.performance && typeof window.performance.now === "function") {
- d += performance.now();
- }
- uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
- var r = (d + Math.random() * 16) % 16 | 0;
- d = Math.floor(d / 16);
- return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
- });
-
- return uuid;
- },
- //随机数
- randMath: function(number){
- number = number? number : 100000;
- var seed = (new Date()).getTime();
- function r(){
- seed = (seed*9301+49297)%233280;
- return seed/(233280.0);
- }
- return Math.ceil(r()*number);
- },
- stopMask: function(){
- //对于界面存在多个iframe时,关闭提示不能移除所有遮罩
- var iframes = top.document.getElementsByTagName('iframe');
- if(iframes.length > 0) {
- for(var i = 0;i < iframes.length;i++) {
- mask = iframes[i].contentWindow.document.getElementById('shr-mask');
- $(mask).remove();
- }
- }
- $("div#shr-mask").remove();
- },
- // 增加一个关闭Mask的方法,用来提示浏览器缩放时的关闭。
- stopAllMask: function(){
- //对于界面存在多个iframe时,关闭提示不能移除所有遮罩
- var iframes = top.document.getElementsByTagName('iframe');
- if(iframes.length > 0) {
- for(var i = 0;i < iframes.length;i++) {
- mask = iframes[i].contentWindow.document.getElementById('shr-mask');
- $(mask).remove();
- }
- }
-
- $("div#shr-mask").remove();
- $("div#shr-mask", top.parent.document).remove();
- },
- /**
- * 获取当前的语言类型
- * 判断语言类型规则:当字符串中存在中午字符、英文字符和数字时,规则是中文字符安>英文字符>数字
- * @param {value}
- */
- getValueLanguageType: function(value) {
- if(escape(value).indexOf('%u') > -1) {
- return 'zh_CN';
- }else if(/[a-z]/i.test(value)) {
- return 'en_US';
- }else{
- return 'number';
- }
- },
- getCommonForUrl: function (someWindow, re) {
- if (!someWindow) {
- someWindow = _top;
- }
- var ret = re.exec(someWindow.location.href);
- return (ret && ret.length > 1) ? ret[1] : '';
- },
- /**
- * 过滤掉jquery选择器中的特殊字符串
- */
- filterSelectorSpecialChar: function (selector) {
- var _selector = selector;
- if (typeof selector == "string") {
- _selector = selector.replace(selector_special_char_regex, "\\$&");
- }
- return _selector;
- },
- /**
- * 描述:获取当前语种标识
- * zh_CN |中文
- *en_US |英文
- *zh_TW |繁体
- */
- getContext: function () {
- if (!shr.context) {
- shr.context = { locale: window.contextLanguage };
- }
- return shr.context;
- },
- //处理安全漏洞扫描出来的json注入
- explainJson: function( data ) {
- var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
- var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
- var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
- var rvalidchars = /^[\],:{}\s]*$/;
- if ( typeof data !== "string" || !data ) {
- return null;
- }
-
- // Make sure leading/trailing whitespace is removed (IE can't handle it)
- data = jQuery.trim( data );
- // Make sure the incoming data is actual JSON
- // Logic borrowed from http://json.org/json2.js
- if ( rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, "")) ) {
- // Try to use the native JSON parser first
- return window.JSON && window.JSON.parse ?window.JSON.parse( data ) : (new Function("return " + data))();
- } else {
- jQuery.error( "Invalid JSON: " + data );
- }
- },
- /**
- * 根据语言环境获取多语言字段对应语言值
- * 作用:当前的en_US,zh_CN,zh_TW环境与l1,l2,13的映射
- * @param lan en_US、zh_CN、zh_TW 可以通过shr.getContext().locale或者window.contextLanguage获取
- * @return l1、l2、13
- * */
- getFieldLangByContext: function (lan) {
- var locale = 'zh_CN';
- if(lan){
- locale = lan;
- }else if(shr.getContext().locale){
- locale = shr.getContext().locale;
- }
- var each = null;
- for (var i = 0, total = window.languageMappingList.length;i<total;i++){
- each = window.languageMappingList[i];
- if(each['locale'] == locale){
- return each['lang'];
- }
- }
- return 'l2';
- },
- /**
- * 校验是否有xss注入
- */
- verifyXss: function(targetVal,noVerify){
- if(noVerify) return;
- //过滤script|link|style|iframe标签
- var reg1 = /<(script|link|style|iframe)(.|\n)*\/\1>\s*/ig;
- //过滤on开头的标签属性
- var reg2 = /\s*(ontoggle|ondragend|onunload|onsubmit|onscroll|onclick|onchange|onblur|onbefore|onafter|onactivate|onselect|onload|onkey|onfocus|onhelp|ondrop|onfinish|onerror|eval|expression|onclick|ondbclick|onmousedown|onmouseup|prompt)\s*=/ig;
- //过滤src和href的伪协议
- var reg3 = /\s*(href|src)\s*=/ig;
- //过滤alert的伪协议
- var reg4 = /\s*(alert|confirm(?!\s*ed))\s*/ig;
- if(reg1.test(targetVal) || reg2.test(targetVal) || reg3.test(targetVal) || reg4.test(targetVal)){
- return true;
- }else{
- return false;
- }
- },
- /**
- * xss过滤
- */
- xssFilter: function(targetVal){
- //XSS过滤
- if((typeof targetVal) != 'string'){
- return targetVal;
- }
- if(shr.verifyXss(targetVal)){
- // 1.前端简单转义,主要对 < > 处理 2,服务端对特殊字符拦截
- return $.htmlEncode(targetVal);
- }else{
- return targetVal;
- }
- },
- /**
- * 防止恶意url
- */
- safeUrl: function(url, whiteChars){
- var strRegex = '^((https|http|ftp)://)?'//(https或http或ftp):// 可有可无
- + '(([\\w_!~*\'()\\.&=+$%-]+: )?[\\w_!~*\'()\\.&=+$%-]+@)?' //ftp的user@ 可有可无
- + '(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 3位数字.3位数字.3位数字.3位数字
- + '|' // 允许IP和DOMAIN(域名)
- + '(localhost)|' //匹配localhost
- + '([\\w_!~*\'()-]+\\.)*' // 域名- 至少一个[英文或数字_!~*\'()-]加上.
- + '\\w+\\.' // 一级域名 -英文或数字 加上.
- + '[a-zA-Z]{1,6})' // 顶级域名- 1-6位英文
- + '(:[0-9]{1,5})?' // 端口- :80 ,1-5位数字
- + '((/?)|' // url无参数结尾 - 斜杆或这没有
- + '(/[\\w_!~*\'()\\.;?:@&=+$,%#-]+)+/?)$';//请求参数结尾- 英文或数字和[]内的各种字符
- var re=new RegExp(strRegex,'i');//i不区分大小写
- //将url做uri转码后再匹配,解除请求参数中的中文和空字符影响
- if (re.test(encodeURI(url))) {
- return url;
- }else {
- return url;
- }
- },
- /**
- * 获取协议和域名
- */
- getProtocolAndDomain: function (someWindow) {
- var re = (/^((?:http|https)(?:\:\/\/)[^\/]+)/i);
- return this.getCommonForUrl(someWindow, re);
- },
-
- /**
- * 获取协议
- */
- getProtocol: function (someWindow) {
- var _window = (someWindow || _top);
- return _window.location.protocol;
- },
-
- /**
- * 获取域名
- */
- getDomain: function (someWindow) {
- var _window = (someWindow || _top);
- return _window.location.host;
- },
-
- /**
- * 获取serviceId
- */
- getServiceId: function (someWindow) {
- var _win = _top;
- if (someWindow) {
- _win = someWindow;
- }
- return shr.getUrlRequestParam('serviceId', _win.location.href);
- },
- /**
- * F7请求头的特征值
- */
- getXShrEncryptF7Value: function(){
- return window.systemParamForShr['encryptDB']+'_'+window.systemParamForShr['encryptUser']+'_'+window.systemParamForShr['encryptContext'];
- },
-
- /**
- * 获取数据中心
- */
- getDataCenter: function () {
- var dataCenter = _top.localStorage.getItem('FAccountDCName');
- if (dataCenter === 'undefined') {
- return;
- }
- return dataCenter;
- },
-
- /**
- * 提供通用的SessionStorage存储方法
- * 整个系统最好统一调用此方法
- * @param key 关键字 必须
- * @param billId 表单Id 可选
- * @param value 必须
- */
- setSessionStorage:function(key,billId,value){
- sessionStorage.setItem(this.genStorageKey(key,billId),value);
- },
- /**提供通用的SessionStorage获取方法
- * 整个系统最好统一调用此方法
- * @param key 关键字 必须
- * @param billId 表单Id 可选
- * @param value 必须
- */
- getSessionStorage:function(key,billId){
- return sessionStorage.getItem(this.genStorageKey(key,billId));
- },
-
- /**
- * 提供通用的LocalStorage 存入方法
- * 整个系统最好统一调用此方法
- * @param key 关键字 必须
- * @param billId 表单Id 可选
- * @param value 必须
- */
- setLocalStorage:function(key,billId,value){
- localStorage.setItem(this.genStorageKey(key,billId),value);
- },
-
- /**
- * 提供通用的LocalStorage 获取方法
- * 整个系统最好统一调用此方法
- * @param key 关键字 必须
- * @param billId 表单Id 可选
- */
- getLocalStorage:function(key,billId){
- return localStorage.getItem(this.genStorageKey(key,billId));
- },
-
- /**
- * SessionStorage 或者 LocalStorage 的key的生成方式,以contextId+key[+单据id(可选)]
- */
- genStorageKey:function(key,billId){
- if(key == 'data-navigationData'){
- return 'data-navigationData';
- }
- var key = window.systemParamForShr.encryptContext + '#' + key;
- if(billId){
- key += '#' + billId;
- }
- return key;
- },
-
- /**
- * 提供通用的LocalStorage 值移除方法
- * 整个系统最好统一调用此方法
- * @param key 关键字 必须
- * @param billId 表单Id 可选
- */
- removeLocalStorageItem:function(key,billId){
- localStorage.removeItem(this.genStorageKey(key,billId));
- },
- /**
- * 提供通用的SessionStorage 值移除方法
- * 整个系统最好统一调用此方法
- * @param key 关键字 必须
- * @param billId 表单Id 可选
- */
- removeSessionStorageItem:function(key,billId){
- sessionStorage.removeItem(this.genStorageKey(key,billId));
- },
- /**
- * 获取浏览器类型
- */
- getBowserInfo : function(){
- var Sys = {};
- var ua = navigator.userAgent.toLowerCase();
- var s;
- (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1] :
- (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
- (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
- (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
- (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
- (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
-
- if (Sys.ie) return { browser : "IE" , version :Sys.ie};
- if (Sys.firefox) return { browser : "Firefox" , version :Sys.firefox};
- if (Sys.chrome) return { browser : "Chrome" , version :Sys.chrome };
- if (Sys.opera) return { browser : "Opera" , version :Sys.opera };
- if (Sys.safari) return { browser : "Safari" ,version : Sys.safari };
- },
-
- /**
- *描述:ajax请求超时时间
- */
- ajaxTimeout: 600000,
-
- /**
- * ajax请求时出现阻塞提示最小间隔时间
- */
- blockMinTime: 100,
-
- dynamicURL: '/dynamic.do',
-
- openServiceURL: '/shr/msf/service.do',
- getTreeDataURL: '/dynamic.do?method=getTreeData',
-
- /**
- * 描述:注册命名空间,并返回
- * @param {String} 名称空间路径
- */
- registerNamespace : function(ns){
- var nsArray = fullNS.split('.');
- var sEval = "";
- var sNS = "";
- for (var i = 0; i < nsArray.length; i++) {
- if (i != 0)
- sNS += ".";
- sNS += nsArray[i];
- sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS
- + " = new Object();"
- }
- if (sEval != "")
- return eval(sEval);
- },
- /**
- * 描述:shr 的js 类继承
- * @param {subClass} 当前类
- * @param {superClass} 需要继承的超类
- */
- inherit : function(subClass, superClass) {
- if(superClass==null) return ;
- var Fun = function(){};//用一个空的函数作为中间缓冲,如果直接用父类的实例作为原型,可能有潜在问题,如计算量超大等
- Fun.prototype = superClass.prototype;
- subClass.prototype = new Fun();
- subClass.prototype.constructor = subClass;
- //提供 superClass 属性,这个属性可以弱化父类子类之间的耦合
- //否则,在子类中调用父类的构造函数就需要指明父类,此时只需调用这个属性即可
- subClass.superClass = superClass.prototype;
- if(superClass.prototype.constructor == Object.prototype.constructor){
- superClass.prototype.constructor = superClass;
- }
- },
- /**
- * 描述:shr 的js 类定义
- * @param subClassName 当前类
- * @param superClass 超类
- * @param prototype 当前类体
- * @return 返回创建好的JS类
- */
- defineClass:function(subClassName,superClass,prototype){
- var clzPath=subClassName.substr(0,subClassName.lastIndexOf('.'));
- var ns=Namespace.register(clzPath);
- var subClass=eval(subClassName + "=function(){};");
- shr.inherit(subClass,superClass);
- for(var p in prototype){
- eval(subClassName + ".prototype." + p.toString() + "=prototype." + p.toString());
- }
- },
- /**
- * 描述: 创建对象
- * @param {clazz} 创建该类的对象
- */
- createObject:function(clazz){
- var obj=new clazz();
- if(clazz.superClass!=null){
- obj.superClass=clazz.superClass;
- }
- //对JS类中的方法 作AOP处理
- shr.aspectClassFun(clazz,obj);
- return obj;
- },
- /**
- * 描述:对JS类中的方法作AOP处理
- * @param {} url
- * @return {}
- */
- aspectClassFun:function(clazz,object){
- var clazz_temp=clazz;
- while(clazz_temp!=null && clazz_temp!=undefined) {
- for(var p in clazz_temp.prototype){
- var methodName=p.toString();
- var beforeMethodFun=p.toString() + "_before";
- var afterMethodFun=p.toString() + "_after";
- var aroundMethodFun=p.toString() + "_replace";
- if(eval("object." + beforeMethodFun)!=null) {
- shr.aspectBefore(object,p.toString(),eval("object." + beforeMethodFun));
- }
- if(eval("object." + afterMethodFun)!=null){
- shr.aspectAfter(object,p.toString(),eval("object." + afterMethodFun));
- }
- if(eval("object." + aroundMethodFun)!=null){
- shr.aspectAround(object,p.toString(),eval("object." + aroundMethodFun));
- }
- }
- clazz_temp=clazz_temp.superClass;
- }
- },
- /**
- * 描述:JS类方法调用代理
- * @param method 方法名称
- * @param clazz JS类名称
- * @param obj 调用对象
- */
- proxyCall:function(methodName,objectName){
- var fun=null;
- if(objectName==null){
- objectName="jsBinder";
- }
- if( typeof(methodName)=="object") {
- fun=methodName;
- }
- else {
- if(typeof(objectName)=="object"){
- fun=eval(objectName[methodName]);
- }
- else {
- fun=eval(objectName + "." + methodName);
- }
- }
- if (!fun) {
- return;
- }
-
- var paramArray=[];
- if(arguments.length>2) {
- paramArray=new Array();
- for(var nIndex=2;nIndex<arguments.length;nIndex++) {
- paramArray.push(arguments[nIndex]);
- }
- }
- fun.apply(objectName,paramArray);
- },
-
- getCurrentViewPage: function(source) {
- var viewPageManager = window.viewPageManager;
- if (typeof(viewPageManager) == 'undefined') {
- return null;
- }
-
- if (typeof source == 'undefined' || source == '') {
- return viewPageManager['emptyObject'];
- }
- var ui = viewPageManager[source];
- if (ui) {
- return ui;
- }
-
- var $viewPage = $(source).closest('.view_mainPage');
- if ($viewPage) {
- var id = $viewPage.attr('id');
- if ($.isEmptyObject(id)) {
- id = 'emptyObject';
- }
- return viewPageManager[id];
- } else {
- return null;
- }
- },
-
- registerViewPage: function(key, viewPage) {
- if ($.isEmptyObject(key)) {
- key = 'emptyObject';
- }
-
- var viewPageManager = window.viewPageManager;
- if (typeof(viewPageManager) == 'undefined') {
- viewPageManager = {};
- window.viewPageManager = viewPageManager;
- }
- viewPageManager[key] = viewPage;
- },
-
- unRegisterViewPage: function(key) {
- if ($.isEmptyObject(key)) {
- key = 'emptyObject';
- }
- var viewPageManager = window.viewPageManager;
- if (viewPageManager) {
- delete viewPageManager[key];
- }
- },
-
- // 新增打开新窗口的方法,url需要调用者提供
- openNew: function (url, someWindow) {
- if (!someWindow) {
- someWindow = _top;
- }
- void(someWindow.open(url));
- },
- //检测数组中是否包含某个字符串
- arrayIndexOf: function(arr,key){
- if(!Array.isArray(arr)){
- return -1;
- }
- var bol = -1;
- arr.forEach(function(item,index){
- if(item === key){
- bol = index;
- }
- });
- return bol;
- },
- redirect: function(url, params) {
- var newUrl = url;
- if (params && typeof(params) == "object") {
- if (newUrl.indexOf('?') == -1) {
- newUrl = newUrl + '?';
- }
- if (newUrl.charAt(newUrl.length - 1) != '?') {
- newUrl = newUrl + '&';
- }
- newUrl = newUrl + $.param(params);
- }
- shr.hideErrorMsg();
- document.location.replace(newUrl);
- },
-
- urlLocate: function(url, params) {
- var newUrl = url;
- if (params && typeof(params) == "object") {
- if (newUrl.indexOf('?') == -1) {
- newUrl = newUrl + '?';
- }
- if (newUrl.charAt(newUrl.length - 1) != '?') {
- newUrl = newUrl + '&';
- }
- newUrl = newUrl + $.param(params);
- }
- shr.hideErrorMsg();
- document.location.href = newUrl;
- },
-
- assembleModel: function(fields, context, uuid) {
- var model = new Object();
- if (fields) {
- var fieldName, value;
- for (var i = 0, length = fields.length; i < length; i++) {
- fieldName = fields[i];
- if(!this.isNoEditPermField(fieldName)){ //无编辑权限字段不参与提交
- value = this.getFieldValue(fieldName, uuid);
- this.setModelFieldValue(model, fieldName, value);
- }
- }
- }
-
- var uiObject = shr.getCurrentViewPage(uuid);
- if (uiObject) {
- // add id field
- model.id = uiObject.billId;
- // add entity name
- model._entityName = uiObject.view_model;
- }
-
- return model;
- },
- assembleTemplateModel: function(fields, context, uuid) {
- var model = new Object();
- if (fields) {
- var fieldName, value;
- for (var i = 0, length = fields.length; i < length; i++) {
- fieldName = fields[i];
- value = this.getTemplateFieldValue(fieldName, uuid);
-
- this.setTamplateModelFieldValue(model, fieldName, value);
- }
- }
-
- return model;
- },
- getTemplateFieldValue: function(fieldName, uuid, context) {
- var id = this.getRealId(fieldName, uuid);
- var $element = $('#' + id, context);
- var value;
- var ctrlrole = $element.attr('ctrlrole');
- var isToTemplate = $element.attr('istotemplate');
- if(isToTemplate == 'false') return;
- if(ctrlrole) {
- ctrlrole = ctrlrole.toLowerCase();
- }
- if (ctrlrole == 'checkbox') {
- value = $element.shrCheckbox('getValue');
- }else if(ctrlrole == 'text') {
- value = $element.shrTextField('getValue');
- }else if(ctrlrole == 'promptbox') {
- value = $element.shrPromptBox('getValue');
- }else if(ctrlrole == 'datepicker') {
- value = $element.shrDatePicker('getValue');
- }else if(ctrlrole == 'datetimepicker') {
- value = $element.shrDateTimePicker('getValue');
- }else if(ctrlrole == 'textarea') {
- value = $element.shrTextarea('getValue');
- }else if(ctrlrole == 'radio') {
- value = $element.shrRadio('getValue');
- }else if(ctrlrole == 'select') {
- value = $element.shrSelect('getValue');
- }
- return value;
- },
- /*
- * url 目标url
- * arg 需要替换的参数名称
- * arg_val 替换后的参数的值
- * return url 参数替换后的url
- */
- changeURLArg: function (url, arg, arg_val) {
- var pattern = arg + '=([^&]*)';
- var replaceText = arg + '=' + arg_val;
- if (url.match(pattern)) {
- var tmp = '/(' + arg + '=)([^&]*)/gi';
- tmp = url.replace(eval(tmp), replaceText);
- return tmp;
- } else {
- if (url.match('[\?]')) {
- return url + '&' + replaceText;
- } else {
- return url + '?' + replaceText;
- }
- }
- return url + '\n' + arg + '\n' + arg_val;
- },
-
- convertId: function(id) {
- return id.replace(/\./g, '_');
- },
-
- strToEscape: function(str) {
- return str.replace(/&/g, '&');
- },
-
- htmlEncode: function(value) {
- return $('<div/>').text(value).html();
- },
-
- htmlDecode: function(value) {
- return $('<div/>').html(value).text();
- },
- /**
- * 转义符换成普通字符
- */
- strEscape: function (str) {
- var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
- var result = '';
- if (str) {
- result = str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
- return arrEntities[t];
- });
- }
- return result;
- },
- getRealId: function(id, uuid) {
- id = this.convertId(id);
- if (uuid) {
- id = id + uuid;
- }
- return id;
- },
-
- getValueByRole: function (role, $element, id, context, isFromWF) {
- var value;
- var handler = {
- 'checkbox': function(){
- var value;
- if (typeof $element.attr("checked") == 'undefined') {
- value = 0;
- } else {
- var _v_ = $element.shrCheckbox('getValue');
- if(_v_){
- value= 1;
- }else{
- value = 0;
- }
- }
- return value;
- },
- 'editGrid': function () {
- var collection = $element.jqGrid('getAllPageData');
- return collection;
- },
- 'shrMultiLangBox': function () {
- return $element.shrMultiLangBox('getTransformedValue');
- },
- 'datetimepicker': function(){
- return $element.shrDateTimePicker('getValue');
- },
- 'numberField': function () {
- return $element.shrNumberField('getValue');
- },
- 'shrFieldDisplay': function() {
- return $element.shrFieldDisplay('getOriginalValue') || $element.shrFieldDisplay('getValue');
- }
- }
- //兼容ie下select控件'01'value值会被浏览器改变为'1'
- if(shr.getBowserInfo().browser == 'IE'){
- handler.select = function() {
- return $element.shrSelect('getValue').value;
- }
- }
- //查看状态下的分录role为grid
- if(role === 'grid' && _self.getOperateState() === 'VIEW'){
- role = 'editGrid';
- }
- if (handler.hasOwnProperty(role)) {
- value = handler[role]();
- } else {
- value = shr.createObject(shr.framework.Widget).getInputValue(id, context, isFromWF);
- }
- return value;
- },
-
- getFieldValue: function (fieldName, uuid, context) {
- var id = this.getRealId(fieldName, uuid);
- var $element = $('#' + id, context);
- var role = $element.attr('ctrlrole');
- var value = this.getValueByRole(role, $element, id, context,false);
- return value;
- },
- /**
- * 根据字段id和方法名来执行方法
- * 使用该方法的前提是具有ctrlrole属性,并且组件中有传入的方法名对应的方法
- * fieldId:是字段的id
- * methodName:方法名
- * arguments:执行的方法要传递的参数
- * context:上下文,可选参数,如果某些iframe中获取不到元素,则需要传上下文
- */
- execByFieldIdAndMethod: function (fieldId, methodName, _arguments, context) {
- var id = this.getRealId(fieldId);
- var $element = $('#' + id, context);
- try {
- if ($element.length == 0) {
- throw 'can not find the suitable element';
- }
- var ctrlrole = $element.attr('ctrlrole');
- if (!ctrlrole) {
- throw 'this elment has no ctrlrole attribute'
- }
- var componentName = this.getComponentNameByCtrlrole(ctrlrole);
- if (_arguments) {
- return $element[componentName](methodName, _arguments);
- }
- return $element[componentName](methodName);
- } catch (e) {
- console.error(e);
- }
- },
-
- /**
- * 根据字段id和方法名来执行方法
- * 使用该方法的前提是具有ctrlrole属性,并且组件中有传入的方法名对应的方法
- * $element:是jquery对象
- * methodName:方法名
- * arguments:执行的方法要传递的参数
- */
- execByElementAndMethod: function ($element, methodName, _arguments) {
- try {
- if ($element.length == 0) {
- throw 'can not find the suitable element';
- }
- var ctrlrole = $element.attr('ctrlrole');
- if (!ctrlrole) {
- throw 'this elment has no ctrlrole attribute'
- }
- var componentName = this.getComponentNameByCtrlrole(ctrlrole);
- if (_arguments) {
- return $element[componentName](methodName, _arguments);
- }
- return $element[componentName](methodName);
- } catch (e) {
- console.error(e);
- }
- },
- /**
- * 根据ctrlrole获取对应的组件名称
- */
- getComponentNameByCtrlrole: function (ctrlrole) {
- var componentName;
- var mapping = {
- 'checkbox': 'shrCheckbox',
- 'radio':'shrRadio',
- 'select':'shrSelect',
- 'text':'shrTextField',
- 'shrSetIndexCode':'shrSetIndexCode',
- 'shrDetailTips':'shrDetailTips',
- 'shrFastFilter':'shrFastFilter',
- 'shrGridConfig':'shrGridConfig',
- 'shrIconUpload':'shrIconUpload',
- 'intlCell':'shrIntlCell',
- 'shrMessageTips':'shrMessageTips',
- 'multiSelect':'shrMultiSelect',
- 'shrSaveFilterSchemeDialog':'shrSaveFilterSchemeDialog',
- 'shrSpreadChooseAll':'shrSpreadChooseAll',
- 'shrTableDialog':'shrTableDialog',
- 'textarea':'shrTextarea',
- 'shrMultiLangBox': 'shrMultiLangBox',
- 'datetimepicker': 'shrDateTimePicker',
- 'dateSpanPicker':'shrDateSpanPicker',
- 'numberField': 'shrNumberField',
- 'shrFieldDisplay': 'shrFieldDisplay',
- 'promptBox':'shrPromptBox',
- }
- if (mapping.hasOwnProperty(ctrlrole)) {
- componentName = mapping[ctrlrole];
- }else{
- throw 'can not find the suitable component';
- }
- return componentName;
- },
-
- setModelFieldValue: function(model, fieldName, value) {
- if (fieldName.indexOf('.') != -1) {
- var fields = fieldName.split('.');
- var subModel;
- for (var i = 0, length = fields.length - 1; i < length; i++) {
- fieldName = fields[i];
- subModel = model[fieldName];
- if (typeof subModel == 'undefined') {
- subModel = {};
- model[fieldName] = subModel;
- }
- model = subModel;
- }
- fieldName = fields[fields.length - 1];
- }
- model[fieldName] = value;
- },
- setTamplateModelFieldValue: function(model, fieldName, value) {
- if (fieldName.indexOf('.') != -1) {
- var fields = fieldName.split('.');
- fieldName = fields.join('_');
- }
- model[fieldName] = value;
- },
- /**
- * 增加表单数据进行加密传输
- * 表单数据有些格式数据会被防火墙或者网络安全策略拦截,导致保存失败
- * @param data
- */
- encryptFormModelData:function(data){
- var option={model:data.model};
- var encryptObj = shr.encryptForObj(option, null);
- data.model = encryptObj.obj['model'];
- data.encryptKeys='encryptKeys:' + $.allEncrypt('model');
- },
- addEncryptParams:function(postData,key,value){
- var option ={};
- option[key]=value;
- var encryptObj = $.encryptForObj(option, null);
- $.extend(postData, encryptObj.obj);
- if (!postData.encryptKeys){
- postData.encryptKeys = encryptObj.keyStr;
- } else if(shr.arrayIndexOf(postData.encryptKeys.split(','),encryptObj.keyStr) == -1 && key != 'encryptKeys') {
- postData.encryptKeys = postData.encryptKeys+','+ encryptObj.keyStr;
- }
- },
- /**
- * 增加接口数据进行加密传输
- * @param postData
- */
- addEncryptPostData: function(postData,isAllEncrypt){
- if(postData){
- var encryptKeysStr = postData.encryptKeys;
- var needEncryptKey = shr.needEncryptKey();
- if(encryptKeysStr && encryptKeysStr.indexOf('encryptKeys:') != -1){
- encryptKeysStr = $.allDecrypt(encryptKeysStr.substring(12,encryptKeysStr.length));
- }else if(encryptKeysStr && encryptKeysStr.indexOf('encryptKeys:') < 0){
- var optEncryptKeysArray = encryptKeysStr.split(',');
- optEncryptKeysArray.forEach(function(item){
- if(shr.arrayIndexOf(needEncryptKey,item) < 0){
- needEncryptKey.push(item);
- }
- });
- }
- if(postData.encryptKeys && encryptKeysStr){
- var encryptKeys = encryptKeysStr;
- for(var key in postData){
- if(shr.arrayIndexOf(encryptKeys.split(','),key) != -1 && key != 'encryptKeys'){
- try {
- if($.allDecrypt(postData[key])){
- postData[key] = $.allDecrypt(postData[key]);
- }
- } catch (error) {}
- }
- }
- postData.encryptKeys = '';
- }else if(!postData.encryptKeys){
- postData.encryptKeys = '';
- }
- }
- for(var key in postData){
- if(postData[key] && !Array.isArray(postData[key])){
- if(!isAllEncrypt && shr.arrayIndexOf(needEncryptKey,key) >= 0){
- shr.addEncryptParams(postData, key, postData[key]);
- }else if(isAllEncrypt && shr.arrayIndexOf(['method','serviceName','uipk','encryptKeys'],key) < 0){
- shr.addEncryptParams(postData, key, postData[key]);
- }
- }
- }
- if(postData.encryptKeys){
- postData.encryptKeys = 'encryptKeys:' + $.allEncrypt(postData.encryptKeys);
- }
- },
- needEncryptKey: function(){
- return ['filterItems','filter',
- 'fastFilterItems','sorterItems','advancedFilter','custom_params',
- 'tree_params','columnModel','queryMode','exportPrivteProtected',
- 'keyField','dataPerm','fieldName_key','searchFilterItems','categoryFilter',
- 'contractFilter','dynamicSql','model','order'];
- },
- //将url参数转换成对象类型,并且参数值做了 decodeURIComponent,所以 仅供与dealPostParam去使用,别的地方不可以使用
- urlParamsToObject: function(url) {
- var queryString = url.split('?').length > 1?url.split('?')[1]:'';
- var paramsArr = queryString.split('&');
- var paramObj = {};
-
- for ( var i = 0; i < paramsArr.length; i++) {
- var pos = paramsArr[i].indexOf('=');// 查找name=value
- if (pos == -1) continue;// 如果没有找到就跳过
- var argname = paramsArr[i].substring(0, pos);// 提取name
- var value = paramsArr[i].substring(pos + 1);// 提取value
- try {
- paramObj[argname] = decodeURIComponent(value);
- } catch (error) {
- paramObj[argname] = value;
- }
- }
- return paramObj;
- },
- dealPostParam: function(option){
- var isHasKey = false;
- var isUrlHasKey = false;
- if(option.data){
- if(option.data.noEncrypt) return;
- var encryptKey = shr.needEncryptKey();
- var optEncryptKeys = option.data.encryptKeys;
- if(optEncryptKeys && optEncryptKeys.indexOf('encryptKeys:') < 0){
- var optEncryptKeysArray = optEncryptKeys.split(',');
- optEncryptKeysArray.forEach(function(item){
- if(shr.arrayIndexOf(shr.needEncryptKey(),item) < 0){
- encryptKey.push(item);
- }
- });
- }
- for(var item in option.data){
- if(shr.arrayIndexOf(encryptKey,item) >= 0){
- isHasKey = true;
- }
- }
- if(option.url.indexOf('/shr/dynamic.do') >= 0){
- encryptKey.forEach(function(item){
- if(option.url.indexOf(item) >= 0){
- isUrlHasKey = true;
- }
- });
- }
- }
-
- if(option.url.indexOf('getListData') >= 0 || isUrlHasKey){
- var paramObj = shr.urlParamsToObject(option.url);
- option.url = option.url.split('?')[0];
- $.extend(option.data,paramObj);
- shr.addEncryptPostData(option.data);
- option.type = 'POST';
- }else if(option.data && option.data.method == 'callService'){
- shr.addEncryptPostData(option.data,true);
- }else if(option.data && option.data.method == 'exportToExcel'
- || option.data && option.data.method == 'newTask'){
- shr.addEncryptPostData(option.data);
- }else if(option.data && option.data.method == 'getCompareResults'){
- option.data.a = $.allEncrypt(option.data.a);
- option.data.b = $.allEncrypt(option.data.b);
- option.data.encryptKeys='encryptKeys:' + $.allEncrypt('a,b');
- }else if(isHasKey){
- shr.addEncryptPostData(option.data);
- }
- },
- doAction: function(option) {
- //shr.dealPostParam会修改options,防止影响外部参数引用
- var option = $.extend(true,{},option);
- // disible button
- if (option.target) {
- var $target = $(option.target);
- if ($target.is('button')) {
- $target.addClass('shrbtn-disabled');
- $target.attr('disabled', 'disabled');
- }
- }
-
- //拼接请求URL
- if(option.url == null){
- if(option.param != null) {
- option.url = "?method=" + option.action + "&" + option.param;
- }
- else {
- option.url="?method=" + option.action;
- }
- }
-
- //默认传输格式为json
- if(option.dataType==null){
- option.dataType = "json";
- }
- //默认请求超时时间为ajaxTimeout
- if(option.timeout==null) {
- option.timeout=this.ajaxTimeout;
- }
- //默认表单名称为form
- /*if(option.form==null){
- option.form="form";
- }*/
- //默认提交方式为异步方式
- if(option.async==null){
- option.async=true;
- }
-
- //默认阻塞界面
- if(option.showBlock == null){
- option.showBlock = true;
- }
- // add check data
- this._addCommonExtParam( option );
- this.dealPostParam( option );
- //var timer=null;
- var requestOption = {
- url: option.url,
- data: option.data,
- /* 默认ajax数据交互格式为json */
- dataType: option.dataType,
- type: option.type,
- async: option.async,
- timeout: option.timeout,
- success: function(obj, textStatus) {
-
- if (option.showBlock == true) {
- clearTimeout(timer);
- $.block.hide();
- }
-
- if(obj == null){
- option.success(null);
- return ;
- }
- if (option.dataType == 'json') {
- //自行处理返回
- if(option.ignoreHandlerMessage && option.ignoreHandlerMessage == true){
- option.success(obj, textStatus);
- return;
- }
- if(obj.result == "success") {
- var message = obj.successMessage;
- if (!message) {
- message = $.shrI18n.common.tips.operateSuccess;
- }
- shr.showSuccess({
- message: message,
- hideAfter: 3
- });
- //如果是portal跳转过来,top为0,否则为60px
- if (isFromPortal()) {
- $("ul[class='messenger messenger-fixed messenger-theme-air messenger-on-top messenger-theme-future']").css('top', 0);
- } else {
- $("ul[class='messenger messenger-fixed messenger-theme-air messenger-on-top messenger-theme-future']").css('top', '60px');
- }
- //调用回调函数
- if(option.success) {
- option.success(obj.data, obj.uiItems, obj.script);
- }
- } else if(obj.result == "error") {
- var message = obj.summary;
- // if (!$.isEmptyObject(obj.detailInfo)) {
- // message = message + '<br>' + obj.detailInfo;
- // }
- if (!message) {
- message = $.shrI18n.common.tips.operateFail;
- }
- shr.showError({message: message});
- //调用回调函数
- if(option.error) {
- option.error(obj.data, obj.uiItems, obj.script);
- }
- }
- } else {
- if(option.success != null) {
- shr.showInfo({
- message: $.shrI18n.common.tips.operateSuccess,
- hideAfter: 3
- });
- shr.stopAllMask();
- //调用回调函数
- if(option.success) {
- option.success(obj);
- }
- }
- }
- },
- error:function(response, textStatus, errorThrown) {
- return shr.handleError(option, response, textStatus, errorThrown);
- },
- complete:function(jqXHR, textStatus){
- if(option.complete && waf.isFunction(option.complete)){
- option.complete.call(this, jqXHR, textStatus);
- }
- /*if (option.showBlock == true) {
- clearTimeout(timer);
- $.block.hide();
- }*/
- if (option.target) {
- var $target = $(option.target);
- if ($target.is('button')) {
- $target.removeClass('shrbtn-disabled');
- $target.removeAttr('disabled');
- }
- }
- }
- };
- var messageOptions = {
- //successMessage : '操作成功!',
- errorMessage : $.shrI18n.common.tips.operateFail,
- progressMessage : $.shrI18n.common.tips.operating,
- showCloseButton: true,
- singleton: true,
- hideAfter: null
- };
- shr.msgHideAll();
-
- //锁定BODY
- if (option.showBlock == true) {
- /*$.block.show({
- text: '正在执行,请稍候...'
- });*/
- timer = setTimeout(function() {
- $.block.show({
- text: $.shrI18n.common.loadingText.runningPlsWait
- });
- }, shr.blockMinTime);
- }
-
- _top.Messenger().run(messageOptions, requestOption);
-
- /*//锁定BODY
- if(option.showBlock==true){
- timer=setTimeout(function(){
- waf.block.show({text:waf.localeResourceObj.AJAX_ASYNC_BLOCK_INFO});
- },
- 500);
- }*/
- /*报出提交事件 */
- /*$('#' + option.form).trigger("onSubmit");
- 提交
- $('#' + option.form).ajaxSubmit(requestOption);*/
- },
- //检测数组中是否包含某个字符串
- arrayIndexOf: function(arr,key){
- if(!Array.isArray(arr)){
- return -1;
- }
- var bol = -1;
- arr.forEach(function(item,index){
- if(item === key){
- bol = index;
- }
- });
- return bol;
- },
- /**
- * 判断是否是一个json
- */
- isJSON: function(str) {
- if (typeof str == 'string') {
- try {
- var obj = JSON.parse(str);
- if(typeof obj == 'object' && obj ){
- return true;
- }else{
- return false;
- }
- } catch(e) {
- return false;
- }
- }
- },
- doWithBatchAction: function(option) {
- //shr.dealPostParam会修改options,防止影响外部参数引用
- var option = $.extend(true,{},option);
- // disible button
- if (option.target) {
- var $target = $(option.target);
- if ($target.is('button')) {
- $target.addClass('shrbtn-disabled');
- $target.attr('disabled', 'disabled');
- }
- }
-
- //拼接请求URL
- if(option.url == null){
- if(option.param != null) {
- option.url = "?method=" + option.action + "&" + option.param;
- }
- else {
- option.url="?method=" + option.action;
- }
- }
-
- //默认传输格式为json
- if(option.dataType==null){
- option.dataType = "json";
- }
- //默认请求超时时间为ajaxTimeout
- if(option.timeout==null) {
- option.timeout=this.ajaxTimeout;
- }
- //默认表单名称为form
- /*if(option.form==null){
- option.form="form";
- }*/
- //默认提交方式为异步方式
- if(option.async==null){
- option.async=true;
- }
-
- //默认阻塞界面
- if(option.showBlock == null){
- option.showBlock = true;
- }
- // add check data
- this._addCommonExtParam( option );
- shr.dealPostParam( option );
- //var timer=null;
- var requestOption = {
- url: option.url,
- data: option.data,
- /* 默认ajax数据交互格式为json */
- dataType: option.dataType,
- type: option.type,
- async: option.async,
- timeout: option.timeout,
- success: function(obj, textStatus) {
-
- if (option.showBlock == true) {
- clearTimeout(timer);
- $.block.hide();
- }
-
- if(obj == null){
- option.success(null);
- return ;
- }
- if (option.dataType == 'json') {
- if(obj.result == "success") {
- // var message = obj.successMessage;
- // if (!message) {
- // message = '操作成功!';
- // }
- // shr.showInfo({
- // message: message,
- // hideAfter: 3
- // });
- //调用回调函数
- if(option.success) {
- option.success(obj.data, obj.uiItems, obj.script);
- }
- } else if(obj.result == "error") {
- var message = obj.summary;
- // if (!$.isEmptyObject(obj.detailInfo)) {
- // message = message + '<br>' + obj.detailInfo;
- // }
- if (!message) {
- message = $.shrI18n.common.tips.operateFail;
- }
- shr.showError({message: message});
- //调用回调函数
- if(option.error) {
- option.error(obj.data, obj.uiItems, obj.script);
- }
- }
- } else {
- if(option.success != null) {
- // shr.showInfo({
- // message: "操作成功!",
- // hideAfter: 3
- // });
- //调用回调函数
- if(option.success) {
- option.success(obj);
- }
- }
- }
- },
- error:function(response, textStatus, errorThrown) {
- return shr.handleError(option, response, textStatus, errorThrown);
- },
- complete:function(jqXHR, textStatus){
- if(option.complete && waf.isFunction(option.complete)){
- option.complete.call(this, jqXHR, textStatus);
- }
- /*if (option.showBlock == true) {
- clearTimeout(timer);
- $.block.hide();
- }*/
- if (option.target) {
- var $target = $(option.target);
- if ($target.is('button')) {
- $target.removeClass('shrbtn-disabled');
- $target.removeAttr('disabled');
- }
- }
- }
- };
- var messageOptions = {
- //successMessage : '操作成功!',
- errorMessage : $.shrI18n.common.tips.operateFail,
- progressMessage : $.shrI18n.common.tips.operating,
- showCloseButton: true,
- singleton: true,
- hideAfter: null
- };
- shr.msgHideAll();
-
- //锁定BODY
- if (option.showBlock == true) {
- /*$.block.show({
- text: '正在执行,请稍候...'
- });*/
- timer = setTimeout(function() {
- $.block.show({
- text: $.shrI18n.common.loadingText.runningPlsWait
- });
- }, shr.blockMinTime);
- }
-
- var messageFun;
- if($.isFunction(_top.Messenger)){
- messageFun = _top.Messenger();
- }else{
- messageFun = Messenger();
- }
- messageFun.run(messageOptions, requestOption);
-
- /*//锁定BODY
- if(option.showBlock==true){
- timer=setTimeout(function(){
- waf.block.show({text:waf.localeResourceObj.AJAX_ASYNC_BLOCK_INFO});
- },
- 500);
- }*/
- /*报出提交事件 */
- /*$('#' + option.form).trigger("onSubmit");
- 提交
- $('#' + option.form).ajaxSubmit(requestOption);*/
- },
- /**
- *此请求,要求success函数一定要进行回调重写
- */
- doAjaxNeedSuccess: function(option) {
- option.successResultSelfHandler = true;
- return $.doAjax(option);
- },
- doAjax: function(option) {
- //拼接请求URL
- if(option.url == null && option.action){
- if(option.param != null) {
- option.url = "?method=" + option.action + "&" + option.param;
- } else {
- option.url= "?method=" + option.action;
- }
- }
- if (option.data && !(option.data.method) && option.action) {
- option.data.method = option.action;
- }
-
- //默认传输格式为json
- if(option.dataType==null){
- option.dataType = "json";
- }
- //默认请求超时时间为ajaxTimeout
- if(option.timeout==null) {
- option.timeout=this.ajaxTimeout;
- }
- //默认表单名称为form
- /*if(option.form==null){
- option.form="form";
- }*/
- //默认提交方式为异步方式
- if(option.async==null){
- option.async=true;
- }
-
- //默认阻塞界面
- /*if(option.showBlock==null){
- option.showBlock = true;
- }*/
- // add check data
- this._addCommonExtParam( option );
- //var timer=null;
- var requestOption = {
- url: option.url,
- data: option.data,
- /* 默认ajax数据交互格式为json */
- dataType: option.dataType,
- type: option.type,
- async: option.async,
- timeout: option.timeout,
- error: function(response, textStatus, errorThrown) {
- if(option.error && $.isFunction(option.error)){
- return option.error.call(this, response, textStatus, errorThrown);
- } else {
- return shr.handleError(option, response, textStatus, errorThrown);
- }
- },
- complete: function(jqXHR, textStatus){
- if(option.complete && $.isFunction(option.complete)){
- option.complete.call(this, jqXHR, textStatus);
- }
- if (option.showBlock == true) {
- clearTimeout(timer);
- $.block.hide();
- }
- }
- };
-
- if (option.success) {
- requestOption.success = function(obj, textStatus) {
- //解锁BODY
- if (option.showBlock == true) {
- clearTimeout(timer);
- $.block.hide();
- }
-
- if(obj == null){
- option.success(null);
- return ;
- }
-
- if(option.successResultSelfHandler === true){
- option.success(obj, textStatus);
- return;
- }
- if (option.dataType == 'json') {
- if(obj.result == "success") {
- if(option.success != null) {
- //调用回调函数
- option.success(obj.data, obj.uiItems, obj.script);
- }
- } else if(obj.result == "error") {
- //$('body').html(obj);
- //var message = obj.summary + '<br>' + obj.detailInfo;
- var message = obj.summary;
- shr.showError({message: message});
- if(option.error != null) {
- option.error(obj);
- }
- } else {
- option.success(obj);
- }
- } else {
- if(option.success != null) {
- //调用回调函数
- option.success(obj);
- }
- }
- };
- }
- //锁定BODY
- if (option.showBlock == true) {
- timer = setTimeout(function() {
- $.block.show({
- text: $.shrI18n.common.loadingText.runningPlsWait
- });
- }, shr.blockMinTime);
- }
-
- if(option.contentType){
- requestOption.contentType = option.contentType;
- }
- if(option.headers){
- requestOption.headers = option.headers;
- }
- return $.ajax(requestOption);
- },
-
- /**
- * 判断是否是session失效,重定向到登录页面
- */
- checkIsRedirectLogin: function(response) {
- var content;
- if (typeof response == 'string') {
- content = response;
- } else if (typeof response == 'object' && response.responseText) {
- content = response.responseText;
- }
-
- if (content && content.indexOf('action="login?') != -1) {
- shr.redirectLogin();
- return true;
- }
- return false;
- },
-
- /**
- * 重定向登录页面
- */
- redirectLogin: function() {
- _top.location.href = _top.location.href
- },
-
- doGet: function(option) {
- //拼接请求URL
- if(option.url == null){
- if(option.param != null) {
- option.url = "?method=" + option.action + "&" + option.param;
- }
- else {
- option.url="?method=" + option.action;
- }
- }
-
- //默认传输格式为json
- if(option.dataType==null){
- option.dataType = "html";
- }
- //默认请求超时时间为ajaxTimeout
- if(option.timeout==null) {
- option.timeout=this.ajaxTimeout;
- }
- //默认提交方式为异步方式
- if(option.async==null){
- option.async = true;
- }
- //添加shruicode
- this._addShruicode( option.data );
- //var timer=null;
- var url = option.url;
- var requestOption = {
- url: option.url,
- data: option.data,
- /* 默认ajax数据交互格式为json */
- dataType: option.dataType,
- type: option.type,
- async: option.async,
- timeout: option.timeout,
- success: function(obj, textStatus) {
- //obj返回可能为空
- var $response;
- try {
- $response = $(obj);
- }catch (e){
- console.log('response data exception: null data response.');
- }
-
- if ($response && $response.filter('meta[content=error-page]').length > 0) {
- var regexp1 = /<script .*?src=\"(.+)\"><\/script>/g;
- var regexp2 = /<script>([\s\S]*)<\/script>/g;
- var codes1 = [];
- var result = obj.replace(regexp1,function(script,code){
- codes1.push(code);
- return '';
- });
-
- var codes2 = [];
- result = obj.replace(regexp2,function(script,code){
- codes2.push(code);
- return '';
- });
- var container = _top.document.body;
- container.innerHTML = result;
-
- codes1.forEach(function(code){
- var script = document.createElement('script');
- script.type = 'text/javascript';
- script.src = code;
- container.appendChild(script);
- });
- codes2.forEach(function(code){
- var script = document.createElement('script');
- script.innerHTML = code;
- container.appendChild(script);
- });
- return;
- }
-
- if(obj == null){
- option.success(null);
- return ;
- }
-
- if(option.success != null) {
- //调用回调函数
- option.success(obj);
- }
- },
- error:function(response, textStatus, errorThrown) {
- return shr.handleError(option, response, textStatus, errorThrown);
- },
- complete:function(jqXHR, textStatus){
- // TODO 稍后补充
- }
- };
- /*var messageOptions = {
- errorMessage : '操作失败!',
- //progressMessage : '操作中',
- showCloseButton: true,
- singleton: true,
- hideAfter: null
- };
- //shr.msgHideAll();
- _top.Messenger().run(messageOptions, requestOption);*/
- $.ajax(requestOption);
- },
-
- handleError: function(option, response, textStatus, errorThrown) {
- // 同一用户登录,踢出的时候,还有未完成的ajax请求,返回退出页面这里,特殊处理
- if((response.responseText && response.responseText.indexOf("window.logoutHR()") !=-1 ) || (response.responseText && response.responseText.indexOf("#reloadtips") !=-1)){
- window.location = '/shr/reloadtips.jsp';
- return ;
- }
- if (shr.checkIsRedirectLogin(response)) {
- return false;
- }
-
- if (option.showBlock == true) {
- clearTimeout(timer);
- $.block.hide();
- }
-
- var message;
- if ((response != null ? response.status : void 0) === 404) {
- message = $.shrI18n.common.loadingText.pageNotFound;
- } else {
- var nExMsgStartIdx = response.responseText && response.responseText.indexOf("<title>");
- var nExMsgEndIdx = response.responseText && response.responseText.indexOf("</title>");
- var strErrorSummary = response.responseText && response.responseText.substr(nExMsgStartIdx + 7, nExMsgEndIdx - nExMsgStartIdx - 7);
-
- if (strErrorSummary != '') {
- message = strErrorSummary;
- } else {
- nExMsgStartIdx = response.responseText && response.responseText.indexOf("{");
- nExMsgEndIdx = response.responseText && response.responseText.indexOf("}");
- strErrorSummary = response.responseText && response.responseText.substr(nExMsgStartIdx, nExMsgEndIdx+1);
- try{
- var _tempError_ = JSON.parse(strErrorSummary);
- if(_tempError_ && _tempError_ instanceof Object && _tempError_['summary']){
- message = _tempError_['summary'];
- }else{
- message = response.responseText;
- }
- }catch(error){
- console.log(error);
- message = response.responseText;
- }
- }
- }
- shr.showError({message: message});
- //console.log('ajax error, url: ' + option.url + '?' + $.param(option.data));
- return false;
- },
- /**
- * 处理OSF入参加密
- * @data 为OSF信息
- * @param 为OSF需要传入的参数
- */
- handlerServiceParam:function(data, param){
- if(data.inputParams || data.inputParams.length == 0){
- return;
- }
- if(!data.encryptKey){
- return;
- }
- $.each(param, function(name, value) {
- if(shr.isNeedEncryptParam(name,data.inputParams)){
- param[name] = this.encryptForAes_CBC(value, data.encryptKey);
- }
- });
- },
- /**
- * 判断OSF中参数是否需要加密的参数
- * @name 参数名称
- * @inputParams OSF参数集合
- */
- isNeedEncryptParam:function(name, inputParams){
- for (var i = 0,total = inputParams.length; i < total; i++) {
- if(name==inputParams[i]['paramName']){
- return true;
- }
- }
- return false;
- },
-
- /**
- * @option 中
- * 新增属性isEncrypt 标记返回值是否已经加密
- * 新增属性encryptKey 配置isEncrypt标记进行cbc解密,需要调用(this.decryptForAes_CBC)
- * OSF的参数中某个具体参数需要进行加密传输,需要调用(this.encryptForAes_CBC)
- */
- callService: function(option) {
- if ($.isEmptyObject(option)) {
- return;
- }
- // url
- var url = shr.getContextPath() + '/shr/msf/service.do';
- option.url = url;
- // data
- var param = shr.getRequestParam(option);
- param.method = 'callService';
- param.serviceName = option.serviceName;
- delete option.serviceName;
- option.data = param;
- //强制POST请求
- option.type = 'POST';
- // 默认为同步
- if (typeof option.async == 'undefined') {
- option.async = false;
- }
- return this.doRemoteCall(option);
- },
- // private
- getRequestParam: function(option) {
- var param;
- if (option.param) {
- param = option.param;
- // 如参数中的对象参数进行处理,如果为对象则转换为JSON格式
- $.each(param, function(name, value) {
- if ($.isPlainObject(value)) {
- param[name] = $.toJSON(value);
- }
- });
- delete option.param;
- } else {
- param = {};
- }
-
- return param;
- },
-
- doRemoteCall: function(option) {
- var xhr = $.doAjax(option);
- if (option.async) {
- return xhr;
- }else {
- var response;
- if(xhr.adapteOSFResponseDataFormat && xhr.isOSFRequest){
- response = xhr.responseJSON;
- } else {
- response = shr.explainJson(xhr.responseText);
- }
- if (response && response.data) {
- return response.data;
- } else {
- return response;
- }
- }
- },
-
- callHandler: function(option) {
- if ($.isEmptyObject(option)) {
- return;
- }
-
- // url
- var url = shr.getContextPath() + shr.dynamicURL;
- option.url = url;
- // data
- var param = shr.getRequestParam(option);
- param.method = option.action;
- param.handler = option.handler;
- delete option.action;
- delete option.handler;
-
- option.data = param;
- //option.showBlock = true;
-
- // 默认为异步
- if (typeof option.async == 'undefined') {
- option.async = true;
- }
- // 默认为get请求
- if (typeof option.type == 'undefined') {
- option.type = 'GET';
- }
-
- return this.doRemoteCall(option);
- },
- remoteCall: function(option) {
- // 这里加一个变量用来控制,参数是否需要转化,isTransformParam = true时,不需要对参数进行转化,直接用传进来的参数即可
- var isTransformParam = option.isTransformParam || false;
- if ($.isEmptyObject(option)) {
- return;
- }
-
- // url
- if (typeof option.url == 'undefined') {
- option.url = shr.getContextPath() + shr.dynamicURL;
- }
-
- // data
- var param
- if (!isTransformParam) {
- param = shr.getRequestParam(option);
- } else {
- param = option.param
- }
-
- param.method = option.method;
- param.uipk = option.uipk;
- delete option.method;
- delete option.uipk;
-
- option.data = param;
-
- // 默认为异步
- if (typeof option.async == 'undefined') {
- option.async = true;
- }
- // 默认为POST请求
- if (typeof option.type == 'undefined') {
- option.type = 'POST';
- }
-
- return this.doRemoteCall(option);
- },
-
- /**
- * 添加自定义统计事件
- */
- trackEvent: function(category, action, opt_label, opt_value) {
- var hmt = shr.getOwnerWindow()._hmt;
- if (hmt) {
- if ($.isEmptyObject(category)) {
- category = document.location.href;
- }
- hmt.push(['_trackEvent', category, action, opt_label, opt_value]);
- }
- },
-
- /**
- * 获得数据所存放的位置
- */
- getOwnerWindow: function() {
- var win;
- if (window.parent != window) {
- // 表示存在父窗口
- win = window.parent;
- } else {
- win = window;
- }
- return window;
- },
-
- /**
- * 描述:获取URL所对应的参数数组
- * @param {url} url 路径
- * @return 返回URL后追加的参数数组
- */
- getUrlParams : function(url) {
- var args = new Object();
- var query = location.search.substring(1);// 获取查询串
- var pairs = query.split("&");// 在逗号处断开
- for ( var i = 0; i < pairs.length; i++) {
- var pos = pairs[i].indexOf('=');// 查找name=value
- if (pos == -1)
- continue;// 如果没有找到就跳过
- var argname = pairs[i].substring(0, pos);// 提取name
- var value = pairs[i].substring(pos + 1);// 提取value
- args[argname] = unescape(value);// 存为属性
- }
- return args;
- },
-
- getUrlRequestParam : function(param, url) {
- if (typeof url == 'undefined') {
- url = location.href;
- }
-
- var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&"),
- paraObj = {};
- //url中参数格式含a=&&这种的容错处理 2017/06/28 tiangang_yang
- for (i = 0; /* j = paraString[i] ;*/i < paraString.length; i++) {
- var j = paraString[i];
- paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j
- .substring(j.indexOf("=") + 1, j.length);
- }
- var returnValue = paraObj[param.toLowerCase()];
- if (typeof (returnValue) == 'undefined' || returnValue == 'undefined') {
- return "";
- } else {
- if (returnValue.charAt(returnValue.length - 1) == '#') {
- returnValue = returnValue.substr(0, returnValue.length - 1);
- }
-
- return decodeURIComponent(returnValue);
- }
- },
-
- /**
- * 描述:获取页面根路径
- * @return 返回页面根路径 如:http://{domain}:{port}/{当前应用实例名称}
- */
- getContextPath:function() {
- var contextPath = window._contextPath;
- if (typeof contextPath == 'undefined') {
- var href = window.location.href;
- var host = window.location.host;
- var f1 = href.substring(href.indexOf(host))
- var f2 = f1.substring(f1.indexOf("/"));
- var next = f2.indexOf('/', 1);
- if (next != -1) {
- contextPath = f2.substring(0, next);
- } else {
- contextPath = '';
- }
- }
- return contextPath;
- },
-
- getOpenServiceFullPath: function() {
- return shr.getContextPath() + shr.openServiceURL;
- },
-
- showInfo: function(options) {
- shr.msgHideAll();
- options = $.extend({
- type: 'info',
- hideAfter: 3,
- showCloseButton: true
- }, options);
- if($.isFunction(_top.Messenger)) {
- _top.Messenger().post(options);
- }else{
- Messenger().post(options);
- }
- },
- showSuccess: function(options) {
- shr.msgHideAll();
- options = $.extend({
- type: 'success',
- hideAfter: 3,
- showCloseButton: true
- }, options);
- if($.isFunction(_top.Messenger)) {
- _top.Messenger().post(options);
- }else{
- Messenger().post(options);
- }
- },
-
- showError: function(options) {
- shr.msgHideAll();
-
- if ($.isEmptyObject(options.message)) {
- return;
- }
- options = $.extend({
- type: 'error',
- hideAfter: null,
- showCloseButton: true
- }, options);
- if($.isFunction(_top.Messenger)) {
- _top.Messenger().post(options);
- }else{
- Messenger().post(options);
- }
- },
-
- showWarning: function(options) {
- shr.msgHideAll();
- shr.stopAllMask();
- if ($.isEmptyObject(options.message)) {
- return;
- }
- options = $.extend({
- type: 'warning',
- hideAfter: null,
- showCloseButton: true
- }, options);
- if($.isFunction(_top.Messenger)) {
- _top.Messenger().post(options);
- }else{
- Messenger().post(options);
- }
- },
- // 增加一个有遮罩的提示,用来处理当浏览器缩放和窗口变小时 使用。
- showMaskWarning: function(options) {
- shr.msgHideAll();
- shr.stopMask();
- shr.stopAllMask();
- if ($.isEmptyObject(options.message)) {
- return;
- }
- var actionsObj = {};
- actionsObj[$.shrI18n.common.buttonName.noMoreReminders] = {
- action: function() {
- $.stopAllMask();
- shr.msgHideAll();
- localStorage.setItem(shr.getUserInfo().id + '#ScreenZoom', $.toJSON({'noMoreReminders': 1}));
- $(top.window).off('resize', throttle(addWindowResize, 500));
- }
- }
- actionsObj[$.shrI18n.common.buttonName.close] = {
- action: function() {
- $.stopAllMask();
- shr.msgHideAll();
- }
- }
-
- options = $.extend({
- type: 'warning',
- hideAfter: null,
- showCloseButton: false,
- actions: actionsObj
- }, options);
- _top.Messenger().post(options);
- shr.startMask();
- },
- // 添加args支持确认的时候的参数传递 格式如[a, b, c] 数组形式
- showConfirm: function(message, action, cancel, args) {
- shr.msgHideAll();
- shr.startMask();
- $('#shr-mask').css({'z-index':1050});
- var messageFun;
- if($.isFunction(_top.Messenger)){
- messageFun = _top.Messenger();
- }else{
- messageFun = Messenger();
- }
- var msg = messageFun.post({
- message: message,
- hideAfter: null,
- showCloseButton: true,
- close: function(){
- shr.stopMask();
- },
- actions: {
- retry: {
- label: $.shrI18n.common.title.confirm,
- auto: false,
- delay: 0,
- showCloseButton: true,
- action: function() {
- shr.msgHideAll();
- shr.stopMask();
- if (action && $.isFunction(action)) {
- if(args){
- action.apply(this,args);
- }else{
- action.apply(this);
- }
- }
- }
- },
- cancel: {
- label: $.shrI18n.common.title.close,
- action: function() {
- shr.msgHideAll();
- shr.stopMask();
- if (cancel && $.isFunction(cancel)) {
- if(args){
- cancel.apply(this,args);
- }else{
- cancel.apply(this);
- }
- } else {
- return msg.cancel();
- }
- }
- }
- }
- });
- return msg;
- },
-
- msgHideAll: function(){
- var topElem = getTop();
- if(topElem && typeof(topElem.Messenger) != 'undefined'){
- topElem.Messenger().hideAll();
- }
-
- },
-
- /**
- * 描述:判断当前传递的json对象是否为枚举类型
- */
- isEnumValue:function(json){
- if(!json || json == null) return false;
- if(json.isenum!==undefined && json.alias!==undefined && json.value!==undefined){
- return true;
- }
- return false;
- },
-
- hideErrorMsg: function() {
- var historyMsg = _top.Messenger().history;
- if (historyMsg) {
- var msg;
- for (var i = 0, length = historyMsg.length; i < length; i++) {
- msg = historyMsg[i].msg;
- if (msg.shown && msg.options.type != 'info') {
- shr.msgHideAll();
- return;
- }
- }
- }
- },
-
- blockModal: function(hasBg){
- var opts = {
- lines: 10, // The number of lines to draw
- length: 10, // The length of each line
- width: 5, // The line thickness
- radius: 10, // The radius of the inner circle
- corners: 1, // Corner roundness (0..1)
- rotate: 0, // The rotation offset
- direction: 1, // 1: clockwise, -1: counterclockwise
- color: '#000', // #rgb or #rrggbb
- speed: 1.4, // Rounds per second
- trail: 100, // Afterglow percentage
- shadow: false, // Whether to render a shadow
- hwaccel: false, // Whether to use hardware acceleration
- className: 'spinner', // The CSS class to assign to the spinner
- zIndex: 2e9, // The z-index (defaults to 2000000000)
- top: 'auto', // Top position relative to parent in px
- left: 'auto' // Left position relative to parent in px
- };
-
- var modal = _top.$.scojs_modal({
- width: 0,
- height: 0,
- top: -1000
- });
- if(!hasBg){
- modal.show();
- }
- var target = _top.document.getElementById('wrap');
- var spinner = new Spinner(opts).spin(target);
-
- var blockModal = {"modal": modal, "spinner": spinner};
- return blockModal;
- },
-
- destroyBlockModal: function(blockModal){
- blockModal.modal.destroy();
- blockModal.spinner.stop();
- },
-
- /**
- * 获得页面对应的短网址
- */
- getShortUrl: function() {
- var doc;
- if ($('#workArea').length > 0) {
- doc = $('#workArea')[0].contentDocument;
- } else {
- doc = document;
- }
- var realUrl = this.getPageUrl(document);
-
- var response = shr.callService({
- serviceName: 'url2short',
- type: 'POST',
- param: {
- url: realUrl
- }
- });
- if (response) {
- var breadcrumb = shrDataManager.pageNavigationStore.getDatas();
- var names = [];
- for (var i = 0, length = breadcrumb.length; i < length; i++) {
- if (i != 0) {
- names.push(' / ');
- }
- names.push(breadcrumb[i].name);
- }
- if (names.length == 0) {
- names.push(doc.title);
- }
- return {
- shortUrl: response.short,
- desc: names.join('')
- }
- }
- },
-
- /**
- * 根据短网址显示页面
- */
- renderPage: function(short) {
- var response = shr.callService({
- serviceName: 'short2url',
- type: 'POST',
- param: {
- id: short
- }
- });
- if (response && response.url) {
- var url = shr.getContextPath() + response.url;
- if ($('#workArea').length > 0) {
- $('#workArea')[0].contentDocument.location.replace(url);
- } else {
- document.location.href = url;
- }
- }
- },
-
- getPageUrl: function(document) {
- if (typeof document == 'undefined') {
- document = window.document;
- }
- var url = document.location.href;
- var contextPath = shr.getContextPath();
- return url.substr(url.indexOf(contextPath) + contextPath.length);
- },
-
- loadScript: function(url, callback) {
- if (callback) {
- return $LAB.script(url).wait(callback);
- } else {
- return $LAB.script(url);
- }
- },
-
- loadCss: function(url){
- var link = document.createElement('link');
- link.type = 'text/css';
- link.rel = 'stylesheet';
- link.href = url;
- document.getElementsByTagName('head')[0].appendChild(link);
- },
-
- //默认设置workArea高度, 如需设置其他高度, 则传入iframe的id
- setIframeHeight: function(iframeId) {
- var _self = this;
- if (typeof iframeId == 'undefined') {
- iframeId = shr.getUrlRequestParam('iframe');
- }
-
- if(iframeId && iframeId != null){
- id = iframeId;
- } else {
- id = 'workArea';
- }
- var _iframe = $('#'+id)[0];
- if(!_iframe){ //在iframe中调用时需要通过父页面获取iframe标签
- _iframe = $('#'+id, parent.document)[0];
- }
- setTimeout(function() {
- if (_iframe){
- if ($(_iframe).attr('autoHeight') == 'false') {
- return;
- }
-
- var _iframeHeight = null;
- if (_iframe.contentDocument && _iframe.contentDocument.body.offsetHeight){
- _iframeHeight = _iframe.contentDocument.body.offsetHeight;
- } else if (_iframe.Document && _iframe.Document.body.scrollHeight){
- _iframeHeight = _iframe.Document.body.scrollHeight;
- }
- if(id === 'workArea'){
- var excludeIframeHeight = _self.getWorkareaVisibleHeight();
- if(_iframeHeight <= excludeIframeHeight){
- _iframe.height = excludeIframeHeight;
- }else{
- _iframe.height = _iframeHeight;
- }
- } else {
- //_iframe.height = _iframeHeight + 60;
- //_iframe.height = _iframeHeight;
-
- var $iframe = $(_iframe);
- $iframe.height(_iframeHeight + 20 );
-
- var printMode = shr.getUrlRequestParam('printMode');
- if (!printMode == 'true') {
- var _iframeWidth = $iframe.parent().width();
- $iframe.width(_iframeWidth);
- }
- }
-
- // 如果当前window不是最顶部window,则递归调用setIframeHeight设置高度
- if (!$.isWindow(parent)) {
- if( parent.shr ){ // 解决父窗口不是s-HR页面登录的时候报错问题
- parent.shr.setIframeHeight();
- }
- }
- }
- }, 100)
-
-
- shr.setFixedBlockPosition();
- },
- getWorkareaVisibleHeight: function() {
- var topWindow = $(_top.window);
- var visibleHeight = topWindow.height();
- var container = $('#home-container', topWindow[0].document);
-
- //row-fluid的外边距为10
- var container_margin = container.outerHeight(true) - container.outerHeight(),
- row_margin_top = 0,
- offset = 10;
- var margin = container_margin + row_margin_top + offset;
- return visibleHeight - margin;
- },
-
- getWorkarea: function() {
- //判断当前界面是否是导航界面,如果是导航界面则去当前的界面进行渲染,不能取外层
- if($('.wz_navi_new', _top.document).length > 0) {
- return $('#workAreaDiv');
- }else{
- return $('#workAreaDiv', _top.document);
- }
- },
-
- /**
- * 构造动态URL
- * @param value 需要打开的视图UIPK或是URL地址
- * @param type URL类型,可传入的值:view,url。
- * @param params 打开页面时需传递的参数
- */
- assembleURL: function(value, type, params) {
- if (!value || !type) {
- return;
- }
- if(value.indexOf("http") === 0 || value.indexOf("/easweb") === 0){
- return value;
- }
- var url, options;
- if (type.toLowerCase() == 'view') {
- // 视图
- url = shr.dynamicURL;
- options = { uipk: value };
- } else if (type.toLowerCase() == 'handler') {
- // handler
- url = shr.dynamicURL;
- options = { handler: value };
- } else {
- // url
- url = value;
- options = {};
- }
-
- url = shr.getContextPath() + url;
-
- if (params) {
- $.extend(options, params);
- }
- url = this.appendParam(url, options);
-
- return url;
- },
-
- appendParam: function(url, param) {
- // append param
- if (!$.isEmptyObject(param)) {
- if (url.indexOf('?') == -1) {
- url += '?';
- } else {
- url += '&';
- }
- url += $.param(param);
- }
- return url;
- },
-
- removeParam: function(url, param) {
- // remove param
- if ($.isEmptyObject(param)) {
- return url;
- }
-
- var start = url.indexOf(param + '=');
- if (start == -1) {
- return url;
- }
-
- var end = url.indexOf('&', start + 1);
- if (end == -1) {
- end = url.length;
- }
- var c = url.charAt(start - 1);
- if (c == '&') {
- start = start - 1;
- } else if (c == '?' && url.charAt(end) == '&') {
- end = end + 1;
- }
-
- return url.substring(0, start) + url.substring(end);
- },
-
- assembleViewUrl: function(uipk, params) {
- return shr.assembleURL(uipk, 'view', params);
- },
-
- assembleHandlerUrl: function(handler, action, params) {
- if (params == 'undefined' || !params) {
- params = {};
- }
- params.method = action;
- return shr.assembleURL(handler, 'handler', params);
- },
-
- /**
- * 加载页面
- * @param value 需要打开的视图UIPK或是URL地址
- * @param type URL类型,可传入的值:view,url。
- * @param params 打开页面时需传递的参数
- */
- loadPage: function(value, type, params) {
- var url = this.assembleURL(value, type, params);
- if (url) {
- this.urlLocate(url);
- }
- },
-
- /**
- * 是否是主工作区iframe
- */
- isWorkareaFrame: function() {
- var inFrame = shr.getUrlRequestParam('inFrame');
- if (inFrame && inFrame.indexOf('true') > -1) {
- return true;
- }
-
- var iframeName = shr.getUrlRequestParam('iframe');
- if (iframeName) {
- value = iframeName == 'workArea';
- } else {
- value = $('#workArea', parent.document).length > 0;
- }
- return value;
- },
-
- /**
- *菜单操作日志
- */
- operateLogger: function(value) {},
-
- base64Encode: function(input) {
- var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- var output = "";
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
- input = shr.utf8Encode(input);
- while (i < input.length) {
- chr1 = input.charCodeAt(i++);
- chr2 = input.charCodeAt(i++);
- chr3 = input.charCodeAt(i++);
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- } else if (isNaN(chr3)) {
- enc4 = 64;
- }
- output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
- }
- return output;
- },
- base64Decode:function(input){
- var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- var output = "";
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- while (i < input.length) {
- enc1 = _keyStr.indexOf(input.charAt(i++));
- enc2 = _keyStr.indexOf(input.charAt(i++));
- enc3 = _keyStr.indexOf(input.charAt(i++));
- enc4 = _keyStr.indexOf(input.charAt(i++));
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
- output = output + String.fromCharCode(chr1);
- if (enc3 != 64) {
- output = output + String.fromCharCode(chr2);
- }
- if (enc4 != 64) {
- output = output + String.fromCharCode(chr3);
- }
- }
- output = shr.utf8Encode(output);
- return output;
- },
- /**
- * encryptObj:{key: value, key: value} key:需要加密的字段; value: 需要加密的值;
- * url: 必填,会将参数最终拼接在url上
- * 加密 for url
- */
- encryptForUrl: function(encryptObj, url) {
- var aKeys = Object.keys(encryptObj),
- keyStr = aKeys.join(',');;
- url = $.appendParam(url, {'encryptKeys': keyStr});
- for(var n = 0; n < aKeys.length; n++) {
- var key = aKeys[n];
- var value = encryptObj[key];
- var encode = $.allEncrypt(value);
- url += '&'+key+'='+encode;
- }
- return url
- },
- /**
- * encryptObj:{key: value, key: value} key:需要加密的字段; value: 需要加密的值;
- * url: 选填,需要在url上添加时则传,否则不传
- * 加密 for obj
- */
- encryptForObj: function(encryptObj, url) {
- var aKeys = Object.keys(encryptObj),
- obj = {},
- keyStr = aKeys.join(',');
- for(var n = 0; n < aKeys.length; n++) {
- var key = aKeys[n];
- var value = encryptObj[key];
- var encode = $.allEncrypt(value);
- obj[key] = encode;
- }
- url ? url = $.appendParam(url, {'encryptKeys': keyStr}) : null;
- return {
- obj: obj,
- keyStr: keyStr,
- url: url
- }
- },
- /**
- * 盐+base64加密
- */
- encryptForB64: function(value) {
- if ($.isUndef(value)) {
- return value;
- }
- var encode = $.base64Encode(value,"utf-8");
- return '_SHRREQPARA_'+encode;
- },
- /**
- * 盐+base64解密
- */
- decryptForB64: function(value) {
- if ($.isUndef(value)) {
- return value;
- }
- value= value.replace('_SHRREQPARA_','');
- var decode = $.base64Decode(value,"utf-8");
- return decode;
- },
-
- /**
- * 盐+base64加密
- */
- encryptForB64PreFix: function(value,preFix) {
- if ($.isUndef(value)) {
- return value;
- }
- var encode = $.base64Encode(value,"utf-8");
- return preFix + encode;
- },
- /**
- * 盐+base64解密
- */
- decryptForB64PreFix: function(value,preFix) {
- if ($.isUndef(value)) {
- return value;
- }
- value= value.replace(preFix,'');
- var decode = $.base64Decode(value,"utf-8");
- return decode;
- },
-
- /**
- * AES加密
- */
- encryptForAes: function(content, secretKey) {
- if ($.isUndef(content)) {
- return content;
- }
-
- var secretKey = secretKey || "g5AJVI7fQGWZKrdZ";
- var key = CryptoJS.enc.Utf8.parse(secretKey);
- var iv = shr.randomRange(16);
- var srcs = CryptoJS.enc.Utf8.parse(content);
- var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv:CryptoJS.enc.Utf8.parse(iv), mode:CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
- return iv + encrypted.toString();
- },
-
- /**
- * AES解密
- */
- decryptForAes: function(content, secretKey) {
- if ($.isUndef(content)) {
- return content;
- }
-
- var secretKey = secretKey || "g5AJVI7fQGWZKrdZ";
- var key = CryptoJS.enc.Utf8.parse(secretKey);
- var iv = content.slice(0, 16);
- var realContent = content.slice(16, content.length);
- var decrypted = CryptoJS.AES.decrypt(realContent, key, { iv:CryptoJS.enc.Utf8.parse(iv), mode:CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
- return decrypted.toString(CryptoJS.enc.Utf8);
- },
- /**
- * AES-CBC加密
- */
- encryptForAes_CBC: function(content, secretKey) {
- if ($.isUndef(content)) {
- return content;
- }
-
- var secretKey = secretKey || "g5AJVI7fQGWZKrdZ";
- var key = CryptoJS.enc.Utf8.parse(secretKey);
- var iv = shr.randomRange(16);
- var srcs = CryptoJS.enc.Utf8.parse(content);
- var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv:CryptoJS.enc.Utf8.parse(iv), mode:CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
- return iv + encrypted.toString();
- },
-
- /**
- * AES-CBC解密
- */
- decryptForAes_CBC: function(content, secretKey) {
- if ($.isUndef(content)) {
- return content;
- }
-
- var secretKey = secretKey || "g5AJVI7fQGWZKrdZ";
- var key = CryptoJS.enc.Utf8.parse(secretKey);
- var iv = content.slice(0, 16);
- var realContent = content.slice(16, content.length);
- var decrypted = CryptoJS.AES.decrypt(realContent, key, { iv:CryptoJS.enc.Utf8.parse(iv), mode:CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
- return decrypted.toString(CryptoJS.enc.Utf8);
- },
- /**
- * 总加密方法,根据window.shrUrlParamEncryptRule的取值去分发 'BASE64' / 'AES', 后续如果要添加新加密方法在这里加即可。
- */
- allEncrypt: function(value) {
- var encryptWay = window.shrUrlParamEncryptRule || 'BASE64'; // 加密方式 根据后端传回
- value = $.isUndef(value) ? value : encodeURIComponent(value);
- var encryptMethod = {
- 'BASE64': $.encryptForB64,
- 'AES': $.encryptForAes_CBC
- }
- return encryptMethod[encryptWay](value)
- },
- /**
- * 总解密方法,根据window.shrUrlParamEncryptRule的取值去分发 'BASE64' / 'AES', 后续如果要添加新解密方法在这里加即可。
- * @param value
- * @returns
- */
- allDecrypt:function(value){
- try {
- var encryptWay = window.shrUrlParamEncryptRule || 'BASE64'; // 解密方式 根据后端传回
- if($.isUndef(value)){
- return value;
- }
- var decryptMethod = {
- 'BASE64': $.decryptForB64,
- 'AES': $.decryptForAes_CBC
- };
- return decodeURIComponent(decryptMethod[encryptWay](value));
- } catch (error) {
- console.log(error);
- return value;
- }
- },
- utf8Encode: function(string){
- if(!string){
- string = '';
- }
- string = string.replace(/\r\n/g,"\n");
- var utftext = "";
- for (var n = 0; n < string.length; n++) {
- var c = string.charCodeAt(n);
- if (c < 128) {
- utftext += String.fromCharCode(c);
- } else if((c > 127) && (c < 2048)) {
- utftext += String.fromCharCode((c >> 6) | 192);
- utftext += String.fromCharCode((c & 63) | 128);
- } else {
- utftext += String.fromCharCode((c >> 12) | 224);
- utftext += String.fromCharCode(((c >> 6) & 63) | 128);
- utftext += String.fromCharCode((c & 63) | 128);
- }
-
- }
- return utftext;
- },
- /**
- * 是否是向导iframe
- */
- isWizardFrame: function() {
- return $('#_wz_iframe', parent.document).length > 0;
- },
- /**
- * 是否是新向导iframe
- */
- isNewWizardFrame: function() {
- return $('.wz_navi_new ', parent.document).length > 0;
- },
-
- /**
- * 定位至某个区域块
- */
- locateTo: function(newElement, complete, duration) {
- var offsetTop;
- if ($.isNumeric(newElement)) {
- offsetTop = newElement;
- } else {
- offsetTop= $(newElement).offset().top;
- }
-
- var doc;
- if (parent == window) {
- doc = document;
- } else if (parent == _top){
- // in iframe
- doc = parent.document;
- // get parent offset
- var iframeId = shr.getUrlRequestParam('iframe') || 'iframe';
- var iframe_top = $('#' + iframeId, doc).offset() ? $('#' + iframeId, doc).offset().top : 0;
- offsetTop += iframe_top;
- }
- // add header offset
- var workarea = this.getWorkarea();
- if (workarea.length > 0) {
- //offsetTop -= workarea.offset().top;
- offsetTop = offsetTop - (workarea.offset().top + 160);
- }
-
- var isIE = false;
- if( "ActiveXObject" in window ){
- isIE = true;
- }
-
- if ( isIE) {
- doc.documentElement.scrollTop = offsetTop;
- if (complete) {
- complete.call(this);
- }
- } else {
- if (typeof duration == 'undefined') {
- duration = 500;
- }
-
- $('body,html', doc).animate({scrollTop: offsetTop}, duration, function() {
- if (complete) {
- complete.call(this);
- }
- });
- }
- },
-
- closeWindow: function() {
- window.open('','_self');
- window.opener = null;
- window.close();
- },
-
- /**
- * 加载HTML片断
- */
- loadHTML: function(options) {
- $.extend(options, {
- dataType: 'html'
- });
- var success = options.success;
- options.success = function(response) {
- try{
- var result = JSON.parse(response);
- if(result && result.result === 'error'){
- shr.showError({message: result.summary});
- return;
- }
- }catch(e){
-
- }
- //var urlParams = shr.getUrlParams();
- var repData = shr.callService({
- serviceName:'getBizMultLanService',
- param:{uipk:shr.getUrlRequestParam('uipk',options.url)},
- type: 'POST',
- async: false,
- ignoreDataPerm: true,
- });
- window.contextLanguage = repData['contextLanguage'];
- $.extend(window.jsBizMultLan, repData['jsBizMultLan']);
- $.extend(window.utcData, repData['utcData']);
- $.extend(window.numberFormat, repData['numberFormat']);
- $.extend(window.languageMappingList, repData['languageMappingList']);
- $.extend(window.isTCtoTWopen, repData['isTCtoTWopen']);
- if (shr.checkIsRedirectLogin(response)) {
- window.location.href = shr.getContextPath();
- return;
- }
-
- var $content = $(response);
- var item;
- var scripts = [];
- // 解析script标签,为手动加载script文件
- for (var i = $content.length - 1; i >= 0; i--) {
- item = $content[i];
- if (item.tagName == 'SCRIPT' && item.getAttribute('src')) {
- scripts.push(item.getAttribute('src'));
- $content.splice(i, 1);
- }
- }
- if (scripts.length > 0) {
- scripts = scripts.reverse();
- // 手动加载script文件,为解决不能调试的问题
- shr.loadScript(scripts, function() {
- if (success && $.isFunction(success)) {
- success.call(this, $content);
- }
- });
- } else {
- if (success && $.isFunction(success)) {
- success.call(this, $content);
- }
- }
- }
- shr.doGet(options);
- },
-
- setFixedBlockPosition: function() {
- var bodywidth = $(window.top.document.body).width();
- var iframewidth = $(window.top.document.body).find("#home-container").width();
- if((bodywidth-iframewidth) < 20){
- /*$(window._top.document.body).find("#adviseUp").css("right", 0);*/
- $(window._top.document.body).find("#scrollUp").css("right", 0);
- }else{
- /*$(window._top.document.body).find("#adviseUp").css("left", iframewidth+(bodywidth-iframewidth)/2);*/
- $(window._top.document.body).find("#scrollUp").css("left", iframewidth+(bodywidth-iframewidth)/2);
- }
- //根据窗口大小动态
- $(window).resize(function(){
- var bodywidth = $(window.top.document.body).width();
- var iframewidth = $(window.top.document.body).find("#home-container").width();
- if((bodywidth-iframewidth) < 20){
- /*$(window._top.document.body).find("#adviseUp").css("right", 0);*/
- $(window.top.document.body).find("#scrollUp").css("right", 0);
- }else{
- /*$(window._top.document.body).find("#adviseUp").css("left", iframewidth+(bodywidth-iframewidth)/2);*/
- $(window.top.document.body).find("#scrollUp").css("left", iframewidth+(bodywidth-iframewidth)/2);
- }
- });
-
-
- },
-
- /**
- * 获得当前登录用户信息
- */
- getUserInfo: function() {
- var context = _top.document;
- return {
- id: $('#userId', context).val(),
- number: $('#userNumber', context).val()
- }
- },
-
- /**
- * 获得页面信息
- */
- getPageInfo: function() {
- var getPageCode = function(url) {
- var uipk = shr.getUrlRequestParam('uipk', url);
- if (uipk) {
- return uipk;
- }
-
- var contextPath = shr.getContextPath();
- var firstIndex = url.indexOf(contextPath) + contextPath.length;
- var lastIndex = url.indexOf('?')
- if (lastIndex == -1) {
- lastIndex = url.length;
- }
- return url.substring(firstIndex, lastIndex);
- };
-
- var doc;
- if ($('#workArea').length > 0) {
- doc = $('#workArea')[0].contentDocument;
- } else {
- doc = document;
- }
-
- var serviceId = shr.getServiceId();
-
- var param;
- if (serviceId) {
- param = {
- category_code: serviceId,
- page_code: getPageCode(doc.location.href),
- page_desc: $('title', doc).data('value')
- };
-
- var service = shr.createObject(shr.base.ServiceData).getServiceById(serviceId);
- var category;
- if (service && service.category && service.category.length > 0) {
- category = service.category[0];
- } else {
- category = '';
- }
- param.category_desc = category;
- } else {
- var title;
- if (doc.location.href.indexOf('/home.do') >= 0) {
- title = $.shrI18n.base.title.homePage;
- } else {
- title = $('title', doc).data('value')
- }
- param = {
- page_code: getPageCode(doc.location.href),
- page_desc: title
- };
- }
-
- return param;
- },
-
- /**
- * js设置placeholder,解决IE9下显示不了的问题
- */
- funPlaceholder: function(element) {
- var placeholder = '';
- if (element && !("placeholder" in document.createElement("input")) && (placeholder = element.getAttribute("placeholder"))) {
- element.onfocus = function() {
- if (this.value === placeholder) {
- this.value = "";
- }
- this.style.color = '';
- };
- element.onblur = function() {
- if (this.value === "") {
- this.value = placeholder;
- }
- };
-
- //样式初始化
- if (element.value === "") {
- element.value = placeholder;
- }
- }
- },
-
- /**
- * 选择器中包含“.”导致JQuery选择器不可用,转义处理
- */
- selectorFormat : function (selectorStr){
- return selectorStr.replace(/(:|\.|\[|\])/g, '\\$1');
- },
-
- /**
- * 本窗口采用post方式加载某个URL,解决URL超长问题
- */
- reloadUrlByPost: function(url, param, name) {
- if (!name) {
- name = (new Date()).getTime();
- }
- name = 'urlpost_' + name;
- var form = $('#' + name);
-
- if (form.length > 0) {
- form.remove();
- }
-
- var str = ['<form id="${name}" action="" method="post" target="${name}-frame"></form>',
- '<iframe id="${name}-frame" name="${name}-frame" src="" style="display: none;"></iframe>'].join('');
- $(juicer(str, {name: name})).appendTo('body');
- form = $('#' + name);
-
- // 将相应的参数值填充至form中
- var option = {
- url: url,
- data: param
- }
- shr.dealPostParam(option);
- var content = this.paramToInputHidden(option.data);
- form.attr('action', option.url).append(content).submit();
- },
-
- /**
- * 采用post方式打开新窗口,解决URL超长问题
- */
- openWindowByPost: function(url, param) {
- $('#openwindow-form').remove();
-
- window.open('', 'openwindow-frame');
-
- var content = this.paramToInputHidden(param);
- var str = '<form id="openwindow-form" action="" method="post" target="openwindow-frame"></form>';
- $(str).attr('action', url).append(content).appendTo('body').submit();
- },
-
- /**
- * 将参数转换为input hidden字符串
- */
- paramToInputHidden: function(param) {
- var content = '', tpl = '<input type="hidden" name="${name}" value="${value}" />';
- for (var key in param) {
- content += juicer(tpl, {
- name: key,
- value: param[key]
- });
- }
- return content;
- },
- /*
- *检测 FlashPlayer
- * */
- getFlashVersion : function () {
- var flashVer = NaN;
- var ua = navigator.userAgent;
-
- if (window.ActiveXObject) {
- var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
-
- if (swf) {
- flashVer = Number(swf.GetVariable('$version').split(' ')[1].replace(/\,/g, '.').replace(/^(\d+\.\d+).*$/, "$1"));
- }
- } else {
- if (navigator.plugins && navigator.plugins.length > 0) {
- var swf = navigator.plugins['Shockwave Flash'];
- if (swf) {
- var arr = swf.description.split(' ');
- for (var i = 0, len = arr.length; i < len; i++) {
- var ver = Number(arr[i]);
-
- if (!isNaN(ver)) {
- flashVer = ver;
- break;
- }
- }
- }
- }
- }
- return flashVer;
- },
-
- /*
- *检测 是否可以上传文件
- * */
- checkCanUpload :function(){
- var _self = this;
- var flashVer = shr.getFlashVersion();
- if (!isNaN(flashVer)) {
- ua = navigator.userAgent;
- ua = ua.toLocaleLowerCase();
- if (ua.match(/msie/) != null || ua.match(/trident/) != null) {
- var browserType = "IE";
- var browserVersion = ua.match(/msie ([\d.]+)/) != null ? ua.match(/msie ([\d.]+)/)[1] : ua.match(/rv:([\d.]+)/)[1];
- }
- if(browserVersion == "11.0" && flashVer <12){
- shr.showError({
- message: $.shrI18n.framework.tips.flashVersionRequirePrefix + flashVer +$.shrI18n.framework.tips.flashVersionRequireSuffix
- });
- return false;
- }
- return true;
- } else {
- shr.showError({
- message: $.shrI18n.framework.tips.noInstallFlashSimple
- });
- return false
- }
- return true;
- },
-
- imCloudInstance: void(0),
- // 真正初始化云之家消息组件
- initImCloudRun: function (response) {
- // if (!this.imCloudInstance) {
- // this.imCloudInstance = new imCloud({ //组件初始化
- // eid: response.eid, //填写企业id号
- // data: response.data //填写上面步骤生成的加密字段
- // });
- // }
- // 点击非控件区域,控件可关闭
- $("iframe").on("load", function(event){//判断 iframe是否加载完成 这一步很重要
- $("body",this.contentDocument).click(function(e){//添加点击事件
- if($(e.target).closest('.im-wrap').length < 1 && !$('#im-session-left').is(':hidden')){
- if(!$('#im-session-left').is(':hidden') && !$(e.target).hasClass('ot-del-person')){
- $('.im-tray').click();
- }
- }
- });
- });
- $(document).click(function(e){
- if($(e.target).closest('.im-wrap').length < 1 && !$('#im-session-left').is(':hidden') && document.body.contains(e.target)){
- if(!$('#im-session-left').is(':hidden') && !$(e.target).hasClass('ot-del-person')){
- if($('.im-tray', window.parent.document).length > 0){
- $('.im-tray', window.parent.document).click();
- }else{
- $('.im-tray').click();
- }
- }
- }
- })
- return this.imCloudInstance;
- },
- // 初始化云之家消息组件
- initImCloud: function (response) {
- var _self = this;
- if (_top.imCloud) {
- if (!this.imCloudInstance) {
- this.imCloudInstance = _top.imCloud;
- }
- _self.initImCloudRun(response);
- } else {
- try {
- shr.loadScript('https://www.yunzhijia.com/imsdk/imcloud/js/imcloud.js', function () {
- if (!this.imCloudInstance) {
- this.imCloudInstance = new imCloud({ //组件初始化
- eid: response.eid, //填写企业id号
- data: response.data //填写上面步骤生成的加密字段
- });
- }
- _self.initImCloudRun(response);
- });
- } catch (error) {
- }
- }
- },
- /**
- * https://www.yunzhijia.com/imsdk/imcloud/js/imcloud.js
- * 云之家消息组件集成
- */
- getIMCloudHubComponent: function(){
- var _self = this;
- shr.callService({
- serviceName: 'getCloudHubParams',
- async: true,
- type: 'POST',
- param: {},
- success: function (response) {
- if(!response.isShowCloudHub){
- $('#loginCloudHub').hide();
- $('.feedback-box').height(60);
- $('.feedback-box .feedback-box-left i').css('marginTop','24px');
- }
- if(response.eid && response.data){
- _self.initImCloud(response);
- }
- }
- });
- },
-
- /**
- * 导入
- */
- doImportData: function(curIOModelString, customData,classify,serviceId,permItemId,gridId) {
- var self = shr.getCurrentViewPage();
- if (typeof curIOModelString == 'undefined') {
- curIOModelString = self.getImportModel();
- }
-
- var importDiv = $('#importDiv');
- if (importDiv.length > 0) {
- importDiv.data('curIOModelString', curIOModelString);
- importDiv.data('customData', customData);
- importDiv.data('classify', classify);
- importDiv.dialog('open');
- return;
- }
-
- // 未生成dialog
- importDiv = $('<div id="importDiv"></div>').appendTo($('body'));
- importDiv.data('curIOModelString', curIOModelString);
- importDiv.data('customData', customData);
- importDiv.data('classify', classify);
- importDiv.data('serviceId', serviceId);
- importDiv.data('permItemId', permItemId);
-
- var _self = this;
- // if(shr.checkCanUpload()){
- importDiv.dialog({
- autoOpen: true,
- width: 708,
- height: 700,
- title: $.shrI18n.framework.title.importData,
- resizable: true,
- position: ['top','top'],
- modal: true,
- open: function(event, ui) {
- if ($.browser.msie) {
- var url = shr.assembleURL('com.kingdee.shr.io.app.ImportInfo', 'view', {
- curIOModelString: curIOModelString,
- customData: customData,
- classify:classify,
- serviceId:serviceId,
- permItemId:permItemId
- });
- var content = '<iframe id="importFrame" name="importFrame" width="700" height="600" frameborder="0" scrolling="no" allowtransparency="true" src="' + url + '"></iframe>';
- importDiv.append(content);
- } else {
- importDiv.css('padding', "0 20px");
- var url = shr.assembleURL('com.kingdee.shr.io.app.ImportInfo$page', 'view');
- shr.loadHTML({
- url: url,
- success: function(response) {
- importDiv.append(response);
- }
- });
- }
- },
- close: function(event, ui) {
- importDiv.empty();
- $(gridId).jqGrid("reloadGrid");
- }
- });
- // }
-
- $(".ui-dialog-titlebar-close").bind("click" , function(){
- importDiv.dialog("close");
- });
- },
-
- /**
- * 组装 按钮数据权限 模型
- */
- getButtonDataPermissionModel:function(){
- var model = [];
- try {
- if( jsBinder && jsBinder.assembleDataPermModel instanceof Function){
- if( jsBinder.initData && jsBinder.initData.checkModel == "client" ){
- model = jsBinder.assembleDataPermModel();
- }
- }
- } catch (error) {// jsBinder 还没有生成,会异常,这里直接catch住,不处理
- //console.warn("[ getButtonDataPermissionModel error ]");
- }
- return model;
- },
-
- addDataPermissionModel:function( data ){
- if(data){
- var dataPerm = this.getButtonDataPermissionModel();
- if( dataPerm && dataPerm.length ){
- data.dataPerm = shr.toJSON(dataPerm);
- }
- }
- return data;
- },
-
- // 添加公共扩展参数
- _addCommonExtParam:function( option ){
- var data = option.data,ignoreDataPerm = false;
- ignoreDataPerm = option.ignoreDataPerm;
- // 添加按钮 数据 权限数据,如果忽略添加数据权限,不构造数据
- if( !ignoreDataPerm ){
- this.addDataPermissionModel( data );
- // 客户端按钮数据权限,修改请求提交方式为POST,解决GET请求URL超长问题
- option.type = 'POST';
- }
- if( data ){
- var assigmentId = data['assigmentId'] || this.getAssignmentId();
- data.assigmentId = assigmentId || "";
- var ProcInstId = data['ProcInstId'] || this.getProcInstId();
- data.ProcInstId = ProcInstId || "";
- var msgId = data['msgId'] || this.getMsgId();
- data.msgId = msgId || "";
- }
- // 添加权限项ID
- this._addPermItemId( data );
- //添加shruicode
- this._addShruicode( data );
- //添加uipk
- this._addUipk(data);
- //添加billId 工作流单据的所有单独请求都需要传入uipk,billId才能正确跳过数据验权
- this._addBillId(data);
- //添加附件fileUUID
- this._addAttachmentFileUUID(data);
- },
- getProcInstId:function(){
- var procInstId = shr.getUrlRequestParam('ProcInstId');
- if(procInstId){
- return procInstId;
- }
- procInstId = shr.getUrlRequestParam('proInstId');
- if(procInstId){
- return procInstId;
- }
- return '';
- },
- getMsgId:function(){
- var msgId = shr.getUrlRequestParam('msgId');
- if(msgId){
- return msgId;
- }
- return '';
- },
- _addUipk:function(data){
- if( data ){
- var uipk = data['uipk'] || this.getUipk();
- data.uipk = uipk || "";
- }
- },
- getUipk:function(){
- return shr.getUrlRequestParam('uipk');
- },
-
- _addShruicode:function(data){
- if( data ){
- var shruicode = data['shruicode'] || this.getShruicode();
- data.shruicode = shruicode || "";
- }
- },
- getShruicode:function(){
- return shr.getUrlRequestParam('shruicode');
- },
- _addBillId:function(data){
- if( data ){
- var billId = data['billId'] || this.getBillId();
- data.billId = billId || "";
- }
- },
- getBillId:function(){
- var billId = shr.getUrlRequestParam('billID');
- if(!billId){
- billId = shr.getUrlRequestParam('billId');
- }
- return billId;
- },
-
- _addPermItemId:function( data ){
- if( data ){
- // 优先获取button上的权限项ID, 如果获取button上的权限项ID为空 ,从url上获取
- var permItemId = data['permItemId'] || this.getButtonPermItemId( data ) || this.getPermItemId();
- data.permItemId = permItemId || "";
- }
- return data;
- },
-
- getButtonPermItemId:function( data ){
- var permItemId = "", method = data.method;
- if( method ){
- try{
- permItemId = $("#"+method).shrButton("getValue")["permItemId"];
- }catch (error) {
- }
- }
- return permItemId;
- },
- getPermItemId:function(_window){
- var _win = _top;
- if (_window) {
- _win = _window;
- }
- return shr.getUrlRequestParam('permItemId', _win.location.href);
- },
-
- getCurrentPagePermItemId:function(){
- var _permItemId = this.getCurrentPagePermItemIdByClient();
- if(!_permItemId){
- _permItemId = this.getCurrentPagePermItemIdByServer();
- }
-
- return _permItemId;
- },
-
- getCurrentPagePermItemIdByClient:function(){
- var _permItemId = "";
- try {
- if( jsBinder && jsBinder.currentPagePermItemId ){
- _permItemId = jsBinder.currentPagePermItemId;
- }
- } catch (error) {
-
- }
-
- return _permItemId;
-
- },
-
- getCurrentPagePermItemIdByServer:function(){
- var _permItemId = "",
- _uipk = shr.getUrlRequestParam("uipk") || "",
- _method = shr.getUrlRequestParam("method") || "",
- _permItemId = shr.getUrlRequestParam("permItemId") || "",
- _serviceId = shr.getUrlRequestParam("serviceId") || "",
- _shruicode = shr.getUrlRequestParam("shruicode") || "",
- //应人事要求,从工作流过来的表单,如果们有method,并且url带有operateState,则将operateState小写作为method
- _isShrBill = shr.getUrlRequestParam("isShrBill") || "";
- if(_isShrBill && _isShrBill == 'true'){
- var _operateState = shr.getUrlRequestParam("operateState");
- if(_operateState && !_method){
- _method = _operateState.toLowerCase();
- }
- }
-
- shr.callService({
- serviceName: 'getCurrentPagePermItemId',
- param: {
- uipk : _uipk,
- methodName :_method,
- permItemId :_permItemId,
- serviceId :_serviceId,
- shruicode:_shruicode
- },
- type: 'POST',
- async: false,
- success: function(data) {
- _permItemId = data;
- }
- });
- return _permItemId;
- },
-
- replaceAll:function( source,target,replacement ){
- var reg = new RegExp(target,"g");
- return source.replace(reg,replacement);
- },
- //获取浏览器缩放比例
- detectZoom: function() {
- var e = 0,
- t = window.screen;
- return (
- void 0 !== window.devicePixelRatio
- ? (e = window.devicePixelRatio)
- : -1 !== navigator.userAgent.toLowerCase().indexOf('msie')
- ? t.deviceXDPI && t.logicalXDPI && (e = t.deviceXDPI / t.logicalXDPI)
- : void 0 !== window.outerWidth && void 0 !== window.innerWidth && (e = window.outerWidth / window.innerWidth),
- e && (e = Math.round(100*e)),
- (99 !== e && 101 !== e) || (e = 100),
- e
- )
- },
- /**
- * 动态加载js、css文件
- */
- loadJsOrCssFile : function(filename, filetype){
- if (filetype == "js"){
- var fileref = document.createElement('script');
- fileref.setAttribute("type","text/javascript");
- fileref.setAttribute("src",filename);
- } else if (filetype == "css"){
- var fileref = document.createElement("link");
- fileref.setAttribute("rel","stylesheet");
- fileref.setAttribute("type","text/css");
- fileref.setAttribute("href",filename);
- }
- if (typeof fileref != "undefined") document.getElementsByTagName("head")[0].appendChild(fileref);
- },
- /**
- * 动态移除js、css文件
- */
- removeJsOrCssFile : function(filename,filetype){
- var targetelement = (filetype == "js")? "script" :(filetype == "css")? "link" : "none";
- var targetattr = (filetype == "js")?"src" : (filetype == "css")? "href" :"none";
- var allsuspects = document.getElementsByTagName(targetelement);
- for (var i = allsuspects.length; i >= 0;i--){
- if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1) allsuspects[i].parentNode.removeChild(allsuspects[i]);
- }
- },
- /**
- * 动态创建js、css文件
- */
- createJsOrCssFile : function (filename,filetype){
- if (filetype=="js"){
- var fileref=document.createElement('script')
- fileref.setAttribute("type","text/javascript")
- fileref.setAttribute("src",filename)
- }
- else if (filetype=="css"){
- var fileref=document.createElement("link")
- fileref.setAttribute("rel","stylesheet")
- fileref.setAttribute("type","text/css")
- fileref.setAttribute("href",filename)
- }
- return fileref
- },
- replaceJsOrCssFile : function (oldfilename,newfilename, filetype){
- var targetelement=(filetype=="js")?"script" : (filetype=="css")? "link" :"none"
- var targetattr=(filetype=="js")?"src" : (filetype=="css")? "href" :"none"
- var allsuspects=document.getElementsByTagName(targetelement)
- for (var i=allsuspects.length; i>=0;i--){
- if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null &&allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
- var newelement=shr.createjscssfile(newfilename, filetype)
- allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
- }
- }
- },
- /**
- * 获取一段字符串中,外部引入的js
- */
- getOutInputScripts: function (str) {
- var html_pool = [];
- var scripts = [];
- var scriptText = '';
- str = str.split(/<\/script>/i);
- for (var i = 0; i < str.length; i++) {
- html_pool[i] = str[i].replace(/<script[\s\S]*$/ig, "");
- scripts[i] = {type: 'text/javascript', src: ''};
- scriptText = str[i].substr(html_pool[i].length);
- scripts[i].src = scriptText.substr(0, scriptText.indexOf('>') + 1);
- scripts[i].src = scripts[i].src.match(/src\s*=\s*(\"([^\"]*)\"|\'([^\']*)\'|([^\s]*)[\s>])/i);
- if(!scripts[i].src) {scripts.splice(i, 1);continue;}
- if (scripts[i].src) {
- if (scripts[i].src[2]) {
- scripts[i].src = scripts[i].src[2];
- }
- else if (scripts[i].src[3]) {
- scripts[i].src = scripts[i].src[3];
- }
- else if (scripts[i].src[4]) {
- scripts[i].src = scripts[i].src[4];
- }
- else {
- scripts[i].src = "";
- }
- }
- }
-
- return scripts;
- },
-
- formatMsg: function (){
- // 数据长度为空,则直接返回
- var result = '';
-
- if (arguments.length == 0){
- return result;
- }
-
- var str = arguments[0] ? arguments[0] : '';
- var valArr = arguments[1] ? arguments[1] : [];
-
- if(typeof str !== 'string' || Object.prototype.toString.call(valArr) !== '[object Array]'){
- return result;
- }
- // 使用正则表达式,循环替换占位符数据
- for (var i = 0; i < valArr.length; i++){
- str = str.replace(new RegExp("\\{\\s*" + i + "\\s*\\}", "g"), valArr[i]);
- }
-
- result = str;
-
- return result;
- },
- escapeSpecChar: function(srcString) {
- // 转义之后的结果
- var escapseResult = srcString;
- // javascript正则表达式中的特殊字符
- var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",
- "]", "|", "{", "}"];
- // jquery中的特殊字符,不是正则表达式中的特殊字符
- var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"",
- ":", ";", "<", ">", ",", "/"];
- for (var i = 0; i < jsSpecialChars.length; i++) {
- escapseResult = escapseResult.replace(new RegExp("\\"
- + jsSpecialChars[i], "g"), "\\"
- + jsSpecialChars[i]);
- }
- for (var i = 0; i < jquerySpecialChars.length; i++) {
- escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
- "g"), "\\" + jquerySpecialChars[i]);
- }
- return escapseResult;
- },
- isUndef: function(v) {
- return v === undefined || v === null || v === "";
- },
- // 判断是否渲染了多页签
- isRenderTabBar:function(){
- return window._isTabBar === 'true' && $('#shrTabBar',top.document).length >0;
- },
- //获取assignmentID,提供公共方法进行调用
- getAssignmentId: function (url) {
- var assignID = shr.getUrlRequestParam("assignmentID", url);
- if(!assignID){
- assignID = shr.getUrlRequestParam("assignmentId", url);
- }
- if(!assignID){
- assignID = shr.getUrlRequestParam("assigmentId", url);
- }
- return assignID;
- },
- isNoPermField: function(noPermFields, field){
- if(null != noPermFields && noPermFields.length > 0){
- for(var i=0;i<noPermFields.length;i++){
- if(noPermFields[i].name == field) {
- return true;
- }
- }
- }
- return false;
- },
- //是否无查看权限字段
- isNoViewPermField: function (field) {
- return this.isNoPermField(noPermFields, field);
- },
- //是否无编辑权限字段
- isNoEditPermField: function (field) {
- return this.isNoPermField(noEditPermFields, field);
- },
- /** 随机生成固定位数或者一定范围内的字符串数字组合
- * @param {Number} min 范围最小值
- * @param {Number} max 范围最大值,当不传递时表示生成指定位数的组合
- * @param {String} charStr指定的字符串中生成组合
- * @returns {String} 返回字符串结果
- * */
- randomRange: function(min, max, charStr){
- var returnStr = "", //返回的字符串
- range; //生成的字符串长度
-
- //随机生成字符
- var autoGetStr = function(){
- var charFun = function(){
- var n= Math.floor(Math.random()*62);
- if(n<10){
- return n; //1-10
- }
- else if(n<36){
- return String.fromCharCode(n+55); //A-Z
- }
- else{
- return String.fromCharCode(n+61); //a-z
- }
- }
- while(returnStr.length< range){
- returnStr += charFun();
- }
- };
-
- //根据指定的字符串中生成组合
- var accordCharStrGet = function(){
- for(var i=0; i<range; i++){
- var index = Math.round(Math.random() * (charStr.length-1));
- returnStr += charStr.substring(index,index+1);
- }
- };
- if(typeof min == 'undefined'){
- min = 10;
- }
- if(typeof max == 'string'){
- charStr = max;
- }
- range = ((max && typeof max == 'number') ? Math.round(Math.random() * (max-min)) + min : min);
-
- if(charStr){
- accordCharStrGet();
- }else{
- autoGetStr();
- }
- return returnStr;
- },
- //对象型数组根据对象的某个属性进行排序 type:默认是升序排序,传参DES则降序排列
- compare: function(property, type) {
- return function(a, b){
- var value1 = a[property];
- var value2 = b[property];
- if(type == 'DES') {
- return value2 - value1;
- }else{
- return value1 - value2;
- }
-
- }
- },
- //父界面直接调用jquery ui方法时,由于选择不同导致提示未初始化,所以采用增加方法的方式解决
- setBreadcrumb: function(tabAndCard, switchNode) {
- var breadcrumbItems = $('#breadcrumb').shrBreadcrumb('getItems');
- var breadCrumbLocationTop = top.shr.getUrlRequestParam('breadCrumbLocationTop');
-
- if(breadCrumbLocationTop == 'true') {
- breadcrumbItems[0].location = 'top';
- breadcrumbItems[1].location = 'top';
- breadcrumbItems[2].location = 'top';
- }
-
- if(breadcrumbItems[0].location == undefined) {
- breadcrumbItems[0].location = 'top';
- if(tabAndCard) {
- breadcrumbItems.splice(1, 0, tabAndCard.tabs);
- breadcrumbItems.splice(2, 0, {url: parent.window.location + '&index=1', name: tabAndCard.cards.name, location: 'top'});
- }
- if(breadcrumbItems.length > 4 && switchNode) {
- breadcrumbItems.splice(3, breadcrumbItems.length - 4);
- }else if(breadcrumbItems.length > 5) {
- breadcrumbItems.splice(3, breadcrumbItems.length - 5);
- }
- }else{
- breadcrumbItems[0].location = 'top';
- if(tabAndCard) {
- if(breadcrumbItems[2].name != tabAndCard['cards'].name) {
- breadcrumbItems.splice(2, 0, {url: parent.window.location + '&index=1', name: tabAndCard.cards.name, location: 'top'});
- }
- }
-
- if(breadcrumbItems.length > 4 && switchNode) {
- breadcrumbItems.splice(3, breadcrumbItems.length - 4);
- }else if(breadcrumbItems.length > 5) {
- breadcrumbItems.splice(3, breadcrumbItems.length - 5);
- }
- }
-
- $('#breadcrumb').shrBreadcrumb('setItems', breadcrumbItems);
- },
-
- /**
- * 适配OSF响应数据格式
- */
- adapteOSFResponseDataFormat: function( obj ) {
- var returnObject = obj;
- if( shr.isStandardOSFResponseFormatByResponseData( obj ) ) {
- if(obj['errCode'] ==0){
- if(obj['_e_x_t_d_'] && obj['_e_x_t_d_']['_e_s_k_'] && obj['_e_x_t_d_']['_d_k_']){
- var esk = shr.decryptForAes_CBC(obj['_e_x_t_d_']['_e_s_k_'],obj['_e_x_t_d_']['_d_k_']);
- returnObject = shr.decryptForAes_CBC(obj.data,esk);
- }else{
- returnObject = JSON.stringify( obj.data );
- }
- }else{
- returnObject = null;
- shr.showError({message: obj['errMsg']});
- }
- }
- return returnObject;
- },
-
- isStandardOSFResponseFormatByResponseData: function( responseDataObject ) {
- if( !$.isPlainObject( responseDataObject ) ) {
- return false ;
- }
- // attribute list
- var standardOSFResponseObjectProperties = ['errCode','bizCode','data','errMsg','_e_x_t_d_'];
- for( var property in standardOSFResponseObjectProperties ) {
- if( !responseDataObject.hasOwnProperty( standardOSFResponseObjectProperties[property] ) ) {
- return false;
- }
- }
-
- return true;
- },
-
- generateOSFSignature: function(openServiceUrl){
- return shr.encryptForAes_CBC(openServiceUrl+','+Math.floor(Math.random() * (50000 - 1) + 1)+','+new Date().getTime());
- },
-
- /**
- * 图片预览
- * url: 需要预览图片的src,如果不存在url可以直接传null
- * $picArr: 需要预览图片的jquery对象集合
- */
- previewPic: function(url, $picArr) {
- var $topBody = $(window.top.document.body);
- if(!url) {
- $picArr.on('click', function() {
- var index = getPreviewImgIndex($(this).attr('src'));
- $topBody.append(getPicTemplate($(this).attr('src'), index));
- $topBody.find('.zoomableContainer').data('imgArr', $picArr);
- $topBody.find('.zoomableContainer').css('top', window.top.document.documentElement.scrollTop);
- $topBody.css({'overflow': 'hidden'});
- $topBody.css({'top': $(_top.document).scrollTop()});
-
- previewPicListener();
- });
- }else{
- $topBody.append(getPicTemplate(url));
- }
-
- var getPicTemplate = function(url, index) {
- var picPreview = [
- '<div class="zoomableContainer" style="width:100%;height:100%;position: absolute;top: 0;z-index: 9999;background-color: rgba(0, 0, 0, 0.7);text-align: center;">',
- '<img id="previewClose" src="/shr/styles/images/attachment-icon-close.png" style="position: absolute;top: 25px;right: 30px;cursor:pointer;z-index: 99999">',
- '<div style="margin:auto;width: 100%;height: 100%;overflow: hidden;justify-content: center;align-items: center;display: flex;position: relative;">',
- '<img id="preViewImg" imgIndex="' + index + '" src="' + url + '" style="width: auto;transform: translate3d(0px, 0px, 0px) scale3d(1, 1, 1);position: absolute;cursor: move;">',
- '</div>',
- '<div class="bottomBtn" style="margin-top: 15px;position: absolute;left: calc(50% - 120px);bottom: 15px;">',
- '<img id="previewPrev" src="/shr/styles/images/attachment_prev.png" style="cursor:pointer;">',
- '<img id="previewDownload" src="/shr/styles/images/attachment_enlarge.png" style="cursor:pointer;margin-left: 20px;margin-right: 20px;">',
- '<img id="previewRotate" src="/shr/styles/images/attachment_rotate.png" style="cursor:pointer;margin-left: 20px;margin-right: 20px;">',
- '<img id="previewOrigin" src="/shr/styles/images/attachment_narrow.png" style="cursor:pointer;margin-left: 20px;margin-right: 20px;">',
- '<img id="previewNext" src="/shr/styles/images/attachment_next.png" style="cursor:pointer;">',
- '</div>',
- '</div>'
- ];
-
- return picPreview.join('');
- };
-
- var previewPicListener = function() {
- //放大
- var $topBody = $(window.top.document.body);
- var $preViewImg = $topBody.find('#preViewImg');
- var imgArr = $topBody.find('.zoomableContainer').data('imgArr');
- $topBody.find('#previewDownload').on('click', function(){
- var scale = getPreviewPicScale();
- var deg = getPreviewPicDeg();
-
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + 1.2 * scale + ', ' + 1.2 * scale + ', 1) rotate(' + deg + 'deg)');
- })
-
- //翻转图片
- $topBody.find('#previewRotate').on('click', function(){
- var scale = getPreviewPicScale();
- if(getPreviewPicDeg() == 0) {
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + scale + ', ' + scale + ', 1) rotate(90deg)');
- return;
- }
-
- if(getPreviewPicDeg() == 90) {
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + scale + ', ' + scale + ', 1) rotate(180deg)');
- return;
- }
-
- if(getPreviewPicDeg() == 180) {
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + scale + ', ' + scale + ', 1) rotate(270deg)');
- return;
- }
-
- if(getPreviewPicDeg() == -90) {
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + scale + ', ' + scale + ', 1) rotate(0deg)');
- return;
- }
- })
-
- //缩小
- $topBody.find('#previewOrigin').on('click', function(){
- var scale = getPreviewPicScale();
- var deg = getPreviewPicDeg();
-
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + 0.8 * scale + ', ' + 0.8 * scale + ', 1) rotate(' + deg + 'deg)');
- })
-
- $topBody.find('#previewClose').on('click', function(){
- $topBody.css({'overflow': 'auto'});
- $topBody.find('#previewClose').parent().remove();
- })
-
- //上一张
- $topBody.find('#previewPrev').on('click', function(){
- var index = parseInt($preViewImg.attr('imgindex'));
- if(index == imgArr.length - 1) {
- $topBody.find('#previewNext').attr('src', '/shr/styles/images/attachment_next.png')
- }
-
- if(index == 1) {
- $(this).attr('src', '/shr/styles/images/attachment_prev_disable.png')
- }
-
- if(index == 0) return;
-
- $preViewImg.attr('src', $(imgArr[index - 1]).attr('src'));
- $preViewImg.attr('imgindex', index - 1);
- });
-
- //下一张
- $topBody.find('#previewNext').on('click', function(){
- var index = parseInt($preViewImg.attr('imgindex'));
-
- if(index == 0) {
- $topBody.find('#previewPrev').attr('src', '/shr/styles/images/attachment_prev.png')
- }
-
- if(index == imgArr.length - 2) {
- $(this).attr('src', '/shr/styles/images/attachment_next_disable.png')
- }
-
- if(index == imgArr.length - 1) return;
-
- $preViewImg.attr('src', $(imgArr[index + 1]).attr('src'));
- $preViewImg.attr('imgindex', index + 1);
- });
-
- //拖动图片
- var canMove = false;
- var dragX, dragY;
- $preViewImg.on('mousedown', function(e) {
- e.preventDefault()
- canMove = true;
- dragX = e.clientX - $preViewImg[0].offsetLeft;
- dragY = e.clientY - $preViewImg[0].offsetTop;
- });
-
- $preViewImg.on('mousemove', function(e) {
- e.preventDefault()
- if(canMove) {
- var left = e.clientX - dragX;
- var top = e.clientY - dragY;
- }
-
- if(left < 0) {
- left = left;
- }else if(left > _top.window.innerWidth - $preViewImg[0].offsetWidth) {
- left = left;
- }
-
- if(top < 0) {
- top = top;
- }else if(top > _top.window.innerHeight - $preViewImg[0].offsetHeight) {
- top = top;
- }
-
- $preViewImg.css({
- left: left + 'px',
- top: top + 'px'
- });
- });
-
- $preViewImg.on('mouseup', function(e) {
- e.preventDefault()
- canMove = false;
- });
-
- //滑动滚轮实现图片的放大和缩小
- $preViewImg.on("mousewheel", function (e) {
- e.preventDefault();
- var deg = getPreviewPicDeg();
- var scale = getPreviewPicScale();
- var del = 0;
- if(e.originalEvent.wheelDelta) {
- del = e.originalEvent.wheelDelta;
- }else if(e.originalEvent.detail) {
- del = e.originalEvent.detail * -1;
- }
-
- if(del > 0) {
- // 放大
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + 1.2 * scale + ', ' + 1.2 * scale + ', 1) rotate(' + deg + 'deg)');
- }else if(del < 0) {
- // 缩小
- $preViewImg.css('transform', 'translate3d(0px, 0px, 0px) scale3d(' + 0.8 * scale + ', ' + 0.8 * scale + ', 1) rotate(' + deg + 'deg)');
- }
- });
- };
-
- //获取图片当前的旋转角度
- var getPreviewPicDeg = function() {
- var $topBody = $(window.top.document.body);
- var $preViewImg = $topBody.find('#preViewImg');
- var values = $preViewImg.css('transform').split('(')[1].split(')')[0].split(',');
- var deg = Math.round(Math.atan2(values[1], values[0]) * (180 / Math.PI));
- return deg;
- };
- //获取图片当前的放大或者缩小值
- var getPreviewPicScale = function() {
- var $topBody = $(window.top.document.body);
- var $preViewImg = $topBody.find('#preViewImg');
- var values = $preViewImg.css('transform').split('(')[1].split(')')[0].split(',');
- var scale = Math.sqrt(values[0] * values[0] + values[1] * values[1]);
- return scale;
- };
- //获取点击预览时的图片数组下标
- var getPreviewImgIndex = function(src) {
- var imgArr = $picArr;
- var index = 0;
- for(var i = 0;i < imgArr.length;i++) {
- if(src == $(imgArr[i]).attr('src')) {
- index = i;
- break;
- }
- }
- return index;
- };
- }
- });
- /**
- * jQuery JSON Plugin
- * version: 2.3 (2011-09-17)
- *
- * This document is licensed as free software under the terms of the
- * MIT License: http://www.opensource.org/licenses/mit-license.php
- *
- * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
- * website's http://www.json.org/json2.js, which proclaims:
- * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
- * I uphold.
- *
- * It is also influenced heavily by MochiKit's serializeJSON, which is
- * copyrighted 2005 by Bob Ippolito.
- */
- (function( $ ) {
- var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
- meta = {
- '\b': '\\b',
- '\t': '\\t',
- '\n': '\\n',
- '\f': '\\f',
- '\r': '\\r',
- '"' : '\\"',
- '\\': '\\\\'
- };
-
- $.ajaxSetup({
-
- // add ext RequestHeader For OSF request.
- beforeSend: function( jqXHR,ajaxOptions ) {
- // if current request is OSF Request, then check adapteOSFResponseDataFormat. default value is true;
- // if you want to use standard response data format ,then set options.adapteOSFResponseDataFormat = false;
- var adapteOSFResponseDataFormat = ( ajaxOptions && ajaxOptions.adapteOSFResponseDataFormat ) ? ajaxOptions.adapteOSFResponseDataFormat : true;
- var openServiceUrl = shr.getOpenServiceFullPath() ;
- var _requsetUrl = ajaxOptions.url ;
- var isOSFRequest = ( _requsetUrl && _requsetUrl.indexOf(openServiceUrl) >= 0 ) ? true : false ;
- var isGetTreeDataURL = ( _requsetUrl && _requsetUrl.indexOf(shr.getTreeDataURL) >= 0 ) ? true : false ;
- function getOSFReqHeaderSignature(ajaxOptions){
-
- }
- // set ajaxOptions.adapteOSFResponseDataFormat
- ajaxOptions.adapteOSFResponseDataFormat = adapteOSFResponseDataFormat;
- ajaxOptions.isOSFRequest = isOSFRequest;
-
- if( isOSFRequest ) {
- jqXHR.adapteOSFResponseDataFormat = adapteOSFResponseDataFormat;
- jqXHR.isOSFRequest = isOSFRequest;
- jqXHR.setRequestHeader("X-OSF-Signature", shr.generateOSFSignature(openServiceUrl));
- }
- if(isGetTreeDataURL){
- jqXHR.setRequestHeader("x-shr-encrypt-F7", shr.getXShrEncryptF7Value());
- }
- },
-
- // adapte OSF Response Data by extend dataFilter.
- dataFilter: function( data, dataType ) {
- var _options = this,jsonObj;
- // if not OSFRequest, return original data
- if( !( _options && _options.isOSFRequest ) ){
- return data ;
- }
-
- if( _options && _options.adapteOSFResponseDataFormat ) {
- if( data ){
- jsonObj = ( shr.isJSON(data)) ? JSON.parse( data ) : data ;
- // Judgment base on results
- // need Judgment dataType,here is JSON Type, maybe text,xml and so on. to do other Logic .........
- return shr.isStandardOSFResponseFormatByResponseData( jsonObj ) ? shr.adapteOSFResponseDataFormat( jsonObj ) : data;
- }
- }else{
- return data;
- }
- }
- });
-
-
- /**
- * jQuery.toJSON
- * Converts the given argument into a JSON respresentation.
- *
- * @param o {Mixed} The json-serializble *thing* to be converted
- *
- * If an object has a toJSON prototype, that will be used to get the representation.
- * Non-integer/string keys are skipped in the object, as are keys that point to a
- * function.
- *
- */
- $.toJSON = typeof JSON === 'object' && JSON.stringify
- ? JSON.stringify
- : function( o ) {
- if ( o === null ) {
- return 'null';
- }
- var type = typeof o;
- if ( type === 'undefined' ) {
- return undefined;
- }
- if ( type === 'number' || type === 'boolean' ) {
- return '' + o;
- }
- if ( type === 'string') {
- return $.quoteString( o );
- }
- if ( type === 'object' ) {
- if ( typeof o.toJSON === 'function' ) {
- return $.toJSON( o.toJSON() );
- }
- if ( o.constructor === Date ) {
- var month = o.getUTCMonth() + 1,
- day = o.getUTCDate(),
- year = o.getUTCFullYear(),
- hours = o.getUTCHours(),
- minutes = o.getUTCMinutes(),
- seconds = o.getUTCSeconds(),
- milli = o.getUTCMilliseconds();
- if ( month < 10 ) {
- month = '0' + month;
- }
- if ( day < 10 ) {
- day = '0' + day;
- }
- if ( hours < 10 ) {
- hours = '0' + hours;
- }
- if ( minutes < 10 ) {
- minutes = '0' + minutes;
- }
- if ( seconds < 10 ) {
- seconds = '0' + seconds;
- }
- if ( milli < 100 ) {
- milli = '0' + milli;
- }
- if ( milli < 10 ) {
- milli = '0' + milli;
- }
- return '"' + year + '-' + month + '-' + day + 'T' +
- hours + ':' + minutes + ':' + seconds +
- '.' + milli + 'Z"';
- }
- if ( o.constructor === Array ) {
- var ret = [];
- for ( var i = 0; i < o.length; i++ ) {
- ret.push( $.toJSON( o[i] ) || 'null' );
- }
- return '[' + ret.join(',') + ']';
- }
- var name,
- val,
- pairs = [];
- for ( var k in o ) {
- type = typeof k;
- if ( type === 'number' ) {
- name = '"' + k + '"';
- } else if (type === 'string') {
- name = $.quoteString(k);
- } else {
- // Keys must be numerical or string. Skip others
- continue;
- }
- type = typeof o[k];
- if ( type === 'function' || type === 'undefined' ) {
- // Invalid values like these return undefined
- // from toJSON, however those object members
- // shouldn't be included in the JSON string at all.
- continue;
- }
- val = $.toJSON( o[k] );
- pairs.push( name + ':' + val );
- }
- return '{' + pairs.join( ',' ) + '}';
- }
- };
- /**
- * jQuery.evalJSON
- * Evaluates a given piece of json source.
- *
- * @param src {String}
- */
- $.evalJSON = typeof JSON === 'object' && JSON.parse
- ? JSON.parse
- : function( src ) {
- return eval('(' + src + ')');
- };
- /**
- * jQuery.secureEvalJSON
- * Evals JSON in a way that is *more* secure.
- *
- * @param src {String}
- */
- $.secureEvalJSON = typeof JSON === 'object' && JSON.parse
- ? JSON.parse
- : function( src ) {
- var filtered =
- src
- .replace( /\\["\\\/bfnrtu]/g, '@' )
- .replace( /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
- .replace( /(?:^|:|,)(?:\s*\[)+/g, '');
- if ( /^[\],:{}\s]*$/.test( filtered ) ) {
- return eval( '(' + src + ')' );
- } else {
- throw new SyntaxError( 'Error parsing JSON, source is not valid.' );
- }
- };
- /**
- * jQuery.quoteString
- * Returns a string-repr of a string, escaping quotes intelligently.
- * Mostly a support function for toJSON.
- * Examples:
- * >>> jQuery.quoteString('apple')
- * "apple"
- *
- * >>> jQuery.quoteString('"Where are we going?", she asked.')
- * "\"Where are we going?\", she asked."
- */
- $.quoteString = function( string ) {
- if ( string.match( escapeable ) ) {
- return '"' + string.replace( escapeable, function( a ) {
- var c = meta[a];
- if ( typeof c === 'string' ) {
- return c;
- }
- c = a.charCodeAt();
- return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
- }) + '"';
- }
- return '"' + string + '"';
- };
-
- $.getUrlParam = function(name){
- var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
- var r = window.location.search.substr(1).match(reg);
- // if (r!=null) return unescape(r[2]); return null;
- if (r!=null) return decodeURIComponent(r[2]); return null;
- }
- })( jQuery );
- /**
- * 打开滚动条
- * @param type
- */
- function openLoader(type, tip) {
- if(!type) type = 1;
- $("#loaderTip", _top.document).text(tip ? tip : $("#loaderTip" + type, _top.document).text());
-
- $("#loader", _top.document).show().css("display", "block");
- }
- /**
- * JSON转化时,对循环结构的转化则会出错
- * 解决方法:避免对循环结构进行转化
- */
- JSON.stringifyOnce = function(obj, replacer, indent){
- var printedObjects = [];
- var printedObjectKeys = [];
-
- function printOnceReplacer(key, value){
- if ( printedObjects.length > 20000){
- return 'object too long';
- }
- var printedObjIndex = false;
- printedObjects.forEach(function(obj, index){
- if(obj===value){
- printedObjIndex = index;
- }
- });
-
- if ( key == ''){
- printedObjects.push(obj);
- printedObjectKeys.push("root");
- return value;
- } else if (printedObjIndex+"" != "false" && typeof(value)=="object"){
- if ( printedObjectKeys[printedObjIndex] == "root"){
- return "(pointer to root)";
- }else{
- return "(see " + ((!!value && !!value.constructor) ? value.constructor.name.toLowerCase() : typeof(value)) + " with key " + printedObjectKeys[printedObjIndex] + ")";
- }
- } else {
- var qualifiedKey = key || "(empty key)";
- printedObjects.push(value);
- printedObjectKeys.push(qualifiedKey);
- if(replacer){
- return replacer(key, value);
- }else{
- return value;
- }
- }
- }
- return JSON.stringify(obj, printOnceReplacer, indent);
- };
- /**
- * 关闭滚动条
- */
- function closeLoader() {
- $("#loader", _top.document).hide().css("display", "none");
- }
- $(document).ready(function() {
- if(!window.console) {console={}; console.log = function(){};}
- if ($.browser.msie && $.browser.version < 9) {
- window.location.href = "browser/browser.html";
- }
- _top = getTop();
- // IE9 support (input, textarea tag) placeholder attribute, use jQuery Placeholder Plugin v2.3.1
- var textElements = $('input, textarea');
- if( textElements && textElements.placeholder ){
- try {
- textElements.placeholder();
- } catch (error) {
- console.log( " placeholder init error " );
- }
- }
- if(window.localStorage.getItem('screenModel') == 'true') {
- $('#castScreenModel a').text($.shrI18n.common.screenModel.standScreenModel);
- shr.loadCss('/shr/styles/castScreenModel.css');
- }
-
- // 使用节流函数来监听页面的缩放,间隔时间可自行设置,防止每次滚动实时监听导致卡顿。(当浏览器宽度小于1200时,不建议用户使用,当浏览器缩放时,提示用户复原)
- // 并且增加“不再提醒”功能,如果用户点击了不再提醒,则通过localStorage存一个标识,和账号绑定,即该账号不会在当前设备上提示。
- // 增加一个判断,当有些页面没有用户id时,则不进行缩放监听。
- // var isScading = shr.getUserInfo().id;
- // if (isScading) {
- // try{
- // var isPrompts = localStorage.getItem(isScading + '#ScreenZoom');
- // if (!isPrompts) {
- // addWindowResize();
- // $(top.window).off('resize', throttle(addWindowResize, 500)).on('resize', throttle(addWindowResize, 500));
- // }
- // } catch (error){
- // console.log(error);
- // }
- // }
-
- $(document).on('click', function(e) {
- if(e.target.className != 'parallelNodeNum' && e.target.className != 'rateProgress' && e.target.className != 'rateProgressImg') {
- $(window.parent.document).find('.parallelNode').hide();
- $(window.parent.document).find('.rateProgressToolsDiv').hide();
- }
- });
- //console.log($('#breadcrumb').shrBreadcrumb('getItems'));
- });
- function addWindowResize() {
- try{
- // 再次增加一个判断,如果点了不再提醒,则直接返回
- var isPrompts = localStorage.getItem(shr.getUserInfo().id + '#ScreenZoom');
- if (isPrompts) {
- return
- }
- var currentZoom = shr.detectZoom();
- // 当缩放比例大于150或者小于100时,和当浏览器宽度小于1200时,提示!
- if(currentZoom < 100 || currentZoom > 150 ) {
- shr.showMaskWarning({
- message: $.shrI18n.common.tips.screenZoom
- });
- } else if ($(top.window).width() < 1200) {
- shr.showMaskWarning({
- message: $.shrI18n.common.tips.screenWidth
- });
- }
- } catch (error){
- console.log(error);
- }
- }
- // 节流函数,防止频繁触发,可以通过时间间隔来控制触发的间隔,即在规定时间间隔内只会触发一次。
- function throttle(callback,delay){
- var timer,
- begin = new Date();
- return function(){
- var current = new Date();
- clearTimeout(timer);
- if(current - begin >= delay){
- callback();
- begin = current;
- }else{
- timer = setTimeout(function() {
- callback();
- },delay);
- }
- }
- }
- //内嵌入EAS页面时,改变Top指向
- function getTop(){
- // 当shr单据在门户中打开时,嵌套在iframe id='bill-frame'中,iframe的创建过程参考门户工作流 approve.js 492行
- // shr单据在门户中打开时,从8.5版本发生变化,对应id为:$(".portal-page","#pageContainer").not(".hide").attr("id"); update by tiangang_yang 2018/03/07
- // shr单据在门户中打开时,从8.5版本发生变化,根据class='portal-page'来获取; update by tiangang_yang 2018/06/25
- return isFromPortal()?window:top;
- }
- function isFromPortal(){
- var billFrame = (frameElement && (frameElement.getAttribute("id") == "bill-frame" || frameElement.getAttribute("id") == "billFrame"));
- if(billFrame){
- return frameElement;
- }
- //兼容portal-page
- var billFrame2 = (frameElement && frameElement.getAttribute("class") == "portal-page");
- if(billFrame2){
- return billFrame2;
- }
- var billFrames = $(".portal-page","#pageContainer").not(".hide");
- if(billFrames && billFrames.length >= 1){
- return billFrames[0];
- }
-
- // 兼容bos的85版本新流程中心iframe的id改动,增加按proInstId参数判断 by wei_yw_yang 2019/11/12
- var src = frameElement && frameElement.getAttribute("src");
- var billFrame3 = (src && src.indexOf('&proInstId=') != -1);
- if(billFrame3){
- return billFrame3;
- }
- return null;
- }
- /**
- * 描述:重写namedItem方法,解决IE下由于ID大小写问题导致窜行的问题。
- * @author BJJLG
- * @class
- * @constructor
- * @return
- */
- if (window.HTMLCollection){
- HTMLCollection.prototype.namedItem = function(name){
- var len = this.length,ret = null;
- if(len>0){
- for(var i=0;i<len;i++){
- if(this[i].id && this[i].id == name){
- ret = this[i];
- break;
- }
- }
- }
- return ret;
- }
- }
- //进入全屏
- function enterfullscreen() {
- var docElm = document.documentElement;
- var requestMethod = docElm.requestFullScreen || //W3C
- docElm.webkitRequestFullScreen || //FireFox
- docElm.mozRequestFullScreen || //Chrome等
- docElm.msRequestFullscreen; //IE11
- if (requestMethod) {
- requestMethod.call(docElm);
- } else if (typeof window.ActiveXObject !== "undefined") {
- var wscript = new ActiveXObject("WScript.Shell");
- if (wscript !== null) {
- wscript.SendKeys("{F11}");
- }
- }
- }
- function exitfullscreen() {
- // 判断各种浏览器,找到正确的方法
- var exitMethod = document.exitFullscreen || //W3C
- document.mozCancelFullScreen || //FireFox
- document.webkitExitFullscreen || //Chrome等
- document.msExitFullscreen; //IE11
- if (exitMethod) {
- exitMethod.call(document);
- } else if (typeof window.ActiveXObject !== "undefined") { //for Internet Explorer
- var wscript = new ActiveXObject("WScript.Shell");
- if (wscript !== null) {
- wscript.SendKeys("{F11}");
- }
- }
- }
- function checkFull() {
- return document.fullscreenElement ||
- document.msFullscreenElement ||
- document.mozFullScreenElement ||
- document.webkitFullscreenElement;
- }
- /**
- * 描述:重写Date,处理在不同时区的时候用中国时间格式横杆少一天,员工离职页点离职日期可以重现
- */
- try {
- if(Intl && Intl.DateTimeFormat().resolvedOptions().timeZone != 'Asia/Shanghai'){
- var OldDate = Date;
- // 重写arguments[0]
- Date = function () {
- var datePattern = /^\d{4}-\d{2}-\d{2}$/;
- // 检查日期字符串是否符合格式
-
- var p = '';
- // IOS环境,时间转化的问题,现在没有客户反馈暂时先不处理
- // if (navigator.userAgent.includes('iPhone') || navigator.userAgent.includes('iPad')) {
- // if (arguments.length > 0 && typeof (arguments[0]) === 'string' && arguments[0].includes('-')) {
- // p = arguments[0].replace(/-/g, '/');
- // arguments[0] = p;
- // }
- // }
- if (arguments.length > 0 && typeof (arguments[0]) === 'string' && arguments[0].indexOf('-') >= 0 && datePattern.test(arguments[0])) {
- //p = arguments[0] + ' 00:00:00'; IE不兼容这种写法
- p = arguments[0].replace(/-/g, '/');
- arguments[0] = p;
- }
- var arr = Array.prototype.slice.call(arguments);
- var str = '';
- if(arr.length == 1){
- return new OldDate(arr[0]);
- }else{
- str = arr.join(',');
- return eval('new OldDate(' + str + ')');
- }
- }
- // 继承原型函数
- Date.prototype = OldDate.prototype;
- // 继承静态函数,过滤已有的静态函数和参数,取数组差集
- var oldDateStaticParam = Object.getOwnPropertyNames(OldDate);
- var dateStaticParam = Object.getOwnPropertyNames(Date);
- var diffParam = [];
- for (var i = 0; i < oldDateStaticParam.length; i++) {
- var find = false;
- for (var j = 0; j < dateStaticParam.length; j++) {
- if (oldDateStaticParam[i] === dateStaticParam[j]) {
- find = true;
- break;
- }
- }
- if (!find) {
- diffParam.push(oldDateStaticParam[i]);
- }
- }
- for (var i = 0; i < diffParam.length; i++) {
- Date[diffParam[i]] = OldDate[diffParam[i]];
- }
- }
- } catch (error) {
- console.log(error);
- }
|