AppDelegateBase.m 143 KB

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