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