AppDelegateBase.m 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718
  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)checkLogin:(BOOL)reloadCurVC {
  910. [((MainViewController *)self.main_vc) checklogin:reloadCurVC];
  911. }
  912. //disable apn
  913. //-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  914. //{
  915. // self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
  916. // DebugLog(@"regisger success:%@",deviceToken);
  917. //
  918. // //注册成功,将deviceToken保存到应用服务器数据库中
  919. //}
  920. #pragma mark - background download
  921. -(bool)isdownloading:(NSString*) file
  922. {
  923. return true;
  924. }
  925. -(long long)getcurrentLength:(int) taskidx
  926. {
  927. int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
  928. return position;
  929. }
  930. -(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
  931. {
  932. //操作有两种,start stop;
  933. //结果有四种, wait , downloading, pause, finish
  934. dispatch_async(dispatch_get_main_queue(), ^{
  935. // debug;
  936. // NSString* file_name=[url lastPathComponent];
  937. //暂停<->开始转换
  938. // bool isdownloading = [self isdownloading:file_name];
  939. if (start)
  940. {//开始下载
  941. DebugLog(@"%d start",taskidx);
  942. self.current_task=taskidx;
  943. NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
  944. // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
  945. //
  946. //
  947. // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  948. //
  949. // //设置请求头(GET)
  950. // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  951. // [request setValue:range forHTTPHeaderField:@"Range"];
  952. //
  953. // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  954. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  955. //设置请求头(GET)
  956. NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  957. [request setValue:range forHTTPHeaderField:@"Range"];
  958. self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  959. }else{ //暂停
  960. DebugLog(@"%d pause",taskidx);
  961. [self.connection cancel];
  962. self.connection = nil;
  963. }
  964. });
  965. }
  966. -(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order params:(NSMutableDictionary*) add_params
  967. {
  968. assert(add_params[@"user"]!=nil);
  969. assert(add_params[@"password"]!=nil);
  970. // assert(add_params[@"contact_id"]!=nil);
  971. [self add_downloadlog:@"Begin sync, please wait."];
  972. [self add_downloadlog:@"Prepare upload data."];
  973. // NSArray* arr_order=[OLDataProvider enumOfflineOrder];
  974. NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order params:add_params];
  975. NSString* upfile=upjson[@"file"];
  976. {
  977. NSData* data = [NSData dataWithContentsOfFile: upfile];
  978. // UIApplication * app = [UIApplication sharedApplication];
  979. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  980. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  981. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  982. if(add_params[@"user"]!=nil)
  983. [params setValue:add_params[@"user"] forKey:@"user"];
  984. // if(appDelegate.contact_id!=nil)
  985. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  986. if(add_params[@"password"]!=nil)
  987. [params setValue:add_params[@"password"] forKey:@"password"];
  988. #if TARGET_IPHONE_SIMULATOR//模拟器
  989. [params setValue:@"simulator_uuid" forKey:@"idfv"];
  990. #elif TARGET_OS_IPHONE//真机
  991. UIDevice * dev = [UIDevice currentDevice];
  992. NSUUID* uuid =dev.identifierForVendor;
  993. [params setValue:uuid.UUIDString forKey:@"idfv"];
  994. #endif
  995. __weak typeof(self) weakSelf = self;
  996. [NetworkUtils upload:data FileName:[upfile lastPathComponent] Params:params ToHost:URL_UPLOAD_OFFLINE Result:^(NSMutableDictionary *json) {
  997. if([[json valueForKey:@"result"] intValue]==2)
  998. {
  999. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1000. // 清理数据库要放入线程中执行
  1001. NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  1002. if (out_of_stock_ids) {
  1003. [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];
  1004. }
  1005. [weakSelf add_downloadlog:@"Upload successful."];
  1006. // [iSalesDB disable_trigger]
  1007. [iSalesDB disable_trigger];
  1008. NSString* so_id=[RAConvertor arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  1009. [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  1010. [iSalesDB execSql:@"delete from wishlist"];
  1011. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  1012. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  1013. [iSalesDB execSql:@"delete from offline_portfolio"];
  1014. [iSalesDB execSql:@"delete from offline_pdf"];
  1015. [OLDataProvider offline_clear_PDFCache];
  1016. NSString* contactMap = json[@"contactMap"];
  1017. if(contactMap.length>0)
  1018. {
  1019. NSDictionary* contactjson = [RAConvertor string2dict:contactMap];
  1020. NSArray *keys= [contactjson allKeys];
  1021. //遍历keys
  1022. for(int i=0;i<[keys count];i++)
  1023. {
  1024. //得到当前key
  1025. NSString *key=[keys objectAtIndex:i];
  1026. //如果key不是pic,说明value是字符类型,比如name:Boris
  1027. NSString* value = [contactjson valueForKey:key];
  1028. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1029. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1030. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1031. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1032. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1033. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1034. }
  1035. }
  1036. // NSDictionary* contactjson= upjson[@"contact"];
  1037. // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1038. // NSDictionary* orderjson= upjson[@"order"];
  1039. // [iSalesDB enable_trigger]
  1040. [iSalesDB enable_trigger];
  1041. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1042. [defaults removeObjectForKey:@"Forcedownload"];
  1043. [defaults setBool:true forKey:@"Forcedownload"];
  1044. [defaults synchronize];
  1045. dispatch_async(dispatch_get_main_queue(), ^{
  1046. //下载函数要从主线程调用
  1047. [weakSelf download_offline:ver useInternalAddress:buseinternaladdress];
  1048. });
  1049. });
  1050. }
  1051. else
  1052. {
  1053. [weakSelf add_downloadlog:[json valueForKey:@"msg"]];
  1054. [weakSelf add_downloadlog:@"Sync canceled."];
  1055. [weakSelf.settingUI onSyncFinish];
  1056. }
  1057. } Progress:^(NSURLSessionTask *task, double progress) {
  1058. } DecryptHandler:nil];
  1059. // AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  1060. //
  1061. // serializer.timeoutInterval=300;
  1062. //
  1063. // NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_OFFLINE parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  1064. // [formData appendPartWithFileData:data name:@"upfile" fileName:[upfile lastPathComponent] mimeType:@"application/zip"];
  1065. // } error:nil];
  1066. //
  1067. //
  1068. //
  1069. // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  1070. //
  1071. // NSProgress *progress = nil;
  1072. //
  1073. // NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  1074. //
  1075. //
  1076. //
  1077. // if (error) {
  1078. //
  1079. // NSString* err_msg = [error localizedDescription];
  1080. // DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  1081. //
  1082. //
  1083. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  1084. //
  1085. // DebugLog(@"data string: %@",str);
  1086. // [self add_downloadlog:err_msg];
  1087. // [self add_downloadlog:@"Can not connect to server please try again."];
  1088. // [self.settingUI onSyncFinish];
  1089. //
  1090. // } else {
  1091. // DebugLog(@"response ");
  1092. //
  1093. //
  1094. //
  1095. // NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  1096. //
  1097. // // 再将NSData转为字符串
  1098. // NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  1099. //
  1100. // // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  1101. //
  1102. // DebugLog(@"data string: %@",jsonStr);
  1103. //
  1104. // NSDictionary* json = responseObject;
  1105. //
  1106. //
  1107. // if([[json valueForKey:@"result"] intValue]==2)
  1108. // {
  1109. // NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  1110. // if (out_of_stock_ids) {
  1111. // [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];
  1112. // }
  1113. //
  1114. // [self add_downloadlog:@"Upload successful."];
  1115. // [iSalesDB disable_trigger]
  1116. // NSString* so_id=[RAUtils arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  1117. //
  1118. // [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  1119. // [iSalesDB execSql:@"delete from wishlist"];
  1120. // [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  1121. // [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  1122. // [iSalesDB execSql:@"delete from offline_portfolio"];
  1123. // [iSalesDB execSql:@"delete from offline_pdf"];
  1124. // [OLDataProvider offline_clear_PDFCache];
  1125. //
  1126. // NSString* contactMap = json[@"contactMap"];
  1127. // if(contactMap.length>0)
  1128. // {
  1129. // NSDictionary* contactjson = [RAUtils string2dict:contactMap];
  1130. // NSArray *keys= [contactjson allKeys];
  1131. // //遍历keys
  1132. // for(int i=0;i<[keys count];i++)
  1133. // {
  1134. // //得到当前key
  1135. // NSString *key=[keys objectAtIndex:i];
  1136. // //如果key不是pic,说明value是字符类型,比如name:Boris
  1137. // NSString* value = [contactjson valueForKey:key];
  1138. //
  1139. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1140. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1141. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1142. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1143. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1144. // [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1145. //
  1146. // }
  1147. // }
  1148. // // NSDictionary* contactjson= upjson[@"contact"];
  1149. // // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1150. // // NSDictionary* orderjson= upjson[@"order"];
  1151. //
  1152. // [iSalesDB enable_trigger]
  1153. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1154. // [defaults removeObjectForKey:@"Forcedownload"];
  1155. // [defaults setBool:true forKey:@"Forcedownload"];
  1156. // [defaults synchronize];
  1157. //
  1158. // [self download_offline:ver useInternalAddress:buseinternaladdress];
  1159. //
  1160. // }
  1161. // else
  1162. // {
  1163. // [self add_downloadlog:[json valueForKey:@"msg"]];
  1164. // [self add_downloadlog:@"Sync canceled."];
  1165. // [self.settingUI onSyncFinish];
  1166. // }
  1167. //
  1168. //
  1169. // }
  1170. // // [waitalert dismissViewControllerAnimated:YES completion:nil];
  1171. // }];
  1172. //
  1173. //
  1174. //
  1175. //
  1176. //
  1177. //
  1178. //
  1179. // [uploadTask resume];
  1180. }
  1181. return;
  1182. }
  1183. -(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
  1184. {
  1185. NSString *plistPath = [RAUtils get_config_path];
  1186. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1187. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1188. {
  1189. ver= nil;
  1190. [self add_downloadlog:@"App required a fully sync."];
  1191. }
  1192. if(self.downloading)
  1193. return;
  1194. self.downloading=true;
  1195. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1196. NSString* pvid = [defaults stringForKey:@"vid"] ;
  1197. [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
  1198. [RANetwork request_new_offline_ticket:ver useInternalAddress:false vid:pvid completionHandler:^(NSMutableDictionary *result) {
  1199. NSMutableDictionary* json= result;
  1200. if([json[@"result"] intValue]!=2)
  1201. {
  1202. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1203. [self.settingUI onSyncFinish];
  1204. // self.downloadlog=nil;
  1205. self.downloading=false;
  1206. return;
  1207. }
  1208. else
  1209. {
  1210. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1211. __block NSMutableDictionary* download_json=nil;
  1212. // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1213. NSString* downSerial=[json valueForKey:@"downSerial"];
  1214. [defaults removeObjectForKey:@"downSerial"];
  1215. [defaults setValue:downSerial forKey:@"downSerial"];
  1216. [defaults synchronize];
  1217. // sleep(3);
  1218. //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1219. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1220. // int count=0;
  1221. // // __block bool preparing = true;
  1222. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1223. // {
  1224. // sleep(RETRY_DELAY);
  1225. //
  1226. //
  1227. // count++;
  1228. //// download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1229. //
  1230. // [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1231. // download_json=result;
  1232. // }];
  1233. //
  1234. //
  1235. //
  1236. //
  1237. // }
  1238. [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
  1239. download_json=result;
  1240. if([download_json[@"result"] intValue]!=RESULT_TRUE)
  1241. {
  1242. [self add_downloadlog:download_json[@"err_msg"]];
  1243. [self add_downloadlog:@"Download Abort."];
  1244. dispatch_async(dispatch_get_main_queue(), ^{
  1245. // self.downloadlog=nil;
  1246. self.downloading=false;
  1247. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1248. [defaults removeObjectForKey:@"Forcedownload"];
  1249. [defaults setBool:true forKey:@"Forcedownload"];
  1250. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1251. // [defaults removeObjectForKey:@"downSerial"];
  1252. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1253. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1254. [defaults synchronize];
  1255. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1256. });
  1257. return;
  1258. }
  1259. //服务器准备数据完毕,进入处理数据逻辑。
  1260. if([download_json[@"request_count"] intValue]>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1261. {
  1262. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1263. dispatch_async(dispatch_get_main_queue(), ^{
  1264. // self.downloadlog=nil;
  1265. self.downloading=false;
  1266. });
  1267. dispatch_async(dispatch_get_main_queue(), ^{
  1268. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1269. });
  1270. [self.settingUI onSyncFinish];
  1271. return;
  1272. //一直没取到json,出错处理
  1273. }
  1274. else
  1275. {
  1276. if([download_json[@"count"] intValue]==0)
  1277. {
  1278. //没有找到更新包,当前是最新版本
  1279. [self add_downloadlog:@"You are up-to-date!"];
  1280. dispatch_async(dispatch_get_main_queue(), ^{
  1281. // self.downloadlog=nil;
  1282. self.downloading=false;
  1283. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1284. [defaults removeObjectForKey:@"Forcedownload"];
  1285. [defaults setBool:FALSE forKey:@"Forcedownload"];
  1286. // NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1287. // [defaults removeObjectForKey:@"downSerial"];
  1288. // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1289. // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1290. [defaults synchronize];
  1291. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1292. });
  1293. // dispatch_async(dispatch_get_main_queue(), ^{
  1294. //
  1295. // });
  1296. [self.settingUI onSyncFinish];
  1297. return;
  1298. }
  1299. else
  1300. {
  1301. [self add_downloadlog:@"Find a new version, downloading..."];
  1302. self.download_task = [download_json mutableCopy];
  1303. // self.download_task[@"abcdef"]=@"abcdef";
  1304. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1305. [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1306. [self download_offline:true checkdiskspace:true];
  1307. return;
  1308. }
  1309. }
  1310. }];
  1311. }
  1312. }];
  1313. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1314. //
  1315. //
  1316. //
  1317. //
  1318. // NSMutableDictionary* json=[[RANetwork check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
  1319. //
  1320. //
  1321. // if([json[@"result"] intValue]!=2)
  1322. // {
  1323. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1324. // [self.settingUI onSyncFinish];
  1325. // dispatch_async(dispatch_get_main_queue(), ^{
  1326. // // self.downloadlog=nil;
  1327. // self.downloading=false;
  1328. // });
  1329. // return;
  1330. // }
  1331. //
  1332. //
  1333. // dispatch_async(dispatch_get_main_queue(), ^{
  1334. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1335. // });
  1336. //
  1337. //
  1338. // NSMutableDictionary* download_json=nil;
  1339. //
  1340. // // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1341. // NSString* downSerial=[json valueForKey:@"downSerial"];
  1342. //
  1343. // [defaults removeObjectForKey:@"downSerial"];
  1344. // [defaults setValue:downSerial forKey:@"downSerial"];
  1345. //
  1346. // [defaults synchronize];
  1347. //
  1348. // // sleep(3);
  1349. // //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1350. //
  1351. //
  1352. // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1353. // int count=0;
  1354. // // __block bool preparing = true;
  1355. // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1356. // {
  1357. // sleep(RETRY_DELAY);
  1358. //
  1359. //
  1360. // count++;
  1361. // download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
  1362. //
  1363. //
  1364. //
  1365. //
  1366. // }
  1367. //
  1368. // //服务器准备数据完毕,进入处理数据逻辑。
  1369. // if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1370. // {
  1371. // [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1372. // dispatch_async(dispatch_get_main_queue(), ^{
  1373. // // self.downloadlog=nil;
  1374. // self.downloading=false;
  1375. // });
  1376. // dispatch_async(dispatch_get_main_queue(), ^{
  1377. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1378. // });
  1379. // [self.settingUI onSyncFinish];
  1380. // return;
  1381. // //一直没取到json,出错处理
  1382. // }
  1383. // else
  1384. // {
  1385. // if([download_json[@"count"] intValue]==0)
  1386. // {
  1387. // //没有找到更新包,当前是最新版本
  1388. // [self add_downloadlog:@"You are up-to-date!"];
  1389. // dispatch_async(dispatch_get_main_queue(), ^{
  1390. // // self.downloadlog=nil;
  1391. // self.downloading=false;
  1392. // });
  1393. // dispatch_async(dispatch_get_main_queue(), ^{
  1394. // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1395. // });
  1396. // [self.settingUI onSyncFinish];
  1397. // return;
  1398. // }
  1399. // else
  1400. // {
  1401. // [self add_downloadlog:@"Find a new version, downloading..."];
  1402. // self.download_task = [download_json mutableCopy];
  1403. // // self.download_task[@"abcdef"]=@"abcdef";
  1404. // long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1405. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1406. // [self download_offline:true checkdiskspace:true];
  1407. // return;
  1408. // }
  1409. //
  1410. // }
  1411. //
  1412. // });
  1413. }
  1414. -(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
  1415. {
  1416. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1417. bool forcedownload = [defaults boolForKey:@"Forcedownload"];
  1418. if(forcedownload|| ver==nil)
  1419. {
  1420. [self download_offline:ver useInternalAddress:buseinternaladdress];
  1421. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1422. syncVC.action_string=@"Download";
  1423. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1424. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1425. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1426. [parent presentViewController:navi animated:YES completion:^{
  1427. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1428. DebugLog(@"about present.........");
  1429. // self.btop = false;
  1430. // <#code#>
  1431. }];
  1432. }
  1433. else
  1434. {
  1435. NSArray* arr_order=nil;
  1436. arr_order=[OLDataProvider enumOfflineOrder];
  1437. // if(arr_order.count>0)
  1438. // {
  1439. //
  1440. // {
  1441. // SelectUploadOrderViewController * vc =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
  1442. // vc.returnValue = ^(NSArray* SelectedOrder){
  1443. //
  1444. // [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:SelectedOrder];
  1445. // SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1446. // syncVC.action_string=@"Download";
  1447. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1448. //
  1449. //
  1450. //
  1451. //
  1452. //
  1453. // // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1454. //
  1455. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1456. // [parent presentViewController:navi animated:YES completion:^{
  1457. //
  1458. // // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1459. //
  1460. // DebugLog(@"about present.........");
  1461. //
  1462. // // self.btop = false;
  1463. // // <#code#>
  1464. // }];
  1465. // };
  1466. //
  1467. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc] ;
  1468. //
  1469. //
  1470. //
  1471. //
  1472. //
  1473. //
  1474. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1475. // [parent presentViewController:navi animated:YES completion:^{
  1476. //
  1477. //
  1478. // }];
  1479. // }
  1480. //
  1481. //
  1482. // }
  1483. // else
  1484. // {
  1485. NSMutableDictionary* add_params=[NSMutableDictionary new];
  1486. add_params[@"user"]=self.user;
  1487. add_params[@"password"]=self.password;
  1488. add_params[@"contact_id"]=self.contact_id;
  1489. [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order params:add_params];
  1490. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1491. syncVC.action_string=@"Download";
  1492. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1493. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1494. [parent presentViewController:navi animated:YES completion:^{
  1495. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1496. DebugLog(@"about present.........");
  1497. // self.btop = false;
  1498. // <#code#>
  1499. }];
  1500. // }
  1501. }
  1502. }
  1503. -(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
  1504. {
  1505. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  1506. if(start)
  1507. {
  1508. dispatch_async(dispatch_get_main_queue(), ^{
  1509. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1510. });
  1511. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1512. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1513. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1514. long long needsize = size+500;
  1515. if(needsize>freespace &&checkdiskspace)
  1516. {
  1517. //size not enough.
  1518. NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
  1519. [self add_downloadlog:space];
  1520. [self.settingUI onSyncFinish];
  1521. return ;
  1522. }
  1523. NSString* temp = NSTemporaryDirectory();
  1524. NSString * ver = self.download_task[@"ver"];
  1525. NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
  1526. //创建版本临时目录
  1527. NSFileManager* fileManager = [NSFileManager defaultManager];
  1528. BOOL bdir=YES;
  1529. if(! [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
  1530. {
  1531. NSError *error = nil;
  1532. bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
  1533. if(!bsuccess)
  1534. DebugLog(@"Create temp folder failed");
  1535. // if(bsuccess)
  1536. // {
  1537. // sqlite3 *db = [self get_db];
  1538. //
  1539. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  1540. // [iSalesDB close_db:db];
  1541. // }
  1542. }
  1543. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
  1544. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1545. if(! [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
  1546. {
  1547. NSError *error = nil;
  1548. bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1549. if(!bsuccess)
  1550. DebugLog(@"Create cache folder failed");
  1551. }
  1552. NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
  1553. NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
  1554. // if(! [fileManager fileExistsAtPath:resource isDirectory:&bdir])
  1555. // {
  1556. //
  1557. // NSError *error = nil;
  1558. // bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
  1559. //
  1560. // if(!bsuccess)
  1561. // DebugLog(@"Create resource folder failed");
  1562. //
  1563. // }
  1564. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1565. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  1566. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  1567. NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
  1568. // tempdb=[documents stringByAppendingPathComponent:DBNAME];
  1569. NSError *error = nil;
  1570. bdir=NO;
  1571. if(! [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
  1572. {
  1573. // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
  1574. if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
  1575. {
  1576. DebugLog(@"copy database failed");
  1577. }
  1578. }
  1579. bdir=YES;
  1580. error=nil;
  1581. int count = [[self.download_task valueForKey:@"count"] intValue];
  1582. bool alldone=true;
  1583. bool trouble=false;
  1584. bool response = false;
  1585. for (int i = 0;i<count;i++)
  1586. {
  1587. NSMutableDictionary* itemjson = [[self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]] mutableCopy];
  1588. NSString* url = [itemjson valueForKey:@"url"];
  1589. NSString* type = [itemjson valueForKey:@"type"];
  1590. {
  1591. #ifdef DEBUG
  1592. //调试模式下跳过下载图片
  1593. if([type isEqualToString:@"img"])
  1594. {
  1595. itemjson[@"status"]=@"finish";
  1596. continue;
  1597. }
  1598. #endif
  1599. }
  1600. NSString* status = itemjson[@"status"];
  1601. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1602. if(! [status isEqualToString:@"finish"])
  1603. {
  1604. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1605. {
  1606. [self handle_download:url start:start type:type taskid:i];
  1607. alldone=false;
  1608. break;
  1609. }
  1610. else
  1611. {
  1612. alldone=false;
  1613. trouble=true;
  1614. response = [itemjson[@"response"] boolValue];
  1615. break;
  1616. }
  1617. }
  1618. }
  1619. if(trouble)
  1620. {
  1621. NSString* msg =@"offline sync got some trouble, sync canceled.";
  1622. if(response==false)
  1623. {
  1624. msg=@"Cannot connect to server, please check your network.";
  1625. }
  1626. [self add_downloadlog:msg];
  1627. dispatch_async(dispatch_get_main_queue(), ^{
  1628. // self.downloadlog=nil;
  1629. self.downloading=false;
  1630. });
  1631. [self.settingUI onSyncFinish];
  1632. }
  1633. else if(alldone)
  1634. {
  1635. [self add_downloadlog:@"Finalizing download..."];
  1636. //全部下载完成;
  1637. //写入当前版本
  1638. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1639. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1640. NSString* lastsync = [formatter stringFromDate:[NSDate date]];
  1641. NSString* ver= self.download_task[@"ver"];
  1642. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1643. NSString *cachefolder = [paths objectAtIndex:0];
  1644. NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
  1645. //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
  1646. if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
  1647. {
  1648. DebugLog(@"move image folder failed");
  1649. [self add_downloadlog:@"move image folder failed"];
  1650. trouble=true;
  1651. }
  1652. else
  1653. {
  1654. DebugLog(@"move image folder successful");
  1655. }
  1656. error=nil;
  1657. // copy temp db to cache.
  1658. if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
  1659. {
  1660. if(![fileManager removeItemAtPath:database_path error:nil])
  1661. {
  1662. DebugLog(@"delete database failed");
  1663. }
  1664. else
  1665. {
  1666. if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1667. {
  1668. DebugLog(@"copy database failed");
  1669. [self add_downloadlog:@"copy database failed"];
  1670. trouble=true;
  1671. }
  1672. else{
  1673. //debug
  1674. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1675. [fileManager removeItemAtPath:tempdb error:nil];
  1676. // [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
  1677. }
  1678. }
  1679. }
  1680. else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1681. {
  1682. DebugLog(@"copy database failed");
  1683. //debug;
  1684. // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1685. [fileManager removeItemAtPath:tempdb error:nil];
  1686. [self add_downloadlog:@"copy database failed"];
  1687. trouble=true;
  1688. }
  1689. // if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
  1690. // {
  1691. // DebugLog(@"move db file failed");
  1692. // }
  1693. // else
  1694. // {
  1695. // DebugLog(@"move db file successful");
  1696. // }
  1697. error=nil;
  1698. if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
  1699. {
  1700. DebugLog(@"move data folder failed");
  1701. [self add_downloadlog:@"move data folder failed"];
  1702. trouble=true;
  1703. }
  1704. else
  1705. {
  1706. DebugLog(@"move data folder successful");
  1707. }
  1708. dispatch_async(dispatch_get_main_queue(), ^{
  1709. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1710. });
  1711. if(trouble)
  1712. {
  1713. [self add_downloadlog:@"offline sync failed."];
  1714. // 尚缺更新失败还原逻辑。
  1715. }
  1716. else
  1717. {
  1718. [self add_downloadlog:@"offline sync complete."];
  1719. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1720. [defaults removeObjectForKey:@"OfflineVer"];
  1721. [defaults setValue:ver forKey:@"OfflineVer"];
  1722. [defaults removeObjectForKey:@"LastSync"];
  1723. [defaults setValue:lastsync forKey:@"LastSync"];
  1724. [defaults removeObjectForKey:@"vid"];
  1725. [defaults setValue:self.vid forKey:@"vid"];
  1726. [defaults removeObjectForKey:@"Forcedownload"];
  1727. NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1728. [defaults removeObjectForKey:@"downSerial"];
  1729. [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1730. [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1731. [defaults synchronize];
  1732. NSString *plistPath = [RAUtils get_config_path];
  1733. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1734. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1735. {
  1736. config_list[@"NEED_FULLY_SYNC"] = @"false";
  1737. [config_list writeToFile:plistPath atomically:YES];
  1738. }
  1739. [RANetwork request_complete_offline_ticket:downSerial completionHandler:^(NSMutableDictionary *result) {
  1740. }];
  1741. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1742. //
  1743. //
  1744. // //debug
  1745. //// NSDictionary* editor_json = [RANetwork finish_download_Offline:downSerial];
  1746. // [RANetwork finish_download_Offline:downSerial];
  1747. //
  1748. //
  1749. // });
  1750. }
  1751. dispatch_async(dispatch_get_main_queue(), ^{
  1752. // self.downloadlog=nil;
  1753. self.downloading=false;
  1754. self.download_task=nil;
  1755. self.vid=nil;
  1756. [self.settingUI onSyncFinish];
  1757. });
  1758. }
  1759. }
  1760. else
  1761. {
  1762. int count = [[self.download_task valueForKey:@"count"] intValue];
  1763. for (int i = 0;i<count;i++)
  1764. {
  1765. NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
  1766. NSString* url = [itemjson valueForKey:@"url"];
  1767. NSString* type = [itemjson valueForKey:@"type"];
  1768. NSString* status = itemjson[@"status"];
  1769. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1770. if(! [status isEqualToString:@"finish"])
  1771. {
  1772. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1773. {
  1774. [self handle_download:url start:start type:type taskid:i];
  1775. break;
  1776. }
  1777. }
  1778. }
  1779. dispatch_async(dispatch_get_main_queue(), ^{
  1780. self.downloading=false;
  1781. });
  1782. }
  1783. }
  1784. -(void) add_downloadlog:(NSString*) newtext
  1785. {
  1786. // if(!self.downloading)
  1787. // return;
  1788. dispatch_async(dispatch_get_main_queue(), ^{
  1789. NSString* date;
  1790. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1791. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1792. date = [formatter stringFromDate:[NSDate date]];
  1793. if(newtext.length<=0)
  1794. return;
  1795. NSString* text = self.downloadlog;
  1796. if(text.length==0)
  1797. text=@"";
  1798. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  1799. self.downloadlog = text;
  1800. [self.settingUI onLogUpdate];
  1801. });
  1802. }
  1803. -(int)unpack
  1804. {
  1805. //return;
  1806. //DebugLog(_fileName);
  1807. ///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
  1808. //文件路径
  1809. // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  1810. NSString* temp = NSTemporaryDirectory();
  1811. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1812. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
  1813. NSString * ver = self.download_task[@"ver"];
  1814. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
  1815. NSString *zipFile = [temp stringByAppendingPathComponent:location];
  1816. ZipArchive* zip = [[ZipArchive alloc] init];
  1817. // filename stringByDeletingPathExtension
  1818. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1819. // NSString *cachefolder = [paths objectAtIndex:0];
  1820. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1821. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1822. //
  1823. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1824. // NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  1825. //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
  1826. // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
  1827. DebugLog(@"path: %@",unZipTo);
  1828. if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
  1829. BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
  1830. if( NO==result )
  1831. {
  1832. // int aaa=0;
  1833. //解压失败
  1834. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1835. if(freespace<=10)
  1836. {
  1837. return UNZIP_NO_SPACE;
  1838. }
  1839. [zip UnzipCloseFile];
  1840. //文件损坏,删除文件重试
  1841. NSFileManager* fileManager=[NSFileManager defaultManager];
  1842. //debug
  1843. // BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
  1844. [fileManager removeItemAtPath:zipFile error:nil];
  1845. [fileManager removeItemAtPath:unZipTo error:nil];
  1846. return UNZIP_FILE_DAMAGE;
  1847. }
  1848. else
  1849. {
  1850. [zip UnzipCloseFile];
  1851. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
  1852. NSFileManager *fileManager = [NSFileManager defaultManager];
  1853. [fileManager removeItemAtPath:zipFile error:nil];
  1854. return UNZIP_SUCCESS;
  1855. //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
  1856. }
  1857. //[zip UnzipCloseFile];
  1858. }
  1859. else
  1860. {
  1861. //打开文件失败,通常是文件路径有问题或密码错误。
  1862. return UNZIP_OPEN_FAILED;
  1863. // NSFileManager *fileManager = [NSFileManager defaultManager];
  1864. // [fileManager removeItemAtPath:zipFile error:nil];
  1865. }
  1866. // [zip release];
  1867. }
  1868. #pragma mark - NSURLConnectionDelegate
  1869. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  1870. DebugLog(@"%d error message:%@",self.current_task,error);
  1871. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1872. // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
  1873. currenttask[@"status"] = @"pause";
  1874. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1875. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1876. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1877. // self.currentLength = 0;
  1878. // self.fileLength = 0;
  1879. [self.fileHandle closeFile];
  1880. self.fileHandle = nil;
  1881. [self.connection cancel];
  1882. self.connection = nil;
  1883. [self download_offline:true checkdiskspace:false];
  1884. }
  1885. #pragma mark - NSURLConnectionDataDelegate
  1886. /**
  1887. *请求失败
  1888. */
  1889. /**
  1890. *接收到服务器的响应
  1891. */
  1892. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  1893. NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
  1894. if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
  1895. DebugLog(@"%d begin",self.current_task);
  1896. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1897. //获取下载文件大小
  1898. // self.fileLength = response.expectedContentLength;
  1899. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1900. //获取文件名
  1901. //self.fileName = response.suggestedFilename;
  1902. currenttask[@"fileName"] = response.suggestedFilename;
  1903. currenttask[@"response"] = @"true";
  1904. [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
  1905. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1906. //文件路径
  1907. NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
  1908. NSString * ver = self.download_task[@"ver"];
  1909. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
  1910. NSString *filePath = [temp stringByAppendingPathComponent:location];
  1911. DebugLog(@"save to: %@",filePath);
  1912. if (position>0) {
  1913. //不需要创建文件;
  1914. //创建一个用来写数据的文件句柄
  1915. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1916. return;
  1917. }
  1918. // 第一次获取的才是文件正确大小
  1919. currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
  1920. //创建一个空的文件到沙盒
  1921. NSFileManager *fileManager = [NSFileManager defaultManager];
  1922. [fileManager createFileAtPath:filePath contents:nil attributes:nil];
  1923. //创建一个用来写数据的文件句柄
  1924. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1925. }else{
  1926. //debug 这里缺少文件的情况还没处理
  1927. [self.connection cancel];
  1928. self.connection = nil;
  1929. DebugLog(@"该文件不存在");
  1930. NSString* str_status=[NSString stringWithFormat:@"Server return %d.",(int)httpresponse.statusCode];
  1931. [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
  1932. [self add_downloadlog:str_status];
  1933. }
  1934. }
  1935. /**
  1936. *接收到服务器返回的数据(可能被调用多次)
  1937. */
  1938. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  1939. //移动到文件末尾
  1940. [self.fileHandle seekToEndOfFile];
  1941. //写入数据到文件
  1942. [self.fileHandle writeData:data];
  1943. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1944. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1945. position += data.length;
  1946. currenttask[@"position"] = [NSNumber numberWithLongLong:position];
  1947. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1948. //更新画面中的进度
  1949. int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
  1950. double progress = (double)position/fileLength;
  1951. self.file_progress = progress;
  1952. [self.settingUI onProgressUpdate];
  1953. }
  1954. /**
  1955. *服务器返回数据完了
  1956. */
  1957. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  1958. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1959. [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
  1960. DebugLog(@"%d finish",self.current_task);
  1961. currenttask[@"position"] = [NSNumber numberWithLongLong:0];
  1962. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1963. // self.currentLength = 0;
  1964. // self.fileLength = 0;
  1965. [self.fileHandle closeFile];
  1966. self.fileHandle = nil;
  1967. int result=[self unpack];
  1968. NSString* temp = NSTemporaryDirectory();
  1969. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1970. NSString * ver = self.download_task[@"ver"];
  1971. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1972. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1973. switch (result) {
  1974. case UNZIP_FILE_DAMAGE:
  1975. {
  1976. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1977. currenttask[@"status"] = @"pause";
  1978. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1979. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1980. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1981. // self.currentLength = 0;
  1982. // self.fileLength = 0;
  1983. [self.fileHandle closeFile];
  1984. self.fileHandle = nil;
  1985. [self.connection cancel];
  1986. self.connection = nil;
  1987. break;
  1988. }
  1989. case UNZIP_SUCCESS:
  1990. {
  1991. NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
  1992. if([type isEqualToString:@"img"])
  1993. {
  1994. NSString* parent_path = self.download_task[@"path"];
  1995. if(parent_path.length==0)
  1996. parent_path=@"";
  1997. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  1998. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  1999. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
  2000. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  2001. BOOL bdir=YES;
  2002. NSError *error = nil;
  2003. if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
  2004. {
  2005. bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  2006. if(!bsuccess)
  2007. DebugLog(@"Create temp folder failed");
  2008. }
  2009. error=nil;
  2010. // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
  2011. // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
  2012. // NSError *error = nil;
  2013. // NSURL* uf=[NSURL fileURLWithPath:imagecache];
  2014. // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
  2015. // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
  2016. // backupItemName:backup
  2017. // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
  2018. // resultingItemURL:nil error:&error])
  2019. if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
  2020. // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
  2021. {
  2022. DebugLog(@"move image folder failed");
  2023. }
  2024. else
  2025. {
  2026. currenttask[@"status"] = @"finish";
  2027. DebugLog(@"move image folder successful");
  2028. }
  2029. }
  2030. else if([type isEqualToString:@"sql"])
  2031. {
  2032. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  2033. NSString * ver = self.download_task[@"ver"];
  2034. NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
  2035. tempdb=[temp stringByAppendingPathComponent:tempdb];
  2036. sqlite3* tdb=[iSalesDB get_db_at:tempdb];
  2037. [self add_downloadlog:@"updating local database..."];
  2038. @try {
  2039. char *errmsg=NULL;
  2040. // [iSalesDB disable_trigger]
  2041. [iSalesDB disable_trigger];
  2042. if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
  2043. {
  2044. 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);
  2045. sqlite3_free(errmsg);
  2046. DebugLog(@"开启事务");
  2047. NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
  2048. NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
  2049. int count = [orderjson[@"count"] intValue];
  2050. for(int i=0;i<count;i++)
  2051. {
  2052. NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
  2053. NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
  2054. NSError *error = nil;
  2055. NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
  2056. //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
  2057. if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
  2058. {
  2059. //throw exception;
  2060. if(errmsg==nil)
  2061. errmsg="Unknown error.";
  2062. NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
  2063. [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
  2064. }
  2065. sqlite3_free(errmsg);
  2066. }
  2067. 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);
  2068. }
  2069. //提交事务
  2070. if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
  2071. DebugLog(@"提交事务");
  2072. sqlite3_free(errmsg);
  2073. }
  2074. [self add_downloadlog:@"updating local database successful"];
  2075. currenttask[@"status"] = @"finish";
  2076. }
  2077. @catch (NSException *exception) {
  2078. char *errmsg=NULL;
  2079. [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
  2080. [self add_downloadlog:@"updating local database failed rollback..."];
  2081. if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
  2082. DebugLog(@"回滚事务");
  2083. }
  2084. else
  2085. {
  2086. [self add_downloadlog:@"rollback failed."];
  2087. }
  2088. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  2089. currenttask[@"status"] = @"pause";
  2090. //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  2091. currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
  2092. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  2093. // self.currentLength = 0;
  2094. // self.fileLength = 0;
  2095. [self.fileHandle closeFile];
  2096. self.fileHandle = nil;
  2097. [self.connection cancel];
  2098. self.connection = nil;
  2099. //break;
  2100. }
  2101. @finally {
  2102. // [iSalesDB enable_trigger]
  2103. [iSalesDB enable_trigger];
  2104. sqlite3_close(tdb);
  2105. // [iSalesDB close_db:tdb];
  2106. // [self SelectData];
  2107. }
  2108. }
  2109. else if([type isEqualToString:@"script"])
  2110. {
  2111. currenttask[@"status"] = @"finish";
  2112. }
  2113. else if([type isEqualToString:@"resource"])
  2114. {
  2115. currenttask[@"status"] = @"finish";
  2116. }
  2117. // debug
  2118. // int c=self.current_task+1;
  2119. // double t=[ self.download_task[@"count"] doubleValue];
  2120. double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
  2121. self.overall_progress = oprogress;
  2122. [self.settingUI onProgressUpdate];
  2123. break;
  2124. }
  2125. case UNZIP_NO_SPACE:
  2126. {
  2127. [self add_downloadlog:@"Disk space not enough."];
  2128. break;
  2129. }
  2130. case UNZIP_OPEN_FAILED:
  2131. {
  2132. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
  2133. break;
  2134. }
  2135. default:
  2136. break;
  2137. }
  2138. [self download_offline:true checkdiskspace:false];
  2139. }
  2140. -(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
  2141. {
  2142. RAPDFViewController *ViewController = [[UIStoryboard storyboardWithName:@"wkweb" bundle:nil] instantiateViewControllerWithIdentifier:@"RAPDFViewController"];
  2143. ViewController.url = url;
  2144. ViewController.canSave = false;
  2145. ViewController.mail_content = content;
  2146. if(soid==nil)
  2147. soid =@"";
  2148. if(company==nil)
  2149. company =@"";
  2150. ViewController.save_name =soid;
  2151. NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
  2152. if(send_to.length>0)
  2153. {
  2154. arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2155. // customer_email compo
  2156. // [send_to addObject:customer_email];
  2157. }
  2158. ViewController.mail_to = arrsend_to;
  2159. #if defined(BUILD_NPD) || defined(BUILD_USAI)|| defined (BUILD_CONTRAST)
  2160. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];//[arr_subject componentsJoinedByString:@" : "];
  2161. if (self.user_type == USER_ROLE_CUSTOMER && ![RASingleton sharedInstance].currentOrderIsMerged) {
  2162. NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
  2163. subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
  2164. }
  2165. #else
  2166. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];
  2167. #endif
  2168. ViewController.mail_subject = subject;
  2169. // NSString* subject;
  2170. // if (company.length==0) {
  2171. // NSString* cur_time =[RAUtils current_date];
  2172. // subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
  2173. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  2174. // NSString* customer_email= [appDelegate.customerInfo valueForKey:@"customer_email"];
  2175. //
  2176. //
  2177. // NSMutableArray* send_to = [[NSMutableArray alloc]init];
  2178. // if(customer_email.length>0)
  2179. // {
  2180. // send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2181. // // customer_email compo
  2182. // // [send_to addObject:customer_email];
  2183. // }
  2184. // ViewController.mail_to = send_to;
  2185. // }
  2186. // else
  2187. // {
  2188. // subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
  2189. // }
  2190. // ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
  2191. // ViewController.mail_subject = subject;
  2192. ViewController.autoPrint=true;
  2193. ViewController.hidenavi = false;
  2194. [self.main_vc.navigationController pushViewController:ViewController animated:YES];
  2195. // [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
  2196. }
  2197. //-(void) addScannerReceiver:(NSString*)classname
  2198. //{
  2199. // [self.arr_scannerReceiver addObject:classname];
  2200. //}
  2201. -(void) setScannerDelegate:(id<ScanApiHelperDelegate>)delegate
  2202. {
  2203. [ScanApi setDelegate:delegate];
  2204. }
  2205. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2206. {
  2207. self.compressFile = [[RAUPloadManagerConfigure alloc] init].compressImage;
  2208. #ifdef OFFLINE_ORDER
  2209. #endif
  2210. self.window.backgroundColor = [UIColor whiteColor];
  2211. // [RAUtils expression_varable:nil regex:nil];
  2212. // self.disable_trigger = false;
  2213. [iSalesDB enable_trigger];
  2214. [self initialExceptionHandler];
  2215. [self becomeObserver];
  2216. #ifdef GOOGLE_ANALYTICS
  2217. [self setUpGoogleAnalytics];
  2218. #endif
  2219. [DefaultAppearance init_appearance];
  2220. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2221. NSString *cachefolder = [paths objectAtIndex:0];
  2222. NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
  2223. // upfolder = [upfolder stringByAppendingPathComponent:serial];
  2224. NSFileManager* fileManager = [NSFileManager defaultManager];
  2225. BOOL bdir=YES;
  2226. if(! [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
  2227. {
  2228. NSError *error = nil;
  2229. bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
  2230. if(!bsuccess)
  2231. DebugLog(@"Create UPLOAD folder failed");
  2232. }
  2233. NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  2234. if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
  2235. {
  2236. NSError *error = nil;
  2237. bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
  2238. if(!bsuccess)
  2239. DebugLog(@"Create PDF Cache folder failed");
  2240. }
  2241. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2242. //
  2243. // DebugLog(@"文件已经存在了");
  2244. //
  2245. // }
  2246. // NSString* order_filter_source_path =[[NSBundle mainBundle] pathForResource:@"status_filter_cadedate" ofType:@"json" ];
  2247. // /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
  2248. //
  2249. //
  2250. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2251. // NSString *documents = [paths objectAtIndex:0];
  2252. // NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
  2253. //
  2254. //
  2255. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  2256. //
  2257. // DebugLog(@"文件已经存在了");
  2258. //
  2259. // }
  2260. // else
  2261. // {
  2262. //
  2263. //
  2264. //
  2265. // // DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
  2266. //
  2267. // NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
  2268. //
  2269. // // DebugLog(@"mainBundleFile==%@",mainBundleFile);
  2270. //
  2271. // [[NSFileManager defaultManager] createFileAtPath:dist_path
  2272. //
  2273. // contents:mainBundleFile
  2274. //
  2275. // attributes:nil];
  2276. //
  2277. // }
  2278. self.recent_model = [[NSMutableDictionary alloc]init];
  2279. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2280. bool offline = [defaults boolForKey:@"EnableOfflineMode"] ;
  2281. self.offline_mode = offline;
  2282. // Override point for customization after application launch.
  2283. if ( [iSalesDB initializeDb]!=0)
  2284. DebugLog(@"init db failed");
  2285. // disable apn
  2286. // [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
  2287. self.contact_id=nil;
  2288. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2289. NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
  2290. if([enable_cache isEqualToString:@"false"])
  2291. self.bEnable_Cache = false;
  2292. else
  2293. self.bEnable_Cache = true;
  2294. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  2295. self.build =[infoDict objectForKey:@"CFBundleVersion"];
  2296. //scanner
  2297. _feedbackStack=[[NSMutableArray alloc]init];
  2298. self.devices=[[NSMutableArray alloc]init];
  2299. // change this to YES if you want SingleEntry to
  2300. // confirm the decoded data
  2301. self.doAppDataConfirmation=NO;
  2302. if(ScanApi==nil){
  2303. #ifdef USE_SOFTSCAN
  2304. // this is useful for SoftScan to keep a handle
  2305. // that is used in the trigger button
  2306. _softScanDeviceInfo=nil;
  2307. #endif
  2308. ScanApi=[[ScanApiHelper alloc]init];
  2309. [ScanApi setDelegate:self];
  2310. self.enable_ScannerLog = true;
  2311. self.api_Status= API_STOP;
  2312. // UIApplication * app = [UIApplication sharedApplication];
  2313. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  2314. //
  2315. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  2316. bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
  2317. if(autolaunch==true)
  2318. [self enableScanner:autolaunch];
  2319. }
  2320. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  2321. [self handleErrorLog];
  2322. });
  2323. return YES;
  2324. }
  2325. #pragma mark - Feedback stack
  2326. -(void)pushFeedback:(id<ScannerEventsFeedback>)feedback{
  2327. long index =[_feedbackStack indexOfObject:feedback];
  2328. if(index!=NSNotFound)
  2329. {
  2330. // if(index!=_feedbackStack.count-1)
  2331. // {
  2332. // [_feedbackStack exchangeObjectAtIndex:index withObjectAtIndex:_feedbackStack.count-1];
  2333. // _eventsFeedback = feedback;
  2334. // }
  2335. }
  2336. else
  2337. {
  2338. [_feedbackStack addObject:feedback];
  2339. }
  2340. _eventsFeedback = feedback;
  2341. // if(_eventsFeedback != feedback){
  2342. // if(_eventsFeedback!=nil){
  2343. // [_feedbackStack addObject:_eventsFeedback];
  2344. // }
  2345. // _eventsFeedback=feedback;
  2346. //// [self generateDeviceArrivals];
  2347. // }
  2348. }
  2349. -(void)popFeedback:(id<ScannerEventsFeedback>)feedback{
  2350. [_feedbackStack removeObject:feedback];
  2351. if(_feedbackStack.count>0)
  2352. _eventsFeedback = _feedbackStack[_feedbackStack.count-1];
  2353. else
  2354. _eventsFeedback = nil;
  2355. // if(_eventsFeedback ==feedback){
  2356. // if(_feedbackStack.count>0){
  2357. // id<ScannerEventsFeedback> newDelegate=[_feedbackStack objectAtIndex:_feedbackStack.count-1];
  2358. // [_feedbackStack removeLastObject];
  2359. // _eventsFeedback = newDelegate;
  2360. // // generate a device Arrival for each scanner we've already receive
  2361. // // so that the new view can be aware of the connected scanners
  2362. //// [self generateDeviceArrivals];
  2363. // }
  2364. // else{
  2365. // _eventsFeedback=nil;
  2366. // }
  2367. // }
  2368. }
  2369. -(void)setFeedback:(id<ScannerEventsFeedback>)feedback
  2370. {
  2371. _eventsFeedback = feedback;
  2372. }
  2373. #pragma mark - ScanApiHelper complete delegates
  2374. // THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
  2375. // TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
  2376. // IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
  2377. // CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
  2378. // THE SCANNER, THESE CALLBACKS CAN BE REMOVED
  2379. // callback received when the Get Symbology Status is completed
  2380. -(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
  2381. [self addlog:@"onGetSymbologyDpm:"];
  2382. SKTRESULT result=[[scanObj Msg]Result];
  2383. if(SKTSUCCESS(result)){
  2384. DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
  2385. if(deviceInfo!=nil){
  2386. ISktScanSymbology* symbology=[[scanObj Property]Symbology];
  2387. if([symbology getStatus]==kSktScanSymbologyStatusDisable){
  2388. [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
  2389. }
  2390. }
  2391. }
  2392. else{
  2393. // an error message should be displayed here
  2394. // indicating that the DPM symbology status cannot be retrieved
  2395. }
  2396. }
  2397. // callback received when the Set Symbology Status is completed
  2398. -(void)onSetSymbology:(ISktScanObject*)scanObj{
  2399. [self addlog:@"onSetSymbology:"];
  2400. SKTRESULT result=[[scanObj Msg]Result];
  2401. if(!SKTSUCCESS(result)){
  2402. // display an error message saying a symbology cannot be set
  2403. }
  2404. }
  2405. /**
  2406. *
  2407. */
  2408. -(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
  2409. [self addlog:@"onSetDataConfirmationMode:"];
  2410. SKTRESULT result=[[scanObj Msg]Result];
  2411. if(SKTSUCCESS(result)){
  2412. [self addlog:@"DataConfirmation Mode OK"];
  2413. }
  2414. else{
  2415. [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
  2416. }
  2417. }
  2418. /**
  2419. *
  2420. */
  2421. -(void) onDataConfirmation:(ISktScanObject*)scanObj{
  2422. [self addlog:@"onDataConfirmation:"];
  2423. SKTRESULT result=[[scanObj Msg]Result];
  2424. if(SKTSUCCESS(result)){
  2425. [self addlog:@"Data Confirmed OK"];
  2426. }
  2427. else{
  2428. [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
  2429. }
  2430. }
  2431. /**
  2432. *
  2433. */
  2434. -(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
  2435. [self addlog:@"onSetLocalDecodeAction:"];
  2436. SKTRESULT result=[[scanObj Msg]Result];
  2437. if(SKTSUCCESS(result)){
  2438. [self addlog:@"Local Decode Action OK"];
  2439. }
  2440. else{
  2441. [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
  2442. }
  2443. }
  2444. /**
  2445. *
  2446. */
  2447. -(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
  2448. SKTRESULT result=[[scanObj Msg]Result];
  2449. if(SKTSUCCESS(result)){
  2450. ISktScanProperty* property=[scanObj Property];
  2451. [self addlog:@"SoftScan status:"];
  2452. if([property getByte]==kSktScanEnableSoftScan){
  2453. [self addlog:@"SoftScan is ENABLED"];
  2454. _softScannerEnabled=TRUE;
  2455. }
  2456. else{
  2457. _softScannerEnabled=FALSE;
  2458. [self addlog:@"SoftScan is DISABLED"];
  2459. }
  2460. }
  2461. else{
  2462. [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
  2463. }
  2464. }
  2465. /**
  2466. *
  2467. */
  2468. -(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
  2469. [self addlog:@"onSetSoftScanStatus:"];
  2470. SKTRESULT result=[[scanObj Msg]Result];
  2471. if(SKTSUCCESS(result)){
  2472. [self addlog:@"SoftScan set status success"];
  2473. }
  2474. else{
  2475. [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
  2476. }
  2477. }
  2478. /**
  2479. *
  2480. */
  2481. -(void) onSetTrigger:(ISktScanObject*)scanObj{
  2482. [self addlog:@"onSetTrigger:"];
  2483. SKTRESULT result=[[scanObj Msg]Result];
  2484. if(SKTSUCCESS(result)){
  2485. [self addlog:@"Trigger set success"];
  2486. }
  2487. else{
  2488. [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
  2489. }
  2490. }
  2491. /**
  2492. *
  2493. */
  2494. -(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
  2495. [self addlog:@"onGetScanApiVersion:"];
  2496. SKTRESULT result=[[scanObj Msg]Result];
  2497. if(SKTSUCCESS(result))
  2498. {
  2499. ISktScanProperty*property=[scanObj Property];
  2500. if([property getType]==kSktScanPropTypeVersion)
  2501. {
  2502. scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
  2503. [[property Version]getMajor],
  2504. [[property Version]getMiddle],
  2505. [[property Version]getMinor],
  2506. [[property Version]getBuild]];
  2507. }
  2508. }
  2509. else{
  2510. scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
  2511. }
  2512. [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
  2513. }
  2514. /**
  2515. *
  2516. */
  2517. #ifdef USE_SOFTSCAN
  2518. -(void) onSetOverlayView:(ISktScanObject*)scanObj{
  2519. SKTRESULT result=[[scanObj Msg]Result];
  2520. if(SKTSUCCESS(result)){
  2521. [self addlog:@"Overlay view set success"];
  2522. }
  2523. else{
  2524. [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
  2525. }
  2526. }
  2527. #endif
  2528. /**
  2529. * called each time a device connects to the host
  2530. * @param result contains the result of the connection
  2531. * @param newDevice contains the device information
  2532. */
  2533. -(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
  2534. [self addlog:@"onDeviceArrival:"];
  2535. [self updateDevicesList:deviceInfo Add:YES];
  2536. #ifdef USE_SOFTSCAN
  2537. // if the scanner is a SoftScan scanner
  2538. if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
  2539. // _softScannerTriggerBtn.hidden=NO;
  2540. _softScanDeviceInfo=deviceInfo;
  2541. if(_deviceInfoToTrigger==nil)
  2542. _deviceInfoToTrigger=deviceInfo;
  2543. NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
  2544. [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
  2545. [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
  2546. }
  2547. else
  2548. #endif
  2549. {
  2550. if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
  2551. // _softScannerTriggerBtn.hidden=NO;
  2552. _deviceInfoToTrigger=deviceInfo;
  2553. }
  2554. if(_doAppDataConfirmation==YES){
  2555. // switch the comment between the 2 following lines for handling the
  2556. // data confirmation beep from the scanner (local)
  2557. // if none is set, the scanner will beep only once when SingleEntry actually
  2558. // confirm the decoded data, otherwise the scanner will beep twice, one locally,
  2559. // and one when SingleEntry will confirm the decoded data
  2560. [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
  2561. // [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
  2562. }
  2563. // for demonstration only, let's make sure the DPM is enabled
  2564. // first interrogate the scanner to see if it's already enabled
  2565. // and in the onGetSymbologyDpm callback, if the DPM is not already set
  2566. // then we send a Symbology property to enable it.
  2567. [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
  2568. }
  2569. }
  2570. /**
  2571. * called each time a device disconnect from the host
  2572. * @param deviceRemoved contains the device information
  2573. */
  2574. -(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
  2575. [self addlog:@"onDeviceRemoval:"];
  2576. [self updateDevicesList:deviceRemoved Add:NO];
  2577. if(_deviceInfoToTrigger==deviceRemoved){
  2578. _deviceInfoToTrigger=nil;
  2579. }
  2580. #ifdef USE_SOFTSCAN
  2581. if(_softScanDeviceInfo==deviceRemoved){
  2582. _softScanDeviceInfo=nil;
  2583. }
  2584. if(_deviceInfoToTrigger==nil)
  2585. _deviceInfoToTrigger=_softScanDeviceInfo;
  2586. #endif
  2587. if(_deviceInfoToTrigger==nil){
  2588. // _softScannerTriggerBtn.hidden=YES;
  2589. }
  2590. }
  2591. /**
  2592. * called each time ScanAPI is reporting an error
  2593. * @param result contains the error code
  2594. */
  2595. -(void) onError:(SKTRESULT) result{
  2596. [self addlog:@"onError:"];
  2597. [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2598. #ifdef RA_NOTIFICATION
  2599. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2600. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2601. }
  2602. #else
  2603. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2604. [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2605. #endif
  2606. // _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
  2607. }
  2608. /**
  2609. * called each time ScanAPI receives decoded data from scanner
  2610. * @param deviceInfo contains the device information from which
  2611. * the data has been decoded
  2612. * @param decodedData contains the decoded data information
  2613. */
  2614. -(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2615. [self addlog:@"onDecodedDataResult:"];
  2616. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2617. if(SKTSUCCESS(result)){
  2618. NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  2619. #ifdef RA_NOTIFICATION
  2620. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2621. [_eventsFeedback onDecodedData:cleanString];
  2622. }
  2623. #else
  2624. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2625. [avc onDecodedData:cleanString];
  2626. #endif
  2627. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2628. [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
  2629. if(_doAppDataConfirmation==YES){
  2630. [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2631. }
  2632. }
  2633. }
  2634. -(void) test_onDecodedDataResult:(NSString*) value
  2635. {
  2636. [self addlog:@"onDecodedDataResult:"];
  2637. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2638. if(true){
  2639. #ifdef RA_NOTIFICATION
  2640. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
  2641. [_eventsFeedback onDecodedData:value];
  2642. }
  2643. #else
  2644. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2645. [avc onDecodedData:value];
  2646. #endif
  2647. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2648. [self addlog:value];
  2649. // if(_doAppDataConfirmation==YES){
  2650. // [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2651. // }
  2652. }
  2653. }
  2654. //-(void) didRotated
  2655. //{
  2656. //
  2657. //}
  2658. /**
  2659. * called when ScanAPI initialization has been completed
  2660. * @param result contains the initialization result
  2661. */
  2662. -(void) onScanApiInitializeComplete:(SKTRESULT) result{
  2663. [self addlog:@"onScanApiInitializeComplete:"];
  2664. if(SKTSUCCESS(result))
  2665. {
  2666. self.api_Status = API_START;
  2667. NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
  2668. [self addlog:strlog];
  2669. #ifdef USE_SOFTSCAN
  2670. // make sure we support SoftScan
  2671. [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2672. // check if SoftScan is enabled
  2673. [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
  2674. #else
  2675. // disable support SoftScan (Default, not really needed if it was never activated)
  2676. [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2677. #endif
  2678. // ask for ScanAPI version (not a requirement but always nice to know)
  2679. [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
  2680. // configure ScanAPI for doing App Data confirmation,
  2681. // if TRUE then SingleEntry will confirm the decoded data
  2682. if(_doAppDataConfirmation==YES){
  2683. [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
  2684. }
  2685. #ifdef RA_NOTIFICATION
  2686. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2687. [_eventsFeedback onStatusChanged:@"Waiting for scanner..."];
  2688. }
  2689. #else
  2690. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2691. [avc onStatusChanged:@"Waiting for scanner..."];
  2692. #endif
  2693. self.Status_Text = @"Waiting for scanner...";
  2694. // _Status.text=@"Waiting for scanner...";
  2695. }
  2696. else{
  2697. #ifdef RA_NOTIFICATION
  2698. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2699. [_eventsFeedback onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2700. }
  2701. #else
  2702. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2703. [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2704. #endif
  2705. self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2706. // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2707. NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2708. [self addlog:strlog];
  2709. }
  2710. }
  2711. /**
  2712. * called when ScanAPI has been terminated. This will be
  2713. * the last message received from ScanAPI
  2714. */
  2715. -(void) onScanApiTerminated{
  2716. [self addlog:@"onScanApiTerminated:"];
  2717. [ScanApiConsumer invalidate];
  2718. ScanApiConsumer= nil;
  2719. [self addlog:@"ScanApiConsumer invalidate"];
  2720. self.api_Status = API_STOP;
  2721. #ifdef RA_NOTIFICATION
  2722. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2723. [_eventsFeedback onStatusChanged:@"Off"];
  2724. }
  2725. #else
  2726. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2727. [avc onStatusChanged:@"Off"];
  2728. #endif
  2729. self.Status_Text =@"Off";
  2730. // _Status.text = @"Off";
  2731. }
  2732. /**
  2733. * called when an error occurs during the retrieval
  2734. * of a ScanObject from ScanAPI.
  2735. * @param result contains the retrieval error code
  2736. */
  2737. -(void) onErrorRetrievingScanObject:(SKTRESULT) result{
  2738. [self addlog:@"onErrorRetrievingScanObject:"];
  2739. [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2740. //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
  2741. #ifdef RA_NOTIFICATION
  2742. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
  2743. [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2744. }
  2745. #else
  2746. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2747. [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2748. #endif
  2749. }
  2750. #pragma mark - Scaner
  2751. -(void)onTimer: (NSTimer*)theTimer{
  2752. if(theTimer==ScanApiConsumer){
  2753. // [self addlog:@"ScanApi::doScanApiReceive:"];
  2754. [ScanApi doScanApiReceive];
  2755. }
  2756. }
  2757. -(void) addlog:(NSString*) newtext
  2758. {
  2759. if(!self.enable_ScannerLog)
  2760. return;
  2761. dispatch_async(dispatch_get_main_queue(), ^{
  2762. NSString* date;
  2763. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  2764. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  2765. date = [formatter stringFromDate:[NSDate date]];
  2766. if(newtext.length<=0)
  2767. return;
  2768. NSString* text = self.log;
  2769. if(text.length==0)
  2770. text=@"";
  2771. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  2772. self.log = text;
  2773. #ifdef RA_NOTIFICATION
  2774. if((self->_eventsFeedback!=nil)&&([self->_eventsFeedback respondsToSelector:@selector(onLogUpdate)])){
  2775. [self->_eventsFeedback onLogUpdate];
  2776. }
  2777. #else
  2778. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2779. [avc onLogUpdate];
  2780. #endif
  2781. });
  2782. }
  2783. - (void)enableScanner:(bool)enable {
  2784. [self addlog:@"Enable scanner:"];
  2785. if(enable)
  2786. {
  2787. [self addlog:@"Enable"];
  2788. self.api_Status = API_INIT;
  2789. #ifdef RA_NOTIFICATION
  2790. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2791. [_eventsFeedback onStatusChanged:@"Initialize..."];
  2792. }
  2793. #else
  2794. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2795. [avc onStatusChanged:@"Initialize..."];
  2796. #endif
  2797. self.Status_Text = @"Initialize...";
  2798. [ScanApi open];
  2799. [self addlog:@"ScanApi open"];
  2800. ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
  2801. [self addlog:@"ScanApiConsumer init"];
  2802. // [ScanApi close];
  2803. // [self addlog:@"ScanApi opent"];
  2804. }
  2805. else
  2806. {
  2807. [self addlog:@"Disable"];
  2808. // [ScanApiConsumer invalidate];
  2809. // ScanApiConsumer= nil;
  2810. // [self addlog:@"ScanApiConsumer invalidate"];
  2811. self.api_Status = API_CLOSING;
  2812. #ifdef RA_NOTIFICATION
  2813. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2814. [_eventsFeedback onStatusChanged:@"Stoping..."];
  2815. }
  2816. #else
  2817. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2818. [avc onStatusChanged:@"Stoping..."];
  2819. #endif
  2820. self.Status_Text = @"Stoping...";
  2821. [ScanApi close];
  2822. [self addlog:@"ScanApi close"];
  2823. }
  2824. }
  2825. #pragma mark - Device Info List management
  2826. -(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
  2827. [self addlog:@"updateDevicesList:"];
  2828. if(add==YES){
  2829. [self.devices addObject:deviceInfo];
  2830. }
  2831. else{
  2832. [self.devices removeObject:deviceInfo];
  2833. }
  2834. NSMutableString* temp=[[NSMutableString alloc]init];
  2835. for (DeviceInfo* info in self.devices) {
  2836. [temp appendString:[info getName]];
  2837. [temp appendString:@"\n"];
  2838. }
  2839. if(self.devices.count>0)
  2840. [temp appendString:@"ready to scan"];
  2841. else
  2842. [temp appendString:@"Waiting for Scanner..."];
  2843. // _Status.text=temp ;
  2844. [self addlog:temp];
  2845. #ifdef RA_NOTIFICATION
  2846. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
  2847. [_eventsFeedback onStatusChanged:temp];
  2848. }
  2849. if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
  2850. [_eventsFeedback OnUpdateDevicesList];
  2851. }
  2852. #else
  2853. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2854. [avc onStatusChanged:temp];
  2855. [avc OnUpdateDevicesList];
  2856. #endif
  2857. self.Status_Text = temp;
  2858. // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
  2859. // [self.dev_table reloadData];
  2860. }
  2861. #pragma mark - offline order
  2862. -(void) backup_oc
  2863. {
  2864. }
  2865. -(void) restore_oc
  2866. {
  2867. }
  2868. #pragma mark - upload manager
  2869. - (void)saveUploadTasks {
  2870. if(true)
  2871. {
  2872. if(self.uploadManager.arr_queue!=nil)
  2873. {
  2874. [self.uploadManager stopAllTasks];
  2875. }
  2876. [self.uploadManager saveTasks];
  2877. return;
  2878. }
  2879. }
  2880. - (NSMutableArray *)cachedUploadTasks {
  2881. if (!self.user) {
  2882. return nil;
  2883. }
  2884. NSString *path = [[RAUtils appCacheDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_uploadTasks",self.user]];
  2885. NSFileManager *manager = [NSFileManager defaultManager];
  2886. if ([manager fileExistsAtPath:path]) {
  2887. NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:path];
  2888. [manager removeItemAtPath:path error:nil];
  2889. return arr;
  2890. }
  2891. return nil;
  2892. }
  2893. @end