AppDelegateBase.m 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846
  1. //
  2. // AppDelegateBase.m
  3. // iSales-UWAVER
  4. //
  5. // Created by Ray on 2018/8/9.
  6. // Copyright © 2018 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "AppDelegateBase.h"
  9. #import "UILabel+FontAppearance.h"
  10. #import "MainViewController.h"
  11. #import "RAPDFViewController.h"
  12. #import "ZipArchive.h"
  13. #import "DefaultAppearance.h"
  14. #import "OLDataProvider.h"
  15. #import "SelectUploadOrderViewController.h"
  16. #import "iSalesDB.h"
  17. #import "RANetwork.h"
  18. #import "NotificationNameCenter.h"
  19. #import "CustomerEditViewController.h"
  20. #import "CreateOrderViewController.h"
  21. #import "OrderDetailViewController.h"
  22. #import "AddressEditorViewController.h"
  23. #import "config.h"
  24. #import "RASingleton.h"
  25. #ifdef GOOGLE_ANALYTICS
  26. #import "Analytics.h"
  27. #import "GoogleAnalyst.h"
  28. #endif
  29. #import "ERPUtils.h"
  30. #import "RANetwork.h"
  31. #import "RASingleton.h"
  32. #ifdef BACKORDER_PROCESS
  33. #import "RAOrderEditorViewController.h"
  34. #endif
  35. #import "RAConvertor.h"
  36. #import "config.h"
  37. #define UNZIP_OPEN_FAILED 0
  38. #define UNZIP_SUCCESS 1
  39. #define UNZIP_NO_SPACE 2
  40. #define UNZIP_FILE_DAMAGE 3
  41. @interface AppDelegateBase ()
  42. @property (nonatomic,strong) NSDate *forgroundDate;
  43. @end
  44. @implementation AppDelegateBase
  45. {
  46. #ifdef USE_SOFTSCAN
  47. DeviceInfo* _softScanDeviceInfo;
  48. #endif
  49. DeviceInfo* _deviceInfoToTrigger;
  50. NSMutableArray* _feedbackStack;
  51. id<ScannerEventsFeedback> _eventsFeedback;
  52. }
  53. @synthesize ScanApi;
  54. @synthesize ScanApiConsumer;
  55. @synthesize scanApiVersion;
  56. @synthesize price_hidden = _price_hidden;
  57. #pragma mark - Global Parameter
  58. //- (NSMutableDictionary *)globalParameters {
  59. // if (!_globalParameters) {
  60. // _globalParameters = [NSMutableDictionary dictionary];
  61. // }
  62. // return _globalParameters;
  63. //}
  64. //
  65. //- (void)setGlobalParameter:(id)param forKey:(NSString *)key {
  66. // if (param == nil || key == nil) {
  67. // return;
  68. // }
  69. // [self.globalParameters setObject:param forKey:key];
  70. //}
  71. //
  72. //- (id)globalParameterForKey:(NSString *)key {
  73. // if (key == nil) {
  74. // return nil;
  75. // }
  76. // return [self.globalParameters objectForKey:key];
  77. //}
  78. #pragma mark - Setter
  79. - (void)setUrgencyDic:(NSMutableDictionary *)urgencyDic {
  80. _urgencyDic = urgencyDic;
  81. [RASingleton.sharedInstance setGlobalParameter:_urgencyDic forKey:@"urgencyDic"];
  82. }
  83. - (void)setCan_see_price:(bool)can_see_price {
  84. _can_see_price = can_see_price;
  85. [RASingleton.sharedInstance setGlobalParameter:@(_can_see_price) forKey:@"can_see_price"];
  86. }
  87. - (void)setPrice_hidden:(bool)price_hidden {
  88. _price_hidden = price_hidden;
  89. [RASingleton.sharedInstance setGlobalParameter:@(_price_hidden) forKey:@"price_hidden"];
  90. #ifdef RA_NOTIFICATION
  91. [ActiveViewController Notify:@"" Message:RA_NOTIFICATION_UPDATE_PRICE];
  92. #else
  93. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  94. [avc showHidePrice];
  95. #endif
  96. }
  97. - (void)setOffline_mode:(bool)offline_mode {
  98. _offline_mode = offline_mode;
  99. [RASingleton.sharedInstance setGlobalParameter:@(_offline_mode) forKey:@"offline_mode"];
  100. }
  101. - (void)setUser:(NSString *)user {
  102. _user = user;
  103. [RASingleton.sharedInstance setGlobalParameter:_user forKey:@"user"];
  104. }
  105. - (void)setUser_type:(long)user_type
  106. {
  107. _user_type = user_type;
  108. }
  109. - (void)setPassword:(NSString *)password {
  110. _password = password;
  111. [RASingleton.sharedInstance setGlobalParameter:_password forKey:@"password"];
  112. }
  113. #pragma mark - Normal
  114. -(void) set_priceHidden:(bool)price_hidden
  115. {
  116. [self setPrice_hidden:price_hidden];
  117. }
  118. -(void) setCustomerInfo:(NSMutableDictionary*)customerInfo
  119. {
  120. if (self.user_type == USER_ROLE_CUSTOMER && _customerInfo) {
  121. return;
  122. }
  123. #ifdef RA_NOTIFICATION
  124. [ActiveViewController Notify:@"ContactListViewController" Message:RA_NOTIFICATION_REFRESH_UI];
  125. //切换账号应该不需要刷新wishlist,此处如果刷新,会使wishlist新建订单自动添加出错。
  126. // [ActiveViewController Notify:@"WatchListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  127. #else
  128. [((MainViewController*)self.main_vc) reloadContact:false immediately:false];
  129. [(MainViewController*)self.main_vc reloadWish:YES immediately:NO];
  130. #endif
  131. _customerInfo=customerInfo;
  132. // DebugLog(@"%@",_customerInfo.class);
  133. // DebugLog(@"%@",customerInfo.class);
  134. // int count=customerInfo[@"count"];
  135. //assert(count==0);
  136. }
  137. -(void) set_main_button_panel
  138. {
  139. return;
  140. // dispatch_async(dispatch_get_main_queue(), ^{
  141. // if(self.main_vc==nil)
  142. // return;
  143. // MainViewController * main_vc= (MainViewController*)self.main_vc;
  144. // if(self.user_type==USER_ROLE_CUSTOMER)
  145. // {
  146. // main_vc.customer_bp.hidden=false;
  147. // main_vc.employee_bp.hidden = true;
  148. // }
  149. // else
  150. // {
  151. // main_vc.customer_bp.hidden=true;
  152. // main_vc.employee_bp.hidden = false;
  153. // }
  154. // });
  155. }
  156. //#ifdef SCANNER_ORDER
  157. //- (void)updateScanButton:(BOOL)enable
  158. //{
  159. // MainViewController * mainvc=(MainViewController * )self.main_vc;
  160. // mainvc.btnScan.enabled = enable;
  161. //}
  162. //#endif
  163. -(void) update_count_mark
  164. {
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. if(self.main_vc==nil)
  167. return;
  168. MainViewController * main_vc= (MainViewController*)self.main_vc;
  169. //contact button
  170. if(self.user==nil)
  171. {
  172. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  173. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  174. main_vc.btnContact.hidden = YES;
  175. }
  176. else
  177. {
  178. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  179. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  180. if(self.customerInfo==nil)
  181. {
  182. // contact=@"No Name"; if(customerinfo==nil)
  183. // {
  184. contact=@"Select Contact";
  185. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  186. }
  187. else
  188. {
  189. if(contact==nil||contact.length==0)
  190. {
  191. contact=@"No Name";
  192. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  193. }
  194. else
  195. {
  196. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  197. }
  198. }
  199. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  200. if(contact.length>0)
  201. [arr_contact addObject:contact];
  202. if(customer.length>0)
  203. [arr_contact addObject:customer];
  204. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  205. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  206. }
  207. //cart
  208. if(self.user==nil||self.cart_count==0)
  209. {
  210. main_vc.label_ccount.hidden = true;
  211. main_vc.label_cccount.hidden=true;
  212. }
  213. else
  214. {
  215. NSString* strcount;
  216. if(self.cart_count>999)
  217. strcount=@"999+";
  218. else
  219. strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
  220. main_vc.label_ccount.text = strcount;
  221. if(strcount.length==1)
  222. main_vc.label_ccount.frame = CGRectMake(128, 0, 21, 21);
  223. if(strcount.length==2)
  224. main_vc.label_ccount.frame = CGRectMake(122, 0, 25, 21);
  225. if(strcount.length==3)
  226. main_vc.label_ccount.frame = CGRectMake(118, 0, 31, 21);
  227. if(strcount.length==4)
  228. main_vc.label_ccount.frame = CGRectMake(103, 0, 42, 21);
  229. main_vc.label_ccount.hidden = false;
  230. main_vc.label_cccount.text = strcount;
  231. if(strcount.length==1)
  232. main_vc.label_cccount.frame = CGRectMake(128, 0, 21, 21);
  233. if(strcount.length==2)
  234. main_vc.label_cccount.frame = CGRectMake(122, 0, 25, 21);
  235. if(strcount.length==3)
  236. main_vc.label_cccount.frame = CGRectMake(118, 0, 31, 21);
  237. if(strcount.length==4)
  238. main_vc.label_cccount.frame = CGRectMake(103, 0, 42, 21);
  239. main_vc.label_cccount.hidden = false;
  240. }
  241. //wishlist
  242. if(self.user==nil||self.wish_count==0)
  243. {
  244. main_vc.label_wcount.hidden = true;
  245. main_vc.label_cwcount.hidden = true;
  246. }
  247. else
  248. {
  249. NSString* strcount;
  250. if(self.wish_count>999)
  251. strcount=@"999+";
  252. else
  253. strcount=[NSString stringWithFormat:@"%ld",self.wish_count];
  254. main_vc.label_wcount.text = strcount;
  255. if(strcount.length==1)
  256. main_vc.label_wcount.frame = CGRectMake(433, 0, 21, 21);
  257. if(strcount.length==2)
  258. main_vc.label_wcount.frame = CGRectMake(433-6, 0, 25, 21);//-6
  259. if(strcount.length==3)
  260. main_vc.label_wcount.frame = CGRectMake(433-10, 0, 31, 21);//-10
  261. if(strcount.length==4)
  262. main_vc.label_wcount.frame = CGRectMake(433-21, 0, 42, 21);//-21
  263. main_vc.label_wcount.hidden = false;
  264. main_vc.label_cwcount.text = strcount;
  265. if(strcount.length==1)
  266. main_vc.label_cwcount.frame = CGRectMake(433-79, 0, 21, 21);
  267. if(strcount.length==2)
  268. main_vc.label_cwcount.frame = CGRectMake(433-6-79, 0, 25, 21);//-6
  269. if(strcount.length==3)
  270. main_vc.label_cwcount.frame = CGRectMake(433-10-79, 0, 31, 21);//-10
  271. if(strcount.length==4)
  272. main_vc.label_cwcount.frame = CGRectMake(433-21-79, 0, 42, 21);//-21
  273. main_vc.label_cwcount.hidden = false;
  274. }
  275. });
  276. }
  277. -(void) closeOrder
  278. {
  279. self.order_code = nil;
  280. self.order_customer_id = nil;
  281. if(self.user_type!=USER_ROLE_CUSTOMER)
  282. {
  283. self.customerInfo = nil;
  284. self.contact_id = nil;
  285. }
  286. // [self SetMode:nil];
  287. // [self SetSo:nil];
  288. #ifdef RA_NOTIFICATION
  289. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  290. #else
  291. [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
  292. [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
  293. #endif
  294. // [self updateScanButton:false];
  295. }
  296. -(void) switchToPreviousVC
  297. {
  298. MainViewController * main_vc= (MainViewController*)self.main_vc;
  299. [main_vc switchToPreviousVC];
  300. }
  301. -(void) SetMode:(NSString*)mode1
  302. {
  303. __block NSString* blockmode= mode1;
  304. dispatch_async(dispatch_get_main_queue(), ^{
  305. if(self.offline_mode)
  306. blockmode =@"Regular Mode";
  307. if(self.main_vc==nil)
  308. return;
  309. MainViewController * main_vc= (MainViewController*)self.main_vc;
  310. if(self.user==nil)
  311. {
  312. NSString* title = [NSString stringWithFormat:@"Sign in"];
  313. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  314. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  315. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  316. main_vc.btnContact.hidden = YES;
  317. main_vc.labelMode.text=nil;
  318. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  319. return;
  320. }
  321. else
  322. {
  323. #ifndef SCANNER_ORDER
  324. main_vc.btnContact.hidden = NO;
  325. #endif
  326. if(self.user_type==USER_ROLE_CUSTOMER)
  327. {
  328. NSString* title = [NSString stringWithFormat:@"%@",self.user];
  329. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  330. main_vc.labelMode.text=nil;
  331. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  332. }
  333. else
  334. {
  335. if([blockmode isEqualToString:@"Regular Mode"])
  336. {
  337. self.mode=@"RM";
  338. NSString* title = self.user;
  339. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  340. main_vc.labelMode.text=self.mode;
  341. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  342. }
  343. else
  344. {
  345. self.mode=@"TM";
  346. NSString* title = self.user;
  347. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  348. main_vc.labelMode.text=self.mode;
  349. [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
  350. }
  351. }
  352. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  353. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  354. if(self.customerInfo==nil)
  355. {
  356. // contact=@"No Name"; if(customerinfo==nil)
  357. // {
  358. contact=@"Select Contact";
  359. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  360. }
  361. else
  362. {
  363. if(contact==nil||contact.length==0)
  364. {
  365. contact=@"No Name";
  366. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  367. }
  368. else
  369. {
  370. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  371. }
  372. }
  373. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  374. if(contact.length>0)
  375. [arr_contact addObject:contact];
  376. if(customer.length>0)
  377. [arr_contact addObject:customer];
  378. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  379. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  380. }
  381. });
  382. }
  383. -(void) SetSo:(NSString *)So
  384. {
  385. dispatch_async(dispatch_get_main_queue(), ^{
  386. if(self.main_vc==nil)
  387. return;
  388. MainViewController * main_vc= (MainViewController*)self.main_vc;
  389. if (self.user_type == USER_ROLE_CUSTOMER) {
  390. if (So == nil) {
  391. // 释放订单
  392. [RASingleton sharedInstance].currentOrderIsMerged = NO;
  393. }
  394. }
  395. if(self.user==nil)
  396. {
  397. // NSString* title = [NSString stringWithFormat:@"Sign in"];
  398. main_vc.labelSo.text=nil;
  399. return;
  400. }
  401. else
  402. {
  403. {
  404. if(So.length==0)
  405. main_vc.labelSo.text=nil;
  406. else
  407. {
  408. NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
  409. main_vc.labelSo.text=text;
  410. }
  411. }
  412. }
  413. });
  414. }
  415. //- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
  416. // if ([rootViewController isKindOfClass:[UITabBarController class]]) {
  417. // UITabBarController* tabBarController = (UITabBarController*)rootViewController;
  418. // return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
  419. // } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
  420. // UINavigationController* navigationController = (UINavigationController*)rootViewController;
  421. // return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
  422. // } else if (rootViewController.presentedViewController) {
  423. // UIViewController* presentedViewController = rootViewController.presentedViewController;
  424. // return [self topViewControllerWithRootViewController:presentedViewController];
  425. // } else {
  426. // return rootViewController;
  427. // }
  428. //}
  429. //- (UIViewController*)topViewController {
  430. // return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  431. //}
  432. //-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  433. ////   // Get topmost/visible view controller
  434. // UIViewController *currentViewController = [self topViewController];
  435. //
  436. // if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
  437. //
  438. // return UIInterfaceOrientationMaskPortrait;
  439. // }
  440. ////
  441. ////   // Only allow portrait (standard behaviour)
  442. // return UIInterfaceOrientationMaskAll;
  443. //}
  444. void UncaughtExceptionHandler(NSException *exception) {
  445. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  446. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  447. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  448. NSString *versionNum = @"";
  449. versionNum = [NSString stringWithFormat:@"Version: %@ %@ Build %@",COMPANY_SHORT_NAME,version,build];
  450. versionNum = [versionNum stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  451. /**
  452. * 获取异常崩溃信息
  453. */
  454. NSArray *callStack = [exception callStackSymbols];
  455. NSString *reason = [exception reason];
  456. NSString *name = [exception name];
  457. NSString *content = [NSString stringWithFormat:@"异常错误报告\n exception_name: %@\n exception_reason: \n%@ \n exception_callStackSymbols: \n%@ \n",name,reason,[callStack componentsJoinedByString:@"\n"]];
  458. content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  459. NSString *sql = [NSString stringWithFormat:@"insert into errlog (errmsg,params) values ('%@','%@');",versionNum,content];
  460. if ([RASingleton sharedInstance].currentDB) {
  461. [iSalesDB close_db:[RASingleton sharedInstance].currentDB];
  462. }
  463. [iSalesDB execSql:sql];
  464. dispatch_async(dispatch_get_main_queue(), ^{
  465. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  466. [appDelegate writeUrgencyCache];
  467. });
  468. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  469. #ifdef SCANNER_ORDER
  470. [appDelegate saveUploadTasks];
  471. #endif
  472. }
  473. - (void)handleErrorLog {
  474. #ifdef SCANNER_ORDER
  475. return;
  476. #endif
  477. __block NSMutableArray *err_array = [NSMutableArray array];
  478. [iSalesDB jk_query:@"select errmsg,params,create_time from errlog;" completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  479. const char *version_char = (char *)sqlite3_column_text(stmt, 0);
  480. const char *errlog_char = (char *)sqlite3_column_text(stmt, 1);
  481. const char *dateTime_char = (char *)sqlite3_column_text(stmt, 2);
  482. if (version_char == NULL)
  483. version_char = "";
  484. if (errlog_char == NULL)
  485. errlog_char = "";
  486. if (dateTime_char == NULL)
  487. dateTime_char = "";
  488. NSString *version_str = [NSString stringWithUTF8String:version_char];
  489. NSString *errlog_str = [NSString stringWithUTF8String:errlog_char];
  490. NSString *dateTime_str = [NSString stringWithUTF8String:dateTime_char];
  491. NSDictionary *err_dic = @{
  492. @"version" : version_str,
  493. @"errlog" : errlog_str,
  494. @"time" : dateTime_str
  495. };
  496. [err_array addObject:err_dic];
  497. }];
  498. if (err_array.count) {
  499. // 首先上传
  500. for (NSDictionary *err_dic in err_array) {
  501. NSString *version = [err_dic objectForKey:@"version"];
  502. NSString *errlog = [err_dic objectForKey:@"errlog"];
  503. NSString *time = [err_dic objectForKey:@"time"];
  504. NSString *result = [NSString stringWithFormat:@"version: %@ \n crash_datetime: %@ \n",version,time];
  505. // NSDictionary *ret = [RANetwork err_log:errlog result:result module:@"crash" code:0];
  506. dispatch_async(dispatch_get_main_queue(), ^{
  507. [RANetwork request_err_log:errlog result:result module:@"crash" code:0 completionHandler:^(NSMutableDictionary *result) {
  508. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  509. // 上传成功之后清除纪录
  510. if ([[result objectForKey:@"result"] integerValue] == 2) {
  511. [iSalesDB execSql:[NSString stringWithFormat:@"delete from errlog where create_time = '%@';",time]];
  512. }
  513. });
  514. }];
  515. });
  516. }
  517. }
  518. }
  519. - (void)dealWithUrgencyFile {
  520. NSDictionary *tmp_urgencyDic = [self readUrgencyCache];
  521. if (tmp_urgencyDic.allKeys.count > 2) {
  522. [self.urgencyDic removeAllObjects];
  523. [self.urgencyDic setObject:[NSNumber numberWithInt:0] forKey:@"count"];
  524. // UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  525. NSString *user = [tmp_urgencyDic objectForKey:@"user"];
  526. if (![user isEqualToString:self.user]) {
  527. return;
  528. }
  529. BOOL offline_mode = [[tmp_urgencyDic objectForKey:@"offline_mode"] boolValue];
  530. if (!((self.offline_mode && offline_mode) || (!self.offline_mode && !offline_mode))) {
  531. return;
  532. }
  533. id count = [tmp_urgencyDic objectForKey:@"count"];
  534. int level_count = count ? (int)[count integerValue] : 0;
  535. if (!level_count) {
  536. return;
  537. }
  538. for (int i = 0; i < level_count; i++) {
  539. NSString *level_key = [NSString stringWithFormat:@"level_%d",i];
  540. NSDictionary *urgencyDic = [tmp_urgencyDic objectForKey:level_key];
  541. NSString *className = [urgencyDic objectForKey:@"class_name"];
  542. NSString *restored_data_key = [NSString stringWithFormat:@"%@_restored_data",className];
  543. NSMutableDictionary *restored_data = [urgencyDic objectForKey:restored_data_key];
  544. dispatch_async(dispatch_get_main_queue(), ^{
  545. if ([className isEqualToString:@"CustomerEditViewController"]) {
  546. // CustomerEditViewController
  547. NSString *contact_id = [urgencyDic objectForKey:@"contact_id"];
  548. BOOL new_customer = [urgencyDic objectForKey:@"new_customer"];
  549. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  550. [params setValue:contact_id forKey:@"contact_id"];
  551. CustomerEditViewController * cuseditVC =[[CustomerEditViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  552. cuseditVC.bnewcustomer=new_customer;
  553. cuseditVC.url_type = URL_RESTORE;
  554. cuseditVC.request_url= new_customer ? URL_NEW_CUSTOMER : URL_EDIT_CUSTOMER;
  555. cuseditVC.params = params;
  556. cuseditVC.content_data_download = restored_data;
  557. // cuseditVC.delegate=self;
  558. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  559. [[mainVC navigationController] setNavigationBarHidden:NO animated:NO];
  560. [mainVC.navigationController pushViewController:cuseditVC animated:false];
  561. } else if ([className isEqualToString:@"CreateOrderViewController"] || [className isEqualToString:@"RAOrderEditorViewController"]) {
  562. // CreateOrderViewController
  563. NSString *order_code = [urgencyDic objectForKey:@"order_code"];
  564. int order_status = [[urgencyDic objectForKey:@"order_status"] intValue];
  565. NSString *order_customer_id = [urgencyDic objectForKey:@"order_customer_id"];
  566. NSInteger userType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"urgency_userType"] integerValue];
  567. NSString *so = [urgencyDic objectForKey:@"order_so"];
  568. self.order_customer_id = order_customer_id;
  569. [RANetwork request_open_order:order_code completionHandler:^(NSMutableDictionary *result) {
  570. NSDictionary* order_json = result;
  571. // [waitalert dismissViewControllerAnimated:YES completion:nil];
  572. if([[order_json valueForKey:@"result"] intValue]==2)
  573. {
  574. self.order_code = order_code;
  575. self.order_status = order_status;
  576. [self SetSo:so];
  577. if (userType != USER_ROLE_CUSTOMER) {
  578. [RANetwork request_contactinfo:order_customer_id completionHandler:^(NSMutableDictionary *result) {
  579. self.customerInfo = [result[@"customerInfo"] mutableCopy];
  580. self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  581. }];
  582. // self.customerInfo = [[[RANetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
  583. //
  584. // self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  585. }
  586. #ifdef RA_NOTIFICATION
  587. [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  588. #else
  589. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  590. [mainVC reloadOrder:true immediately:false];
  591. [mainVC reloadCart:true immediately:false];
  592. #endif
  593. }
  594. else
  595. {
  596. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  597. [RAUtils message_alert:[order_json valueForKey:@"err_msg"] title:@"Open Order" controller:mainVC] ;
  598. }
  599. }];
  600. // 首先通过order code 打开订单
  601. // NSDictionary* order_json = [RANetwork open_Order:order_code];
  602. // dispatch_async(dispatch_get_main_queue(), ^{
  603. // // [waitalert dismissViewControllerAnimated:YES completion:nil];
  604. // if([[order_json valueForKey:@"result"] intValue]==2)
  605. // {
  606. //
  607. // self.order_code = order_code;
  608. // self.order_status = order_status;
  609. // [self SetSo:so];
  610. //
  611. // if (userType != USER_ROLE_CUSTOMER) {
  612. //
  613. // [RANetwork request_contactinfo:order_customer_id completionHandler:^(NSMutableDictionary *result) {
  614. // self.customerInfo = [result[@"customerInfo"] mutableCopy];
  615. // self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  616. // }];
  617. //
  618. //// self.customerInfo = [[[RANetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
  619. ////
  620. //// self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  621. // }
  622. //
  623. //
  624. //
  625. //
  626. //
  627. //#ifdef RA_NOTIFICATION
  628. // [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
  629. //#else
  630. // [mainVC reloadOrder:true immediately:false];
  631. // [mainVC reloadCart:true immediately:false];
  632. //#endif
  633. //
  634. // }
  635. // else
  636. // {
  637. // [RAUtils message_alert:[order_json valueForKey:@"err_msg"] title:@"Open Order" controller:mainVC] ;
  638. // }
  639. // });
  640. // 再place order
  641. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  642. if ([className isEqualToString:@"CreateOrderViewController"]) {
  643. CreateOrderViewController * orderinfoVC = [[CreateOrderViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  644. orderinfoVC.disable_dropdown_refresh=true;
  645. orderinfoVC.url_type = URL_RESTORE;
  646. orderinfoVC.request_url=URL_CARTDELIVERY;
  647. orderinfoVC.params = params;
  648. orderinfoVC.content_data_download = restored_data;
  649. orderinfoVC.resumeOrder = YES;
  650. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  651. [mainVC.navigationController pushViewController:orderinfoVC animated:true];
  652. }
  653. #ifdef BACKORDER_PROCESS
  654. else if ([className isEqualToString:@"RAOrderEditorViewController"]) {
  655. RAOrderEditorViewController *orderEditorVC = [[RAOrderEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  656. [orderEditorVC recoveryFromUrgencyDic:urgencyDic];
  657. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  658. [mainVC.navigationController pushViewController:orderEditorVC animated:YES];
  659. }
  660. #endif
  661. } else if ([className isEqualToString:@"AddressEditorViewController"]) {
  662. // AddressEditorViewController
  663. AddressEditorViewController * addressVC = [[AddressEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
  664. addressVC.url_type = URL_RESTORE;
  665. addressVC.request_url=URL_ADDRESS_EDOTOR;
  666. NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
  667. params[@"is_subaction"]=@"true";
  668. addressVC.params = params;
  669. addressVC.content_data_download = restored_data;
  670. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  671. [mainVC.navigationController pushViewController:addressVC animated:true];
  672. }// class_name
  673. });
  674. }
  675. }
  676. }
  677. - (void)handleUrgencyFile {
  678. __weak typeof(self) weakself = self;
  679. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  680. if (weakself) {
  681. __strong typeof(weakself) strongself = weakself;
  682. [strongself dealWithUrgencyFile];
  683. }
  684. });
  685. }
  686. - (void)writeUrgencyCache {
  687. if (!self.user) {
  688. return;
  689. }
  690. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  691. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  692. // [NSKeyedArchiver archiveRootObject:self.urgencyDic toFile:urgencyFile];
  693. [self.urgencyDic writeToFile:urgencyFile atomically:NO];
  694. // Place Order恢复是否能提交订单
  695. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_resume"];
  696. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:self.user_type] forKey:@"urgency_userType"];
  697. if ([RASingleton sharedInstance].currentOrderIsMerged && [RASingleton sharedInstance].permissions_submit_order) {
  698. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_submitOrder"];
  699. }
  700. }
  701. - (NSMutableDictionary *)readUrgencyCache {
  702. // 检查本地urgency文件,存在则加载进_urgencyDic
  703. NSFileManager *manager = [NSFileManager defaultManager];
  704. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  705. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  706. NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
  707. if ([manager fileExistsAtPath:urgencyFile]) {
  708. resultDic = [NSMutableDictionary dictionaryWithContentsOfFile:urgencyFile];
  709. [manager removeItemAtPath:urgencyFile error:nil];
  710. }
  711. self.urgencyDic = [NSMutableDictionary dictionary];
  712. return resultDic;
  713. }
  714. - (void)initialExceptionHandler {
  715. if (exception_switch == 1) {
  716. NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
  717. }
  718. }
  719. - (void)becomeObserver {
  720. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUrgencyFile) name:LoginOK_HandleUrgencyFile_Notification object:nil];
  721. }
  722. - (void)dealloc {
  723. [[NSNotificationCenter defaultCenter] removeObserver:self];
  724. }
  725. #ifdef SCANNER_ORDER
  726. -(void) setAddress:(NSString *)address
  727. {
  728. _address = address;
  729. _uploadurl = [address stringByAppendingPathComponent:URL_SCAN_UPLOAD];// [NSString stringWithFormat:@"%@%@",address,URL_SCAN_UPLOAD];
  730. NSString * file = [NSString stringWithFormat:URL_SCAN_DOWNLOAD,[RADataProvider getSiteName]];
  731. _downloadurl =[address stringByAppendingPathComponent:file] ; // [NSString stringWithFormat:@"%@%@",address,URL_SCAN_DOWNLOAD];
  732. }
  733. #endif
  734. #ifdef GOOGLE_ANALYTICS
  735. - (void)setUpGoogleAnalytics {
  736. // 初始化Google Analytics
  737. NSError *configureError;
  738. [[GGLContext sharedInstance] configureWithError:&configureError];
  739. if (configureError) {
  740. DebugLog(@"congigure googleAnalytics error: %@",configureError);
  741. }
  742. GAI *gai = [GAI sharedInstance];
  743. gai.trackUncaughtExceptions = YES;
  744. id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
  745. // Enable IDFA collection.
  746. tracker.allowIDFACollection = YES;
  747. // gai.dispatchInterval = 120;// 每隔 2 分钟调度一次数据
  748. // 调试使用
  749. // gai.logger.logLevel = kGAILogLevelVerbose;
  750. // [[GAI sharedInstance] setDryRun:YES];
  751. //
  752. }
  753. #endif
  754. //-(void)test_descrypt
  755. //{
  756. // sqlite3 *db = [iSalesDB get_db];
  757. //
  758. // int result= [iSalesDB AddExFunction:db];
  759. //
  760. // NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  761. // sqlite3_stmt * statement;
  762. //
  763. //
  764. // if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  765. // {
  766. //
  767. //
  768. // while (sqlite3_step(statement) == SQLITE_ROW)
  769. // {
  770. //
  771. //
  772. // char *url = (char*)sqlite3_column_text(statement, 0);
  773. // if(url==nil)
  774. // url="";
  775. // NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  776. // DebugLog(nsurl);
  777. //
  778. //
  779. //
  780. //
  781. // }
  782. // // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  783. //
  784. //
  785. // sqlite3_finalize(statement);
  786. // }
  787. //
  788. // [iSalesDB close_db:db];
  789. //}
  790. //
  791. //-(void)test_descrypt1
  792. //{
  793. // sqlite3 *db = [iSalesDB get_db];
  794. //
  795. // int result= [iSalesDB AddExFunction:db];
  796. //
  797. // NSString* sqlindex= @"CREATE INDEX hijk ON offline_contact (lower(company_name));";
  798. //
  799. // [iSalesDB execSql:sqlindex];
  800. ////
  801. //// NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  802. //// sqlite3_stmt * statement;
  803. ////
  804. ////
  805. ////
  806. //// if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  807. //// {
  808. ////
  809. ////
  810. //// while (sqlite3_step(statement) == SQLITE_ROW)
  811. //// {
  812. ////
  813. ////
  814. //// char *url = (char*)sqlite3_column_text(statement, 0);
  815. //// if(url==nil)
  816. //// url="";
  817. //// NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  818. //// DebugLog(nsurl);
  819. ////
  820. ////
  821. ////
  822. ////
  823. //// }
  824. //// // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  825. ////
  826. ////
  827. //// sqlite3_finalize(statement);
  828. //// }
  829. //
  830. // [iSalesDB close_db:db];
  831. //}
  832. - (void)applicationWillResignActive:(UIApplication *)application
  833. {
  834. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  835. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  836. }
  837. - (void)applicationDidEnterBackground:(UIApplication *)application
  838. {
  839. [self download_offline:false checkdiskspace:false];
  840. // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  841. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  842. #if defined(GOOGLE_ANALYTICS)
  843. NSTimeInterval timing = [[NSDate date] timeIntervalSinceDate:self.forgroundDate];
  844. self.forgroundDate = nil;
  845. [GoogleAnalyst trackTimingWithCategory:@"foreground" interval:timing name:@"user used time" label:nil];
  846. #endif
  847. }
  848. - (void)applicationWillEnterForeground:(UIApplication *)application
  849. {
  850. // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
  851. }
  852. - (void)applicationDidBecomeActive:(UIApplication *)application
  853. {
  854. if(self.download_task!=nil)
  855. [self download_offline:true checkdiskspace:false];
  856. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  857. self.forgroundDate = [NSDate date];
  858. #ifdef SCANNER_ORDER
  859. [RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
  860. configure.autoRemoveFinish = YES;
  861. }];
  862. if (!self.uploadManager) {
  863. self.uploadManager=[RAUploadManager sharedManager];
  864. }
  865. #endif
  866. }
  867. #ifdef SCANNER_ORDER
  868. -(RAUploadManager *)uploadManager
  869. {
  870. [RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
  871. configure.autoRemoveFinish = YES;
  872. }];
  873. if (!_uploadManager) {
  874. _uploadManager=[RAUploadManager sharedManager];
  875. }
  876. return _uploadManager;
  877. }
  878. #endif
  879. -(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
  880. {
  881. DebugLog(@"======================================");
  882. DebugLog(@"===== MEMORY WORRING ! ==========");
  883. DebugLog(@"======================================");
  884. }
  885. - (void)applicationWillTerminate:(UIApplication *)application
  886. {
  887. #ifdef SCANNER_ORDER
  888. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  889. [self saveUploadTasks];
  890. #endif
  891. }
  892. -(void) Logout
  893. {
  894. // 由于之前使用dispatch_async(dispatch_get_main_queue(), ^{}) 在用户切换时登出后刷新SideMenu User仍然显示
  895. dispatch_main_async_safe(^{
  896. MainViewController * main_vc= (MainViewController*)self.main_vc;
  897. [main_vc logoutOrder];
  898. [main_vc logoutCart];
  899. [main_vc logoutWish];
  900. [main_vc logoutContact];
  901. [main_vc logoutCategory];
  902. [main_vc logoutDocuments];
  903. [main_vc logoutPortfolio];
  904. #ifdef RA_NOTIFICATION
  905. [ActiveViewController Notify:@"SearchViewController" Message:RA_NOTIFICATION_CLEAR_DATA];
  906. #endif
  907. [main_vc hideMenu];
  908. [main_vc switchToHome];
  909. self.user = nil;
  910. self.password=nil;
  911. self.user_icon=nil;
  912. self.user_type = USER_ROLE_UNKNOWN;
  913. self.bLogin = false;
  914. self.contact_id=nil;
  915. self.customerInfo = nil;
  916. self.order_code = nil;
  917. [self.recent_model removeAllObjects];
  918. [self SetMode:nil];
  919. #ifdef SCANNER_ORDER
  920. self.available_price_group = nil;
  921. [RADataProvider default_price_group];
  922. #endif
  923. });
  924. }
  925. -(void)setOrder_code:(NSString *)order_code
  926. {
  927. _order_code = order_code;
  928. if(order_code==nil)
  929. NSLog(@"Clear order code");
  930. else
  931. NSLog(@"New order code %@",order_code);
  932. }
  933. - (void)checkLogin:(BOOL)reloadCurVC {
  934. [((MainViewController *)self.main_vc) checklogin:reloadCurVC];
  935. }
  936. //disable apn
  937. //-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  938. //{
  939. // self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
  940. // DebugLog(@"regisger success:%@",deviceToken);
  941. //
  942. // //注册成功,将deviceToken保存到应用服务器数据库中
  943. //}
  944. #pragma mark - background download
  945. -(bool)isdownloading:(NSString*) file
  946. {
  947. return true;
  948. }
  949. -(long long)getcurrentLength:(int) taskidx
  950. {
  951. int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
  952. return position;
  953. }
  954. -(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
  955. {
  956. //操作有两种,start stop;
  957. //结果有四种, wait , downloading, pause, finish
  958. dispatch_async(dispatch_get_main_queue(), ^{
  959. // debug;
  960. // NSString* file_name=[url lastPathComponent];
  961. //暂停<->开始转换
  962. // bool isdownloading = [self isdownloading:file_name];
  963. if (start)
  964. {//开始下载
  965. DebugLog(@"%d start",taskidx);
  966. self.current_task=taskidx;
  967. NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
  968. // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
  969. //
  970. //
  971. // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  972. //
  973. // //设置请求头(GET)
  974. // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  975. // [request setValue:range forHTTPHeaderField:@"Range"];
  976. //
  977. // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  978. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  979. //设置请求头(GET)
  980. NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  981. [request setValue:range forHTTPHeaderField:@"Range"];
  982. self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  983. }else{ //暂停
  984. DebugLog(@"%d pause",taskidx);
  985. [self.connection cancel];
  986. self.connection = nil;
  987. }
  988. });
  989. }
  990. -(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order params:(NSMutableDictionary*) add_params
  991. {
  992. assert(add_params[@"user"]!=nil);
  993. assert(add_params[@"password"]!=nil);
  994. // assert(add_params[@"contact_id"]!=nil);
  995. [self add_downloadlog:@"Begin sync, please wait."];
  996. [self add_downloadlog:@"Prepare upload data."];
  997. // NSArray* arr_order=[OLDataProvider enumOfflineOrder];
  998. NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order params:add_params];
  999. NSString* upfile=upjson[@"file"];
  1000. {
  1001. NSData* data = [NSData dataWithContentsOfFile: upfile];
  1002. // UIApplication * app = [UIApplication sharedApplication];
  1003. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  1004. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  1005. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  1006. if(add_params[@"user"]!=nil)
  1007. [params setValue:add_params[@"user"] forKey:@"user"];
  1008. // if(appDelegate.contact_id!=nil)
  1009. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  1010. if(add_params[@"password"]!=nil)
  1011. [params setValue:add_params[@"password"] forKey:@"password"];
  1012. #if TARGET_IPHONE_SIMULATOR//模拟器
  1013. [params setValue:@"simulator_uuid" forKey:@"idfv"];
  1014. #elif TARGET_OS_IPHONE//真机
  1015. UIDevice * dev = [UIDevice currentDevice];
  1016. NSUUID* uuid =dev.identifierForVendor;
  1017. [params setValue:uuid.UUIDString forKey:@"idfv"];
  1018. #endif
  1019. __weak typeof(self) weakSelf = self;
  1020. [NetworkUtils upload:data FileName:[upfile lastPathComponent] Params:params ToHost:URL_UPLOAD_OFFLINE Result:^(NSMutableDictionary *json) {
  1021. if([[json valueForKey:@"result"] intValue]==2)
  1022. {
  1023. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1024. // 清理数据库要放入线程中执行
  1025. NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  1026. if (out_of_stock_ids) {
  1027. [RAUtils message_alert:[NSString stringWithFormat:@"Below orders were not submitted because some models were out of stock. You can check from order history under online mode.\n %@",out_of_stock_ids] title:@"Warning" controller:self.main_vc];
  1028. }
  1029. [weakSelf add_downloadlog:@"Upload successful."];
  1030. // [iSalesDB disable_trigger]
  1031. [iSalesDB disable_trigger];
  1032. NSString* so_id=[RAConvertor arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  1033. [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  1034. [iSalesDB execSql:@"delete from wishlist"];
  1035. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  1036. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  1037. [iSalesDB execSql:@"delete from offline_portfolio"];
  1038. [iSalesDB execSql:@"delete from offline_pdf"];
  1039. [OLDataProvider offline_clear_PDFCache];
  1040. NSString* contactMap = json[@"contactMap"];
  1041. if(contactMap.length>0)
  1042. {
  1043. NSDictionary* contactjson = [RAConvertor string2dict:contactMap];
  1044. NSArray *keys= [contactjson allKeys];
  1045. //遍历keys
  1046. for(int i=0;i<[keys count];i++)
  1047. {
  1048. //得到当前key
  1049. NSString *key=[keys objectAtIndex:i];
  1050. //如果key不是pic,说明value是字符类型,比如name:Boris
  1051. NSString* value = [contactjson valueForKey:key];
  1052. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1053. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1054. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1055. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1056. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1057. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1058. }
  1059. }
  1060. // NSDictionary* contactjson= upjson[@"contact"];
  1061. // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1062. // NSDictionary* orderjson= upjson[@"order"];
  1063. // [iSalesDB enable_trigger]
  1064. [iSalesDB enable_trigger];
  1065. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1066. [defaults removeObjectForKey:@"Forcedownload"];
  1067. [defaults setBool:true forKey:@"Forcedownload"];
  1068. [defaults synchronize];
  1069. dispatch_async(dispatch_get_main_queue(), ^{
  1070. //下载函数要从主线程调用
  1071. [weakSelf download_offline:ver useInternalAddress:buseinternaladdress];
  1072. });
  1073. });
  1074. }
  1075. else
  1076. {
  1077. [weakSelf add_downloadlog:[json valueForKey:@"msg"]];
  1078. [weakSelf add_downloadlog:@"Sync canceled."];
  1079. [weakSelf.settingUI onSyncFinish];
  1080. }
  1081. } Progress:^(NSURLSessionTask *task, double progress) {
  1082. } DecryptHandler:nil];
  1083. // AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  1084. //
  1085. // serializer.timeoutInterval=300;
  1086. //
  1087. // NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_OFFLINE parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  1088. // [formData appendPartWithFileData:data name:@"upfile" fileName:[upfile lastPathComponent] mimeType:@"application/zip"];
  1089. // } error:nil];
  1090. //
  1091. //
  1092. //
  1093. // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  1094. //
  1095. // NSProgress *progress = nil;
  1096. //
  1097. // NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  1098. //
  1099. //
  1100. //
  1101. // if (error) {
  1102. //
  1103. // NSString* err_msg = [error localizedDescription];
  1104. // DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  1105. //
  1106. //
  1107. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  1108. //
  1109. // DebugLog(@"data string: %@",str);
  1110. // [self add_downloadlog:err_msg];
  1111. // [self add_downloadlog:@"Can not connect to server please try again."];
  1112. // [self.settingUI onSyncFinish];
  1113. //
  1114. // } else {
  1115. // DebugLog(@"response ");
  1116. //
  1117. //
  1118. //
  1119. // NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  1120. //
  1121. // // 再将NSData转为字符串
  1122. // NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  1123. //
  1124. // // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  1125. //
  1126. // DebugLog(@"data string: %@",jsonStr);
  1127. //
  1128. // NSDictionary* json = responseObject;
  1129. //
  1130. //
  1131. // if([[json valueForKey:@"result"] intValue]==2)
  1132. // {
  1133. // NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  1134. // if (out_of_stock_ids) {
  1135. // [RAUtils message_alert:[NSString stringWithFormat:@"Below orders were not submitted because some models were out of stock. You can check from order history under online mode.\n %@",out_of_stock_ids] title:@"Warning" controller:self.main_vc];
  1136. // }
  1137. //
  1138. // [self add_downloadlog:@"Upload successful."];
  1139. // [iSalesDB disable_trigger]
  1140. // NSString* so_id=[RAUtils arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  1141. //
  1142. // [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  1143. // [iSalesDB execSql:@"delete from wishlist"];
  1144. // [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  1145. // [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  1146. // [iSalesDB execSql:@"delete from offline_portfolio"];
  1147. // [iSalesDB execSql:@"delete from offline_pdf"];
  1148. // [OLDataProvider offline_clear_PDFCache];
  1149. //
  1150. // NSString* contactMap = json[@"contactMap"];
  1151. // if(contactMap.length>0)
  1152. // {
  1153. // NSDictionary* contactjson = [RAUtils string2dict:contactMap];
  1154. // NSArray *keys= [contactjson allKeys];
  1155. // //遍历keys
  1156. // for(int i=0;i<[keys count];i++)
  1157. // {
  1158. // //得到当前key
  1159. // NSString *key=[keys objectAtIndex:i];
  1160. // //如果key不是pic,说明value是字符类型,比如name:Boris
  1161. // NSString* value = [contactjson valueForKey:key];
  1162. //
  1163. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1164. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1165. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1166. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1167. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1168. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1169. //
  1170. // }
  1171. // }
  1172. // // NSDictionary* contactjson= upjson[@"contact"];
  1173. // // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1174. // // NSDictionary* orderjson= upjson[@"order"];
  1175. //
  1176. // [iSalesDB enable_trigger]
  1177. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1178. // [defaults removeObjectForKey:@"Forcedownload"];
  1179. // [defaults setBool:true forKey:@"Forcedownload"];
  1180. // [defaults synchronize];
  1181. //
  1182. // [self download_offline:ver useInternalAddress:buseinternaladdress];
  1183. //
  1184. // }
  1185. // else
  1186. // {
  1187. // [self add_downloadlog:[json valueForKey:@"msg"]];
  1188. // [self add_downloadlog:@"Sync canceled."];
  1189. // [self.settingUI onSyncFinish];
  1190. // }
  1191. //
  1192. //
  1193. // }
  1194. // // [waitalert dismissViewControllerAnimated:YES completion:nil];
  1195. // }];
  1196. //
  1197. //
  1198. //
  1199. //
  1200. //
  1201. //
  1202. //
  1203. // [uploadTask resume];
  1204. }
  1205. return;
  1206. }
  1207. -(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
  1208. {
  1209. NSString *plistPath = [RAUtils get_config_path];
  1210. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1211. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1212. {
  1213. ver= nil;
  1214. [self add_downloadlog:@"App required a fully sync."];
  1215. }
  1216. if(self.downloading)
  1217. return;
  1218. self.downloading=true;
  1219. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1220. NSString* pvid = [defaults stringForKey:@"vid"] ;
  1221. [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
  1222. [RANetwork request_new_offline_ticket:ver useInternalAddress:false vid:pvid completionHandler:^(NSMutableDictionary *result) {
  1223. NSMutableDictionary* json= result;
  1224. if([json[@"result"] intValue]!=2)
  1225. {
  1226. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1227. [self.settingUI onSyncFinish];
  1228. // self.downloadlog=nil;
  1229. self.downloading=false;
  1230. return;
  1231. }
  1232. else
  1233. {
  1234. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1235. __block NSMutableDictionary* download_json=nil;
  1236. // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1237. NSString* downSerial=[json valueForKey:@"downSerial"];
  1238. [defaults removeObjectForKey:@"downSerial"];
  1239. [defaults setValue:downSerial forKey:@"downSerial"];
  1240. [defaults synchronize];
  1241. // sleep(3);
  1242. //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1243. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1244. // int count=0;
  1245. // // __block bool preparing = true;
  1246. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1247. // {
  1248. // sleep(RETRY_DELAY);
  1249. //
  1250. //
  1251. // count++;
  1252. //// download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1253. //
  1254. // [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1255. // download_json=result;
  1256. // }];
  1257. //
  1258. //
  1259. //
  1260. //
  1261. // }
  1262. [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1263. download_json=result;
  1264. if([download_json[@"result"] intValue]!=RESULT_TRUE)
  1265. {
  1266. [self add_downloadlog:download_json[@"err_msg"]];
  1267. [self add_downloadlog:@"Download Abort."];
  1268. dispatch_async(dispatch_get_main_queue(), ^{
  1269. // self.downloadlog=nil;
  1270. self.downloading=false;
  1271. [self.settingUI onSyncFinish];
  1272. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1273. [defaults removeObjectForKey:@"Forcedownload"];
  1274. [defaults setBool:true forKey:@"Forcedownload"];
  1275. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1276. // [defaults removeObjectForKey:@"downSerial"];
  1277. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1278. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1279. [defaults synchronize];
  1280. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1281. });
  1282. return;
  1283. }
  1284. //服务器准备数据完毕,进入处理数据逻辑。
  1285. if([download_json[@"request_count"] intValue]>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1286. {
  1287. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1288. dispatch_async(dispatch_get_main_queue(), ^{
  1289. // self.downloadlog=nil;
  1290. self.downloading=false;
  1291. });
  1292. dispatch_async(dispatch_get_main_queue(), ^{
  1293. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1294. });
  1295. [self.settingUI onSyncFinish];
  1296. return;
  1297. //一直没取到json,出错处理
  1298. }
  1299. else
  1300. {
  1301. if([download_json[@"count"] intValue]==0)
  1302. {
  1303. //没有找到更新包,当前是最新版本
  1304. [self add_downloadlog:@"You are up-to-date!"];
  1305. dispatch_async(dispatch_get_main_queue(), ^{
  1306. // self.downloadlog=nil;
  1307. self.downloading=false;
  1308. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1309. [defaults removeObjectForKey:@"Forcedownload"];
  1310. [defaults setBool:FALSE forKey:@"Forcedownload"];
  1311. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1312. // [defaults removeObjectForKey:@"downSerial"];
  1313. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1314. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1315. [defaults synchronize];
  1316. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1317. });
  1318. // dispatch_async(dispatch_get_main_queue(), ^{
  1319. //
  1320. // });
  1321. [self.settingUI onSyncFinish];
  1322. return;
  1323. }
  1324. else
  1325. {
  1326. [self add_downloadlog:@"Find a new version, downloading..."];
  1327. self.download_task = [download_json mutableCopy];
  1328. // self.download_task[@"abcdef"]=@"abcdef";
  1329. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1330. [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1331. [self download_offline:true checkdiskspace:true];
  1332. return;
  1333. }
  1334. }
  1335. }];
  1336. }
  1337. }];
  1338. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1339. //
  1340. //
  1341. //
  1342. //
  1343. // NSMutableDictionary* json=[[RANetwork check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
  1344. //
  1345. //
  1346. // if([json[@"result"] intValue]!=2)
  1347. // {
  1348. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1349. // [self.settingUI onSyncFinish];
  1350. // dispatch_async(dispatch_get_main_queue(), ^{
  1351. // // self.downloadlog=nil;
  1352. // self.downloading=false;
  1353. // });
  1354. // return;
  1355. // }
  1356. //
  1357. //
  1358. // dispatch_async(dispatch_get_main_queue(), ^{
  1359. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1360. // });
  1361. //
  1362. //
  1363. // NSMutableDictionary* download_json=nil;
  1364. //
  1365. // // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1366. // NSString* downSerial=[json valueForKey:@"downSerial"];
  1367. //
  1368. // [defaults removeObjectForKey:@"downSerial"];
  1369. // [defaults setValue:downSerial forKey:@"downSerial"];
  1370. //
  1371. // [defaults synchronize];
  1372. //
  1373. // // sleep(3);
  1374. // //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1375. //
  1376. //
  1377. // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1378. // int count=0;
  1379. // // __block bool preparing = true;
  1380. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1381. // {
  1382. // sleep(RETRY_DELAY);
  1383. //
  1384. //
  1385. // count++;
  1386. // download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1387. //
  1388. //
  1389. //
  1390. //
  1391. // }
  1392. //
  1393. // //服务器准备数据完毕,进入处理数据逻辑。
  1394. // if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1395. // {
  1396. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1397. // dispatch_async(dispatch_get_main_queue(), ^{
  1398. // // self.downloadlog=nil;
  1399. // self.downloading=false;
  1400. // });
  1401. // dispatch_async(dispatch_get_main_queue(), ^{
  1402. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1403. // });
  1404. // [self.settingUI onSyncFinish];
  1405. // return;
  1406. // //一直没取到json,出错处理
  1407. // }
  1408. // else
  1409. // {
  1410. // if([download_json[@"count"] intValue]==0)
  1411. // {
  1412. // //没有找到更新包,当前是最新版本
  1413. // [self add_downloadlog:@"You are up-to-date!"];
  1414. // dispatch_async(dispatch_get_main_queue(), ^{
  1415. // // self.downloadlog=nil;
  1416. // self.downloading=false;
  1417. // });
  1418. // dispatch_async(dispatch_get_main_queue(), ^{
  1419. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1420. // });
  1421. // [self.settingUI onSyncFinish];
  1422. // return;
  1423. // }
  1424. // else
  1425. // {
  1426. // [self add_downloadlog:@"Find a new version, downloading..."];
  1427. // self.download_task = [download_json mutableCopy];
  1428. // // self.download_task[@"abcdef"]=@"abcdef";
  1429. // long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1430. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1431. // [self download_offline:true checkdiskspace:true];
  1432. // return;
  1433. // }
  1434. //
  1435. // }
  1436. //
  1437. // });
  1438. }
  1439. #ifdef SCANNER_ORDER
  1440. //- (NSString *)price0_name
  1441. //{
  1442. // if(_price0_name.length==0)
  1443. // {
  1444. // return @"DDP";
  1445. // }
  1446. // else
  1447. // return _price0_name;
  1448. //}
  1449. //- (NSString *)price1_name
  1450. //{
  1451. // if(_price1_name.length==0)
  1452. // {
  1453. // return @"Unit Price";
  1454. // }
  1455. // else
  1456. // return _price1_name;
  1457. //}
  1458. //- (NSString *)price2_name
  1459. //{
  1460. // if(_price2_name.length==0)
  1461. // {
  1462. // return @"Special";
  1463. // }
  1464. // else
  1465. // return _price2_name;
  1466. //}
  1467. //- (NSString *)price3_name
  1468. //{
  1469. // if(_price3_name.length==0)
  1470. // {
  1471. // return @"Net Price";
  1472. // }
  1473. // else
  1474. // return _price3_name;
  1475. //}
  1476. #endif
  1477. -(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
  1478. {
  1479. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1480. bool forcedownload = [defaults boolForKey:@"Forcedownload"];
  1481. if(forcedownload|| ver==nil)
  1482. {
  1483. [self download_offline:ver useInternalAddress:buseinternaladdress];
  1484. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1485. syncVC.action_string=@"Download";
  1486. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1487. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1488. navi.modalInPresentation = true;
  1489. navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态,自己看看是哪种
  1490. [parent presentViewController:navi animated:YES completion:^{
  1491. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1492. DebugLog(@"about present.........");
  1493. // self.btop = false;
  1494. // <#code#>
  1495. }];
  1496. }
  1497. else
  1498. {
  1499. NSArray* arr_order=nil;
  1500. arr_order=[OLDataProvider enumOfflineOrder];
  1501. // if(arr_order.count>0)
  1502. // {
  1503. //
  1504. // {
  1505. // SelectUploadOrderViewController * vc =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
  1506. // vc.returnValue = ^(NSArray* SelectedOrder){
  1507. //
  1508. // [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:SelectedOrder];
  1509. // SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1510. // syncVC.action_string=@"Download";
  1511. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1512. //
  1513. //
  1514. //
  1515. //
  1516. //
  1517. // // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1518. //
  1519. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1520. // [parent presentViewController:navi animated:YES completion:^{
  1521. //
  1522. // // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1523. //
  1524. // DebugLog(@"about present.........");
  1525. //
  1526. // // self.btop = false;
  1527. // // <#code#>
  1528. // }];
  1529. // };
  1530. //
  1531. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc] ;
  1532. //
  1533. //
  1534. //
  1535. //
  1536. //
  1537. //
  1538. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1539. // [parent presentViewController:navi animated:YES completion:^{
  1540. //
  1541. //
  1542. // }];
  1543. // }
  1544. //
  1545. //
  1546. // }
  1547. // else
  1548. // {
  1549. NSMutableDictionary* add_params=[NSMutableDictionary new];
  1550. add_params[@"user"]=self.user;
  1551. add_params[@"password"]=self.password;
  1552. add_params[@"contact_id"]=self.contact_id;
  1553. [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order params:add_params];
  1554. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1555. syncVC.action_string=@"Download";
  1556. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1557. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1558. [parent presentViewController:navi animated:YES completion:^{
  1559. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1560. DebugLog(@"about present.........");
  1561. // self.btop = false;
  1562. // <#code#>
  1563. }];
  1564. // }
  1565. }
  1566. }
  1567. -(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
  1568. {
  1569. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  1570. if(start)
  1571. {
  1572. dispatch_async(dispatch_get_main_queue(), ^{
  1573. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1574. });
  1575. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1576. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1577. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1578. long long needsize = size+500;
  1579. if(needsize>freespace &&checkdiskspace)
  1580. {
  1581. //size not enough.
  1582. NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
  1583. [self add_downloadlog:space];
  1584. [self.settingUI onSyncFinish];
  1585. return ;
  1586. }
  1587. NSString* temp = NSTemporaryDirectory();
  1588. NSString * ver = self.download_task[@"ver"];
  1589. NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
  1590. //创建版本临时目录
  1591. NSFileManager* fileManager = [NSFileManager defaultManager];
  1592. BOOL bdir=YES;
  1593. if(! [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
  1594. {
  1595. NSError *error = nil;
  1596. bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
  1597. if(!bsuccess)
  1598. DebugLog(@"Create temp folder failed");
  1599. // if(bsuccess)
  1600. // {
  1601. // sqlite3 *db = [self get_db];
  1602. //
  1603. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  1604. // [iSalesDB close_db:db];
  1605. // }
  1606. }
  1607. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
  1608. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1609. if(! [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
  1610. {
  1611. NSError *error = nil;
  1612. bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1613. if(!bsuccess)
  1614. DebugLog(@"Create cache folder failed");
  1615. }
  1616. NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
  1617. NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
  1618. // if(! [fileManager fileExistsAtPath:resource isDirectory:&bdir])
  1619. // {
  1620. //
  1621. // NSError *error = nil;
  1622. // bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
  1623. //
  1624. // if(!bsuccess)
  1625. // DebugLog(@"Create resource folder failed");
  1626. //
  1627. // }
  1628. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1629. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  1630. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  1631. NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
  1632. // tempdb=[documents stringByAppendingPathComponent:DBNAME];
  1633. NSError *error = nil;
  1634. bdir=NO;
  1635. if(! [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
  1636. {
  1637. // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
  1638. if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
  1639. {
  1640. DebugLog(@"copy database failed");
  1641. }
  1642. }
  1643. bdir=YES;
  1644. error=nil;
  1645. int count = [[self.download_task valueForKey:@"count"] intValue];
  1646. bool alldone=true;
  1647. bool trouble=false;
  1648. bool response = false;
  1649. for (int i = 0;i<count;i++)
  1650. {
  1651. NSMutableDictionary* itemjson = [[self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]] mutableCopy];
  1652. NSString* url = [itemjson valueForKey:@"url"];
  1653. NSString* type = [itemjson valueForKey:@"type"];
  1654. {
  1655. #ifdef DEBUG
  1656. //调试模式下跳过下载图片
  1657. if([type isEqualToString:@"img"])
  1658. {
  1659. itemjson[@"status"]=@"finish";
  1660. continue;
  1661. }
  1662. #endif
  1663. }
  1664. NSString* status = itemjson[@"status"];
  1665. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1666. if(! [status isEqualToString:@"finish"])
  1667. {
  1668. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1669. {
  1670. [self handle_download:url start:start type:type taskid:i];
  1671. alldone=false;
  1672. break;
  1673. }
  1674. else
  1675. {
  1676. alldone=false;
  1677. trouble=true;
  1678. response = [itemjson[@"response"] boolValue];
  1679. break;
  1680. }
  1681. }
  1682. }
  1683. if(trouble)
  1684. {
  1685. NSString* msg =@"offline sync got some trouble, sync canceled.";
  1686. if(response==false)
  1687. {
  1688. msg=@"Cannot connect to server, please check your network.";
  1689. }
  1690. [self add_downloadlog:msg];
  1691. dispatch_async(dispatch_get_main_queue(), ^{
  1692. // self.downloadlog=nil;
  1693. self.downloading=false;
  1694. });
  1695. [self.settingUI onSyncFinish];
  1696. }
  1697. else if(alldone)
  1698. {
  1699. [self add_downloadlog:@"Finalizing download..."];
  1700. //全部下载完成;
  1701. //写入当前版本
  1702. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1703. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1704. NSString* lastsync = [formatter stringFromDate:[NSDate date]];
  1705. NSString* ver= self.download_task[@"ver"];
  1706. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1707. NSString *cachefolder = [paths objectAtIndex:0];
  1708. NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
  1709. //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
  1710. if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
  1711. {
  1712. DebugLog(@"move image folder failed");
  1713. [self add_downloadlog:@"move image folder failed"];
  1714. trouble=true;
  1715. }
  1716. else
  1717. {
  1718. DebugLog(@"move image folder successful");
  1719. }
  1720. error=nil;
  1721. // copy temp db to cache.
  1722. if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
  1723. {
  1724. if(![fileManager removeItemAtPath:database_path error:nil])
  1725. {
  1726. DebugLog(@"delete database failed");
  1727. }
  1728. else
  1729. {
  1730. if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1731. {
  1732. DebugLog(@"copy database failed");
  1733. [self add_downloadlog:@"copy database failed"];
  1734. trouble=true;
  1735. }
  1736. else{
  1737. //debug
  1738. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1739. [fileManager removeItemAtPath:tempdb error:nil];
  1740. // [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
  1741. }
  1742. }
  1743. }
  1744. else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1745. {
  1746. DebugLog(@"copy database failed");
  1747. //debug;
  1748. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1749. [fileManager removeItemAtPath:tempdb error:nil];
  1750. [self add_downloadlog:@"copy database failed"];
  1751. trouble=true;
  1752. }
  1753. // if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
  1754. // {
  1755. // DebugLog(@"move db file failed");
  1756. // }
  1757. // else
  1758. // {
  1759. // DebugLog(@"move db file successful");
  1760. // }
  1761. error=nil;
  1762. if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
  1763. {
  1764. DebugLog(@"move data folder failed");
  1765. [self add_downloadlog:@"move data folder failed"];
  1766. trouble=true;
  1767. }
  1768. else
  1769. {
  1770. DebugLog(@"move data folder successful");
  1771. }
  1772. dispatch_async(dispatch_get_main_queue(), ^{
  1773. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1774. });
  1775. if(trouble)
  1776. {
  1777. [self add_downloadlog:@"offline sync failed."];
  1778. // 尚缺更新失败还原逻辑。
  1779. }
  1780. else
  1781. {
  1782. [self add_downloadlog:@"offline sync complete."];
  1783. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1784. [defaults removeObjectForKey:@"OfflineVer"];
  1785. [defaults setValue:ver forKey:@"OfflineVer"];
  1786. [defaults removeObjectForKey:@"LastSync"];
  1787. [defaults setValue:lastsync forKey:@"LastSync"];
  1788. [defaults removeObjectForKey:@"vid"];
  1789. [defaults setValue:self.vid forKey:@"vid"];
  1790. [defaults removeObjectForKey:@"Forcedownload"];
  1791. NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1792. [defaults removeObjectForKey:@"downSerial"];
  1793. [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1794. [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1795. [defaults synchronize];
  1796. NSString *plistPath = [RAUtils get_config_path];
  1797. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1798. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1799. {
  1800. config_list[@"NEED_FULLY_SYNC"] = @"false";
  1801. [config_list writeToFile:plistPath atomically:YES];
  1802. }
  1803. [RANetwork request_complete_offline_ticket:downSerial completionHandler:^(NSMutableDictionary *result) {
  1804. }];
  1805. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1806. //
  1807. //
  1808. // //debug
  1809. //// NSDictionary* editor_json = [RANetwork finish_download_Offline:downSerial];
  1810. // [RANetwork finish_download_Offline:downSerial];
  1811. //
  1812. //
  1813. // });
  1814. }
  1815. dispatch_async(dispatch_get_main_queue(), ^{
  1816. // self.downloadlog=nil;
  1817. self.downloading=false;
  1818. self.download_task=nil;
  1819. self.vid=nil;
  1820. [self.settingUI onSyncFinish];
  1821. });
  1822. }
  1823. }
  1824. else
  1825. {
  1826. int count = [[self.download_task valueForKey:@"count"] intValue];
  1827. for (int i = 0;i<count;i++)
  1828. {
  1829. NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
  1830. NSString* url = [itemjson valueForKey:@"url"];
  1831. NSString* type = [itemjson valueForKey:@"type"];
  1832. NSString* status = itemjson[@"status"];
  1833. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1834. if(! [status isEqualToString:@"finish"])
  1835. {
  1836. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1837. {
  1838. [self handle_download:url start:start type:type taskid:i];
  1839. break;
  1840. }
  1841. }
  1842. }
  1843. dispatch_async(dispatch_get_main_queue(), ^{
  1844. self.downloading=false;
  1845. });
  1846. }
  1847. }
  1848. -(void) add_downloadlog:(NSString*) newtext
  1849. {
  1850. // if(!self.downloading)
  1851. // return;
  1852. dispatch_async(dispatch_get_main_queue(), ^{
  1853. NSString* date;
  1854. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1855. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1856. date = [formatter stringFromDate:[NSDate date]];
  1857. if(newtext.length<=0)
  1858. return;
  1859. NSString* text = self.downloadlog;
  1860. if(text.length==0)
  1861. text=@"";
  1862. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  1863. self.downloadlog = text;
  1864. [self.settingUI onLogUpdate];
  1865. });
  1866. }
  1867. -(int)unpack
  1868. {
  1869. //return;
  1870. //DebugLog(_fileName);
  1871. ///Users/Ray/Library/Developer/CoreSimulator/Devices/0852B217-599B-41C2-95BA-4755B02B7FA0/data/Containers/Data/Application/FC6AC5D0-2ADF-4A3B-935D-059078622031/Library/Caches/apache-tomcat-8.0.22.zip
  1872. //文件路径
  1873. // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  1874. NSString* temp = NSTemporaryDirectory();
  1875. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1876. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
  1877. NSString * ver = self.download_task[@"ver"];
  1878. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
  1879. NSString *zipFile = [temp stringByAppendingPathComponent:location];
  1880. ZipArchive* zip = [[ZipArchive alloc] init];
  1881. // filename stringByDeletingPathExtension
  1882. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1883. // NSString *cachefolder = [paths objectAtIndex:0];
  1884. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1885. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1886. //
  1887. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1888. // NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  1889. //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
  1890. // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
  1891. DebugLog(@"path: %@",unZipTo);
  1892. if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
  1893. BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
  1894. if( NO==result )
  1895. {
  1896. // int aaa=0;
  1897. //解压失败
  1898. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1899. if(freespace<=10)
  1900. {
  1901. return UNZIP_NO_SPACE;
  1902. }
  1903. [zip UnzipCloseFile];
  1904. //文件损坏,删除文件重试
  1905. NSFileManager* fileManager=[NSFileManager defaultManager];
  1906. //debug
  1907. // BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
  1908. [fileManager removeItemAtPath:zipFile error:nil];
  1909. [fileManager removeItemAtPath:unZipTo error:nil];
  1910. return UNZIP_FILE_DAMAGE;
  1911. }
  1912. else
  1913. {
  1914. [zip UnzipCloseFile];
  1915. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
  1916. NSFileManager *fileManager = [NSFileManager defaultManager];
  1917. [fileManager removeItemAtPath:zipFile error:nil];
  1918. return UNZIP_SUCCESS;
  1919. //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
  1920. }
  1921. //[zip UnzipCloseFile];
  1922. }
  1923. else
  1924. {
  1925. //打开文件失败,通常是文件路径有问题或密码错误。
  1926. return UNZIP_OPEN_FAILED;
  1927. // NSFileManager *fileManager = [NSFileManager defaultManager];
  1928. // [fileManager removeItemAtPath:zipFile error:nil];
  1929. }
  1930. // [zip release];
  1931. }
  1932. #pragma mark - NSURLConnectionDelegate
  1933. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  1934. DebugLog(@"%d error message:%@",self.current_task,error);
  1935. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1936. // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
  1937. currenttask[@"status"] = @"pause";
  1938. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1939. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1940. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1941. // self.currentLength = 0;
  1942. // self.fileLength = 0;
  1943. [self.fileHandle closeFile];
  1944. self.fileHandle = nil;
  1945. [self.connection cancel];
  1946. self.connection = nil;
  1947. [self download_offline:true checkdiskspace:false];
  1948. }
  1949. #pragma mark - NSURLConnectionDataDelegate
  1950. /**
  1951. *请求失败
  1952. */
  1953. /**
  1954. *接收到服务器的响应
  1955. */
  1956. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  1957. NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
  1958. if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
  1959. DebugLog(@"%d begin",self.current_task);
  1960. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1961. //获取下载文件大小
  1962. // self.fileLength = response.expectedContentLength;
  1963. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1964. //获取文件名
  1965. //self.fileName = response.suggestedFilename;
  1966. currenttask[@"fileName"] = response.suggestedFilename;
  1967. currenttask[@"response"] = @"true";
  1968. [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
  1969. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1970. //文件路径
  1971. NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
  1972. NSString * ver = self.download_task[@"ver"];
  1973. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
  1974. NSString *filePath = [temp stringByAppendingPathComponent:location];
  1975. DebugLog(@"save to: %@",filePath);
  1976. if (position>0) {
  1977. //不需要创建文件;
  1978. //创建一个用来写数据的文件句柄
  1979. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1980. return;
  1981. }
  1982. // 第一次获取的才是文件正确大小
  1983. currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
  1984. //创建一个空的文件到沙盒
  1985. NSFileManager *fileManager = [NSFileManager defaultManager];
  1986. [fileManager createFileAtPath:filePath contents:nil attributes:nil];
  1987. //创建一个用来写数据的文件句柄
  1988. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1989. }else{
  1990. //debug 这里缺少文件的情况还没处理
  1991. [self.connection cancel];
  1992. self.connection = nil;
  1993. DebugLog(@"该文件不存在");
  1994. NSString* str_status=[NSString stringWithFormat:@"Server return %d.",(int)httpresponse.statusCode];
  1995. [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
  1996. [self add_downloadlog:str_status];
  1997. }
  1998. }
  1999. /**
  2000. *接收到服务器返回的数据(可能被调用多次)
  2001. */
  2002. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  2003. //移动到文件末尾
  2004. [self.fileHandle seekToEndOfFile];
  2005. //写入数据到文件
  2006. [self.fileHandle writeData:data];
  2007. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  2008. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  2009. position += data.length;
  2010. currenttask[@"position"] = [NSNumber numberWithLongLong:position];
  2011. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  2012. //更新画面中的进度
  2013. int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
  2014. double progress = (double)position/fileLength;
  2015. self.file_progress = progress;
  2016. [self.settingUI onProgressUpdate];
  2017. }
  2018. /**
  2019. *服务器返回数据完了
  2020. */
  2021. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  2022. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  2023. [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
  2024. DebugLog(@"%d finish",self.current_task);
  2025. currenttask[@"position"] = [NSNumber numberWithLongLong:0];
  2026. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  2027. // self.currentLength = 0;
  2028. // self.fileLength = 0;
  2029. [self.fileHandle closeFile];
  2030. self.fileHandle = nil;
  2031. int result=[self unpack];
  2032. NSString* temp = NSTemporaryDirectory();
  2033. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  2034. NSString * ver = self.download_task[@"ver"];
  2035. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  2036. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  2037. switch (result) {
  2038. case UNZIP_FILE_DAMAGE:
  2039. {
  2040. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  2041. currenttask[@"status"] = @"pause";
  2042. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  2043. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  2044. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  2045. // self.currentLength = 0;
  2046. // self.fileLength = 0;
  2047. [self.fileHandle closeFile];
  2048. self.fileHandle = nil;
  2049. [self.connection cancel];
  2050. self.connection = nil;
  2051. break;
  2052. }
  2053. case UNZIP_SUCCESS:
  2054. {
  2055. NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
  2056. if([type isEqualToString:@"img"])
  2057. {
  2058. NSString* parent_path = self.download_task[@"path"];
  2059. if(parent_path.length==0)
  2060. parent_path=@"";
  2061. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  2062. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  2063. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
  2064. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  2065. BOOL bdir=YES;
  2066. NSError *error = nil;
  2067. if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
  2068. {
  2069. bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  2070. if(!bsuccess)
  2071. DebugLog(@"Create temp folder failed");
  2072. }
  2073. error=nil;
  2074. // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
  2075. // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
  2076. // NSError *error = nil;
  2077. // NSURL* uf=[NSURL fileURLWithPath:imagecache];
  2078. // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
  2079. // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
  2080. // backupItemName:backup
  2081. // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
  2082. // resultingItemURL:nil error:&error])
  2083. if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
  2084. // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
  2085. {
  2086. DebugLog(@"move image folder failed");
  2087. }
  2088. else
  2089. {
  2090. currenttask[@"status"] = @"finish";
  2091. DebugLog(@"move image folder successful");
  2092. }
  2093. }
  2094. else if([type isEqualToString:@"sql"])
  2095. {
  2096. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  2097. NSString * ver = self.download_task[@"ver"];
  2098. NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
  2099. tempdb=[temp stringByAppendingPathComponent:tempdb];
  2100. sqlite3* tdb=[iSalesDB get_db_at:tempdb];
  2101. [self add_downloadlog:@"updating local database..."];
  2102. @try {
  2103. char *errmsg=NULL;
  2104. // [iSalesDB disable_trigger]
  2105. [iSalesDB disable_trigger];
  2106. if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
  2107. {
  2108. sqlite3_exec(tdb, "drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;drop trigger if exists offline_portfolio_insert;drop trigger if exists offline_portfolio_update;drop trigger if exists offline_portfolio_delete;drop trigger if exists offline_pdf_insert;drop trigger if exists offline_pdf_update;drop trigger if exists offline_pdf_delete;offline_pdf;", NULL, NULL, &errmsg);
  2109. sqlite3_free(errmsg);
  2110. DebugLog(@"开启事务");
  2111. NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
  2112. NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
  2113. int count = [orderjson[@"count"] intValue];
  2114. for(int i=0;i<count;i++)
  2115. {
  2116. NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
  2117. NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
  2118. NSError *error = nil;
  2119. NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
  2120. //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
  2121. if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
  2122. {
  2123. //throw exception;
  2124. if(errmsg==nil)
  2125. errmsg="Unknown error.";
  2126. NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
  2127. [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
  2128. }
  2129. sqlite3_free(errmsg);
  2130. }
  2131. sqlite3_exec(tdb, "CREATE TRIGGER if not exists wishlist_insert after insert on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists wishlist_update after update on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists wishlist_delete after DELETE ON wishlist BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_pdf_insert after insert on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_pdf_update after update on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_pdf_delete after DELETE ON offline_pdf BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_portfolio_insert after insert on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_portfolio_update after update on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_portfolio_delete after DELETE ON offline_portfolio BEGIN select offline_dirty(); END;", NULL, NULL, &errmsg);
  2132. }
  2133. //提交事务
  2134. if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
  2135. DebugLog(@"提交事务");
  2136. sqlite3_free(errmsg);
  2137. }
  2138. [self add_downloadlog:@"updating local database successful"];
  2139. currenttask[@"status"] = @"finish";
  2140. }
  2141. @catch (NSException *exception) {
  2142. char *errmsg=NULL;
  2143. [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
  2144. [self add_downloadlog:@"updating local database failed rollback..."];
  2145. if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
  2146. DebugLog(@"回滚事务");
  2147. }
  2148. else
  2149. {
  2150. [self add_downloadlog:@"rollback failed."];
  2151. }
  2152. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  2153. currenttask[@"status"] = @"pause";
  2154. //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  2155. currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
  2156. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  2157. // self.currentLength = 0;
  2158. // self.fileLength = 0;
  2159. [self.fileHandle closeFile];
  2160. self.fileHandle = nil;
  2161. [self.connection cancel];
  2162. self.connection = nil;
  2163. //break;
  2164. }
  2165. @finally {
  2166. // [iSalesDB enable_trigger]
  2167. [iSalesDB enable_trigger];
  2168. sqlite3_close(tdb);
  2169. // [iSalesDB close_db:tdb];
  2170. // [self SelectData];
  2171. }
  2172. }
  2173. else if([type isEqualToString:@"script"])
  2174. {
  2175. currenttask[@"status"] = @"finish";
  2176. }
  2177. else if([type isEqualToString:@"resource"])
  2178. {
  2179. currenttask[@"status"] = @"finish";
  2180. }
  2181. // debug
  2182. // int c=self.current_task+1;
  2183. // double t=[ self.download_task[@"count"] doubleValue];
  2184. double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
  2185. self.overall_progress = oprogress;
  2186. [self.settingUI onProgressUpdate];
  2187. break;
  2188. }
  2189. case UNZIP_NO_SPACE:
  2190. {
  2191. [self add_downloadlog:@"Disk space not enough."];
  2192. break;
  2193. }
  2194. case UNZIP_OPEN_FAILED:
  2195. {
  2196. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
  2197. break;
  2198. }
  2199. default:
  2200. break;
  2201. }
  2202. [self download_offline:true checkdiskspace:false];
  2203. }
  2204. -(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
  2205. {
  2206. RAPDFViewController *ViewController = [[UIStoryboard storyboardWithName:@"wkweb" bundle:nil] instantiateViewControllerWithIdentifier:@"RAPDFViewController"];
  2207. ViewController.url = url;
  2208. ViewController.canSave = false;
  2209. ViewController.mail_content = content;
  2210. if(soid==nil)
  2211. soid =@"";
  2212. if(company==nil)
  2213. company =@"";
  2214. ViewController.save_name =soid;
  2215. NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
  2216. if(send_to.length>0)
  2217. {
  2218. arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2219. // customer_email compo
  2220. // [send_to addObject:customer_email];
  2221. }
  2222. ViewController.mail_to = arrsend_to;
  2223. #if defined(BUILD_NPD) || defined(BUILD_USAI)|| defined (BUILD_CONTRAST)
  2224. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];//[arr_subject componentsJoinedByString:@" : "];
  2225. if (self.user_type == USER_ROLE_CUSTOMER && ![RASingleton sharedInstance].currentOrderIsMerged) {
  2226. NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
  2227. subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
  2228. }
  2229. #else
  2230. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];
  2231. #endif
  2232. ViewController.mail_subject = subject;
  2233. // NSString* subject;
  2234. // if (company.length==0) {
  2235. // NSString* cur_time =[RAUtils current_date];
  2236. // subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
  2237. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  2238. // NSString* customer_email= [appDelegate.customerInfo valueForKey:@"customer_email"];
  2239. //
  2240. //
  2241. // NSMutableArray* send_to = [[NSMutableArray alloc]init];
  2242. // if(customer_email.length>0)
  2243. // {
  2244. // send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2245. // // customer_email compo
  2246. // // [send_to addObject:customer_email];
  2247. // }
  2248. // ViewController.mail_to = send_to;
  2249. // }
  2250. // else
  2251. // {
  2252. // subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
  2253. // }
  2254. // ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
  2255. // ViewController.mail_subject = subject;
  2256. ViewController.autoPrint=true;
  2257. ViewController.hidenavi = false;
  2258. [self.main_vc.navigationController pushViewController:ViewController animated:YES];
  2259. // [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
  2260. }
  2261. //-(void) addScannerReceiver:(NSString*)classname
  2262. //{
  2263. // [self.arr_scannerReceiver addObject:classname];
  2264. //}
  2265. -(void) setScannerDelegate:(id<ScanApiHelperDelegate>)delegate
  2266. {
  2267. [ScanApi setDelegate:delegate];
  2268. }
  2269. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2270. {
  2271. #ifdef SCANNER_ORDER
  2272. //审核时连接测试数据库
  2273. // NSDate *cdate= [NSDate date];
  2274. // NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
  2275. // [dateFormatter setDateFormat:@"yyyy-MM-dd"];
  2276. //
  2277. //NSDate * ddate =[dateFormatter dateFromString:@"2022-07-08"];
  2278. //
  2279. //// bool review=[cdate earlierDate:ddate];
  2280. // NSTimeInterval secondsInterval= [cdate timeIntervalSinceDate:ddate];
  2281. // int sec =secondsInterval;
  2282. bool rtime = [RADataProvider scanRtime:@"2022-07-10"];
  2283. NSDictionary *addressDic = [[NSUserDefaults standardUserDefaults] valueForKey:@"ScanAddress"];
  2284. if(rtime && !addressDic)
  2285. {
  2286. NSUInteger selectedIndex = 1;
  2287. // 保存信息
  2288. NSString *name = @"HMLG";
  2289. NSString *show_name = @"FREMONT, CA";
  2290. NSString *internalAddr =@"https://erp.homelegance.com/" ;
  2291. int price_index = 0;
  2292. // NSString *externalAddr = weakself.externalTextField.text;
  2293. NSMutableDictionary *addressDic = [NSMutableDictionary dictionary];
  2294. if (internalAddr.length) {
  2295. [addressDic setObject:internalAddr forKey:@"serverAddress"];
  2296. }
  2297. // if (externalAddr.length) {
  2298. // [addressDic setObject:externalAddr forKey:@"externalAddress"];
  2299. // }
  2300. if (name.length) {
  2301. [addressDic setObject:name forKey:@"name"];
  2302. }
  2303. if (show_name.length) {
  2304. [addressDic setObject:show_name forKey:@"show_name"];
  2305. }
  2306. [addressDic setObject:@(price_index) forKey:@"price_index"];
  2307. [addressDic setObject:@(selectedIndex) forKey:@"selectedIndex"];
  2308. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  2309. [userDefaults setValue:addressDic forKey:@"ScanAddress"];
  2310. [userDefaults synchronize];
  2311. }
  2312. self.compressFile = [[RAUPloadManagerConfigure alloc] init].compressImage;
  2313. #endif
  2314. #ifdef OFFLINE_ORDER
  2315. #endif
  2316. self.window.backgroundColor = [UIColor whiteColor];
  2317. // [RAUtils expression_varable:nil regex:nil];
  2318. // self.disable_trigger = false;
  2319. [iSalesDB enable_trigger];
  2320. [self initialExceptionHandler];
  2321. [self becomeObserver];
  2322. #ifdef GOOGLE_ANALYTICS
  2323. [self setUpGoogleAnalytics];
  2324. #endif
  2325. [DefaultAppearance init_appearance];
  2326. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2327. NSString *cachefolder = [paths objectAtIndex:0];
  2328. NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
  2329. // upfolder = [upfolder stringByAppendingPathComponent:serial];
  2330. NSFileManager* fileManager = [NSFileManager defaultManager];
  2331. BOOL bdir=YES;
  2332. if(! [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
  2333. {
  2334. NSError *error = nil;
  2335. bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
  2336. if(!bsuccess)
  2337. DebugLog(@"Create UPLOAD folder failed");
  2338. }
  2339. NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  2340. if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
  2341. {
  2342. NSError *error = nil;
  2343. bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
  2344. if(!bsuccess)
  2345. DebugLog(@"Create PDF Cache folder failed");
  2346. }
  2347. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2348. //
  2349. // DebugLog(@"文件已经存在了");
  2350. //
  2351. // }
  2352. // NSString* order_filter_source_path =[[NSBundle mainBundle] pathForResource:@"status_filter_cadedate" ofType:@"json" ];
  2353. // /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
  2354. //
  2355. //
  2356. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2357. // NSString *documents = [paths objectAtIndex:0];
  2358. // NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
  2359. //
  2360. //
  2361. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2362. //
  2363. // DebugLog(@"文件已经存在了");
  2364. //
  2365. // }
  2366. // else
  2367. // {
  2368. //
  2369. //
  2370. //
  2371. // // DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
  2372. //
  2373. // NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
  2374. //
  2375. // // DebugLog(@"mainBundleFile==%@",mainBundleFile);
  2376. //
  2377. // [[NSFileManager defaultManager] createFileAtPath:dist_path
  2378. //
  2379. // contents:mainBundleFile
  2380. //
  2381. // attributes:nil];
  2382. //
  2383. // }
  2384. self.recent_model = [[NSMutableDictionary alloc]init];
  2385. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2386. bool offline = [defaults boolForKey:@"EnableOfflineMode"] ;
  2387. self.offline_mode = offline;
  2388. // Override point for customization after application launch.
  2389. if ( [iSalesDB initializeDb]!=0)
  2390. DebugLog(@"init db failed");
  2391. // disable apn
  2392. // [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
  2393. self.contact_id=nil;
  2394. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2395. NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
  2396. if([enable_cache isEqualToString:@"false"])
  2397. self.bEnable_Cache = false;
  2398. else
  2399. self.bEnable_Cache = true;
  2400. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  2401. self.build =[infoDict objectForKey:@"CFBundleVersion"];
  2402. //scanner
  2403. _feedbackStack=[[NSMutableArray alloc]init];
  2404. self.devices=[[NSMutableArray alloc]init];
  2405. // change this to YES if you want SingleEntry to
  2406. // confirm the decoded data
  2407. self.doAppDataConfirmation=NO;
  2408. if(ScanApi==nil){
  2409. #ifdef USE_SOFTSCAN
  2410. // this is useful for SoftScan to keep a handle
  2411. // that is used in the trigger button
  2412. _softScanDeviceInfo=nil;
  2413. #endif
  2414. ScanApi=[[ScanApiHelper alloc]init];
  2415. [ScanApi setDelegate:self];
  2416. self.enable_ScannerLog = true;
  2417. self.api_Status= API_STOP;
  2418. // UIApplication * app = [UIApplication sharedApplication];
  2419. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  2420. //
  2421. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2422. bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
  2423. if(autolaunch==true)
  2424. [self enableScanner:autolaunch];
  2425. }
  2426. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  2427. [self handleErrorLog];
  2428. });
  2429. return YES;
  2430. }
  2431. #pragma mark - Feedback stack
  2432. -(void)pushFeedback:(id<ScannerEventsFeedback>)feedback{
  2433. long index =[_feedbackStack indexOfObject:feedback];
  2434. if(index!=NSNotFound)
  2435. {
  2436. // if(index!=_feedbackStack.count-1)
  2437. // {
  2438. // [_feedbackStack exchangeObjectAtIndex:index withObjectAtIndex:_feedbackStack.count-1];
  2439. // _eventsFeedback = feedback;
  2440. // }
  2441. }
  2442. else
  2443. {
  2444. [_feedbackStack addObject:feedback];
  2445. }
  2446. _eventsFeedback = feedback;
  2447. // if(_eventsFeedback != feedback){
  2448. // if(_eventsFeedback!=nil){
  2449. // [_feedbackStack addObject:_eventsFeedback];
  2450. // }
  2451. // _eventsFeedback=feedback;
  2452. //// [self generateDeviceArrivals];
  2453. // }
  2454. }
  2455. -(void)popFeedback:(id<ScannerEventsFeedback>)feedback{
  2456. [_feedbackStack removeObject:feedback];
  2457. if(_feedbackStack.count>0)
  2458. _eventsFeedback = _feedbackStack[_feedbackStack.count-1];
  2459. else
  2460. _eventsFeedback = nil;
  2461. // if(_eventsFeedback ==feedback){
  2462. // if(_feedbackStack.count>0){
  2463. // id<ScannerEventsFeedback> newDelegate=[_feedbackStack objectAtIndex:_feedbackStack.count-1];
  2464. // [_feedbackStack removeLastObject];
  2465. // _eventsFeedback = newDelegate;
  2466. // // generate a device Arrival for each scanner we've already receive
  2467. // // so that the new view can be aware of the connected scanners
  2468. //// [self generateDeviceArrivals];
  2469. // }
  2470. // else{
  2471. // _eventsFeedback=nil;
  2472. // }
  2473. // }
  2474. }
  2475. -(void)setFeedback:(id<ScannerEventsFeedback>)feedback
  2476. {
  2477. _eventsFeedback = feedback;
  2478. }
  2479. #pragma mark - ScanApiHelper complete delegates
  2480. // THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
  2481. // TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
  2482. // IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
  2483. // CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
  2484. // THE SCANNER, THESE CALLBACKS CAN BE REMOVED
  2485. // callback received when the Get Symbology Status is completed
  2486. -(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
  2487. [self addlog:@"onGetSymbologyDpm:"];
  2488. SKTRESULT result=[[scanObj Msg]Result];
  2489. if(SKTSUCCESS(result)){
  2490. DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
  2491. if(deviceInfo!=nil){
  2492. ISktScanSymbology* symbology=[[scanObj Property]Symbology];
  2493. if([symbology getStatus]==kSktScanSymbologyStatusDisable){
  2494. [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
  2495. }
  2496. }
  2497. }
  2498. else{
  2499. // an error message should be displayed here
  2500. // indicating that the DPM symbology status cannot be retrieved
  2501. }
  2502. }
  2503. // callback received when the Set Symbology Status is completed
  2504. -(void)onSetSymbology:(ISktScanObject*)scanObj{
  2505. [self addlog:@"onSetSymbology:"];
  2506. SKTRESULT result=[[scanObj Msg]Result];
  2507. if(!SKTSUCCESS(result)){
  2508. // display an error message saying a symbology cannot be set
  2509. }
  2510. }
  2511. /**
  2512. *
  2513. */
  2514. -(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
  2515. [self addlog:@"onSetDataConfirmationMode:"];
  2516. SKTRESULT result=[[scanObj Msg]Result];
  2517. if(SKTSUCCESS(result)){
  2518. [self addlog:@"DataConfirmation Mode OK"];
  2519. }
  2520. else{
  2521. [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
  2522. }
  2523. }
  2524. /**
  2525. *
  2526. */
  2527. -(void) onDataConfirmation:(ISktScanObject*)scanObj{
  2528. [self addlog:@"onDataConfirmation:"];
  2529. SKTRESULT result=[[scanObj Msg]Result];
  2530. if(SKTSUCCESS(result)){
  2531. [self addlog:@"Data Confirmed OK"];
  2532. }
  2533. else{
  2534. [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
  2535. }
  2536. }
  2537. /**
  2538. *
  2539. */
  2540. -(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
  2541. [self addlog:@"onSetLocalDecodeAction:"];
  2542. SKTRESULT result=[[scanObj Msg]Result];
  2543. if(SKTSUCCESS(result)){
  2544. [self addlog:@"Local Decode Action OK"];
  2545. }
  2546. else{
  2547. [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
  2548. }
  2549. }
  2550. /**
  2551. *
  2552. */
  2553. -(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
  2554. SKTRESULT result=[[scanObj Msg]Result];
  2555. if(SKTSUCCESS(result)){
  2556. ISktScanProperty* property=[scanObj Property];
  2557. [self addlog:@"SoftScan status:"];
  2558. if([property getByte]==kSktScanEnableSoftScan){
  2559. [self addlog:@"SoftScan is ENABLED"];
  2560. _softScannerEnabled=TRUE;
  2561. }
  2562. else{
  2563. _softScannerEnabled=FALSE;
  2564. [self addlog:@"SoftScan is DISABLED"];
  2565. }
  2566. }
  2567. else{
  2568. [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
  2569. }
  2570. }
  2571. /**
  2572. *
  2573. */
  2574. -(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
  2575. [self addlog:@"onSetSoftScanStatus:"];
  2576. SKTRESULT result=[[scanObj Msg]Result];
  2577. if(SKTSUCCESS(result)){
  2578. [self addlog:@"SoftScan set status success"];
  2579. }
  2580. else{
  2581. [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
  2582. }
  2583. }
  2584. /**
  2585. *
  2586. */
  2587. -(void) onSetTrigger:(ISktScanObject*)scanObj{
  2588. [self addlog:@"onSetTrigger:"];
  2589. SKTRESULT result=[[scanObj Msg]Result];
  2590. if(SKTSUCCESS(result)){
  2591. [self addlog:@"Trigger set success"];
  2592. }
  2593. else{
  2594. [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
  2595. }
  2596. }
  2597. /**
  2598. *
  2599. */
  2600. -(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
  2601. [self addlog:@"onGetScanApiVersion:"];
  2602. SKTRESULT result=[[scanObj Msg]Result];
  2603. if(SKTSUCCESS(result))
  2604. {
  2605. ISktScanProperty*property=[scanObj Property];
  2606. if([property getType]==kSktScanPropTypeVersion)
  2607. {
  2608. scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
  2609. [[property Version]getMajor],
  2610. [[property Version]getMiddle],
  2611. [[property Version]getMinor],
  2612. [[property Version]getBuild]];
  2613. }
  2614. }
  2615. else{
  2616. scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
  2617. }
  2618. [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
  2619. }
  2620. /**
  2621. *
  2622. */
  2623. #ifdef USE_SOFTSCAN
  2624. -(void) onSetOverlayView:(ISktScanObject*)scanObj{
  2625. SKTRESULT result=[[scanObj Msg]Result];
  2626. if(SKTSUCCESS(result)){
  2627. [self addlog:@"Overlay view set success"];
  2628. }
  2629. else{
  2630. [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
  2631. }
  2632. }
  2633. #endif
  2634. /**
  2635. * called each time a device connects to the host
  2636. * @param result contains the result of the connection
  2637. * @param newDevice contains the device information
  2638. */
  2639. -(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
  2640. [self addlog:@"onDeviceArrival:"];
  2641. [self updateDevicesList:deviceInfo Add:YES];
  2642. #ifdef USE_SOFTSCAN
  2643. // if the scanner is a SoftScan scanner
  2644. if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
  2645. // _softScannerTriggerBtn.hidden=NO;
  2646. _softScanDeviceInfo=deviceInfo;
  2647. if(_deviceInfoToTrigger==nil)
  2648. _deviceInfoToTrigger=deviceInfo;
  2649. NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
  2650. [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
  2651. [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
  2652. }
  2653. else
  2654. #endif
  2655. {
  2656. if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
  2657. // _softScannerTriggerBtn.hidden=NO;
  2658. _deviceInfoToTrigger=deviceInfo;
  2659. }
  2660. if(_doAppDataConfirmation==YES){
  2661. // switch the comment between the 2 following lines for handling the
  2662. // data confirmation beep from the scanner (local)
  2663. // if none is set, the scanner will beep only once when SingleEntry actually
  2664. // confirm the decoded data, otherwise the scanner will beep twice, one locally,
  2665. // and one when SingleEntry will confirm the decoded data
  2666. [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
  2667. // [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
  2668. }
  2669. // for demonstration only, let's make sure the DPM is enabled
  2670. // first interrogate the scanner to see if it's already enabled
  2671. // and in the onGetSymbologyDpm callback, if the DPM is not already set
  2672. // then we send a Symbology property to enable it.
  2673. [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
  2674. }
  2675. }
  2676. /**
  2677. * called each time a device disconnect from the host
  2678. * @param deviceRemoved contains the device information
  2679. */
  2680. -(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
  2681. [self addlog:@"onDeviceRemoval:"];
  2682. [self updateDevicesList:deviceRemoved Add:NO];
  2683. if(_deviceInfoToTrigger==deviceRemoved){
  2684. _deviceInfoToTrigger=nil;
  2685. }
  2686. #ifdef USE_SOFTSCAN
  2687. if(_softScanDeviceInfo==deviceRemoved){
  2688. _softScanDeviceInfo=nil;
  2689. }
  2690. if(_deviceInfoToTrigger==nil)
  2691. _deviceInfoToTrigger=_softScanDeviceInfo;
  2692. #endif
  2693. if(_deviceInfoToTrigger==nil){
  2694. // _softScannerTriggerBtn.hidden=YES;
  2695. }
  2696. }
  2697. /**
  2698. * called each time ScanAPI is reporting an error
  2699. * @param result contains the error code
  2700. */
  2701. -(void) onError:(SKTRESULT) result{
  2702. [self addlog:@"onError:"];
  2703. [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2704. #ifdef RA_NOTIFICATION
  2705. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2706. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2707. }
  2708. #else
  2709. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2710. [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2711. #endif
  2712. // _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
  2713. }
  2714. /**
  2715. * called each time ScanAPI receives decoded data from scanner
  2716. * @param deviceInfo contains the device information from which
  2717. * the data has been decoded
  2718. * @param decodedData contains the decoded data information
  2719. */
  2720. -(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2721. [self addlog:@"onDecodedDataResult:"];
  2722. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2723. if(SKTSUCCESS(result)){
  2724. NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  2725. #ifdef RA_NOTIFICATION
  2726. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2727. [_eventsFeedback onDecodedData:cleanString];
  2728. }
  2729. #else
  2730. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2731. [avc onDecodedData:cleanString];
  2732. #endif
  2733. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2734. [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
  2735. if(_doAppDataConfirmation==YES){
  2736. [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2737. }
  2738. }
  2739. }
  2740. -(void) test_onDecodedDataResult:(NSString*) value
  2741. {
  2742. [self addlog:@"onDecodedDataResult:"];
  2743. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2744. if(true){
  2745. #ifdef RA_NOTIFICATION
  2746. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2747. [_eventsFeedback onDecodedData:value];
  2748. }
  2749. #else
  2750. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2751. [avc onDecodedData:value];
  2752. #endif
  2753. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2754. [self addlog:value];
  2755. // if(_doAppDataConfirmation==YES){
  2756. // [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2757. // }
  2758. }
  2759. }
  2760. //-(void) didRotated
  2761. //{
  2762. //
  2763. //}
  2764. /**
  2765. * called when ScanAPI initialization has been completed
  2766. * @param result contains the initialization result
  2767. */
  2768. -(void) onScanApiInitializeComplete:(SKTRESULT) result{
  2769. [self addlog:@"onScanApiInitializeComplete:"];
  2770. if(SKTSUCCESS(result))
  2771. {
  2772. self.api_Status = API_START;
  2773. NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
  2774. [self addlog:strlog];
  2775. #ifdef USE_SOFTSCAN
  2776. // make sure we support SoftScan
  2777. [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2778. // check if SoftScan is enabled
  2779. [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
  2780. #else
  2781. // disable support SoftScan (Default, not really needed if it was never activated)
  2782. [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2783. #endif
  2784. // ask for ScanAPI version (not a requirement but always nice to know)
  2785. [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
  2786. // configure ScanAPI for doing App Data confirmation,
  2787. // if TRUE then SingleEntry will confirm the decoded data
  2788. if(_doAppDataConfirmation==YES){
  2789. [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
  2790. }
  2791. #ifdef RA_NOTIFICATION
  2792. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2793. [_eventsFeedback onStatusChanged:@"Waiting for scanner..."];
  2794. }
  2795. #else
  2796. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2797. [avc onStatusChanged:@"Waiting for scanner..."];
  2798. #endif
  2799. self.Status_Text = @"Waiting for scanner...";
  2800. // _Status.text=@"Waiting for scanner...";
  2801. }
  2802. else{
  2803. #ifdef RA_NOTIFICATION
  2804. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2805. [_eventsFeedback onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2806. }
  2807. #else
  2808. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2809. [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2810. #endif
  2811. self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2812. // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2813. NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2814. [self addlog:strlog];
  2815. }
  2816. }
  2817. /**
  2818. * called when ScanAPI has been terminated. This will be
  2819. * the last message received from ScanAPI
  2820. */
  2821. -(void) onScanApiTerminated{
  2822. [self addlog:@"onScanApiTerminated:"];
  2823. [ScanApiConsumer invalidate];
  2824. ScanApiConsumer= nil;
  2825. [self addlog:@"ScanApiConsumer invalidate"];
  2826. self.api_Status = API_STOP;
  2827. #ifdef RA_NOTIFICATION
  2828. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2829. [_eventsFeedback onStatusChanged:@"Off"];
  2830. }
  2831. #else
  2832. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2833. [avc onStatusChanged:@"Off"];
  2834. #endif
  2835. self.Status_Text =@"Off";
  2836. // _Status.text = @"Off";
  2837. }
  2838. /**
  2839. * called when an error occurs during the retrieval
  2840. * of a ScanObject from ScanAPI.
  2841. * @param result contains the retrieval error code
  2842. */
  2843. -(void) onErrorRetrievingScanObject:(SKTRESULT) result{
  2844. [self addlog:@"onErrorRetrievingScanObject:"];
  2845. [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2846. //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
  2847. #ifdef RA_NOTIFICATION
  2848. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2849. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2850. }
  2851. #else
  2852. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2853. [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2854. #endif
  2855. }
  2856. #pragma mark - Scaner
  2857. -(void)onTimer: (NSTimer*)theTimer{
  2858. if(theTimer==ScanApiConsumer){
  2859. // [self addlog:@"ScanApi::doScanApiReceive:"];
  2860. [ScanApi doScanApiReceive];
  2861. }
  2862. }
  2863. -(void) addlog:(NSString*) newtext
  2864. {
  2865. if(!self.enable_ScannerLog)
  2866. return;
  2867. dispatch_async(dispatch_get_main_queue(), ^{
  2868. NSString* date;
  2869. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  2870. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  2871. date = [formatter stringFromDate:[NSDate date]];
  2872. if(newtext.length<=0)
  2873. return;
  2874. NSString* text = self.log;
  2875. if(text.length==0)
  2876. text=@"";
  2877. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  2878. self.log = text;
  2879. #ifdef RA_NOTIFICATION
  2880. if((self->_eventsFeedback!=nil)&&([self->_eventsFeedback respondsToSelector:@selector(onLogUpdate)])){
  2881. [self->_eventsFeedback onLogUpdate];
  2882. }
  2883. #else
  2884. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2885. [avc onLogUpdate];
  2886. #endif
  2887. });
  2888. }
  2889. - (void)enableScanner:(bool)enable {
  2890. [self addlog:@"Enable scanner:"];
  2891. if(enable)
  2892. {
  2893. [self addlog:@"Enable"];
  2894. self.api_Status = API_INIT;
  2895. #ifdef RA_NOTIFICATION
  2896. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2897. [_eventsFeedback onStatusChanged:@"Initialize..."];
  2898. }
  2899. #else
  2900. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2901. [avc onStatusChanged:@"Initialize..."];
  2902. #endif
  2903. self.Status_Text = @"Initialize...";
  2904. [ScanApi open];
  2905. [self addlog:@"ScanApi open"];
  2906. ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
  2907. [self addlog:@"ScanApiConsumer init"];
  2908. // [ScanApi close];
  2909. // [self addlog:@"ScanApi opent"];
  2910. }
  2911. else
  2912. {
  2913. [self addlog:@"Disable"];
  2914. // [ScanApiConsumer invalidate];
  2915. // ScanApiConsumer= nil;
  2916. // [self addlog:@"ScanApiConsumer invalidate"];
  2917. self.api_Status = API_CLOSING;
  2918. #ifdef RA_NOTIFICATION
  2919. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2920. [_eventsFeedback onStatusChanged:@"Stoping..."];
  2921. }
  2922. #else
  2923. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2924. [avc onStatusChanged:@"Stoping..."];
  2925. #endif
  2926. self.Status_Text = @"Stoping...";
  2927. [ScanApi close];
  2928. [self addlog:@"ScanApi close"];
  2929. }
  2930. }
  2931. #pragma mark - Device Info List management
  2932. -(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
  2933. [self addlog:@"updateDevicesList:"];
  2934. if(add==YES){
  2935. [self.devices addObject:deviceInfo];
  2936. }
  2937. else{
  2938. [self.devices removeObject:deviceInfo];
  2939. }
  2940. NSMutableString* temp=[[NSMutableString alloc]init];
  2941. for (DeviceInfo* info in self.devices) {
  2942. [temp appendString:[info getName]];
  2943. [temp appendString:@"\n"];
  2944. }
  2945. if(self.devices.count>0)
  2946. [temp appendString:@"ready to scan"];
  2947. else
  2948. [temp appendString:@"Waiting for Scanner..."];
  2949. // _Status.text=temp ;
  2950. [self addlog:temp];
  2951. #ifdef RA_NOTIFICATION
  2952. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2953. [_eventsFeedback onStatusChanged:temp];
  2954. }
  2955. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2956. [_eventsFeedback OnUpdateDevicesList];
  2957. }
  2958. #else
  2959. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2960. [avc onStatusChanged:temp];
  2961. [avc OnUpdateDevicesList];
  2962. #endif
  2963. self.Status_Text = temp;
  2964. // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
  2965. // [self.dev_table reloadData];
  2966. }
  2967. #pragma mark - offline order
  2968. -(void) backup_oc
  2969. {
  2970. }
  2971. -(void) restore_oc
  2972. {
  2973. }
  2974. #ifdef SCANNER_ORDER
  2975. #pragma mark - upload manager
  2976. - (void)saveUploadTasks {
  2977. if(true)
  2978. {
  2979. if(self.uploadManager.arr_queue!=nil)
  2980. {
  2981. [self.uploadManager stopAllTasks];
  2982. }
  2983. [self.uploadManager saveTasks];
  2984. return;
  2985. }
  2986. }
  2987. - (NSMutableArray *)cachedUploadTasks {
  2988. if (!self.user) {
  2989. return nil;
  2990. }
  2991. NSString *path = [[RAUtils appCacheDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_uploadTasks",self.user]];
  2992. NSFileManager *manager = [NSFileManager defaultManager];
  2993. if ([manager fileExistsAtPath:path]) {
  2994. NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:path];
  2995. [manager removeItemAtPath:path error:nil];
  2996. return arr;
  2997. }
  2998. return nil;
  2999. }
  3000. #endif
  3001. @end