// // NewTopicVC.m // smartRhino // // Created by niuzhen on 2019/12/14. // Copyright © 2019 tederen. All rights reserved. // #import "NewTopicVC.h" #import "LYLPhotoTailoringTool.h" #import "FWZFileGetTool.h" #import "FWZGetNoteBookTool.h" #import "RichTextEditViewController.h" #import "AddLookUpUserSecondVC.h" @interface NewTopicVC () @property (weak, nonatomic) IBOutlet UIView *NavBarV; @property (weak, nonatomic) IBOutlet UIButton *DoneBtn; @property (nonatomic,strong) WKWebView *webView; @property (nonatomic,assign) CGFloat keyBoardH; @property (nonatomic,assign) BOOL isShoujianren; @property (nonatomic,assign) BOOL isChaosongren; @property (nonatomic,strong) NSMutableArray *chaoShongArray; @property (nonatomic,strong) NSMutableArray *shouJianArray; @end @implementation NewTopicVC + (NewTopicVC *)initNewTopicVC{ NewTopicVC *controller = [StoryboardManager.shared.TDGroupInfo instantiateViewControllerWithIdentifier:@"NewTopicVC"]; return controller; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[IQKeyboardManager sharedManager] setEnable:YES]; } - (void)viewDidLoad { [super viewDidLoad]; self.fd_prefersNavigationBarHidden = YES; WS(weakSelf); [self.DoneBtn setAction:^{ [weakSelf submit]; }]; NSURL *pathUrl = [NSURL URLWithString:@"http://192.168.0.118:8080/#/mobile/editor"]; // NSURL *pathUrl = [NSURL URLWithString:@"http://192.168.0.119:8080/#/mobile/topicDetails"]; NSURLRequest *request = [NSURLRequest requestWithURL:pathUrl]; [self.webView loadRequest:request]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recviveChaoSongRen:) name:NOTIFI_ChaoSongRen object:nil]; } - (void)upDateAction:(NSString *)action { [self.webView evaluateJavaScript:action completionHandler:^(id _Nullable data, NSError * _Nullable error) { NSLog(@"上传成功"); }]; } #pragma mark - layload - (WKWebView *)webView { if (!_webView) { WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; // 实例化对象 WKUserContentController* userContent = [[WKUserContentController alloc] init]; [userContent addScriptMessageHandler:self name:@"chosePic"]; [userContent addScriptMessageHandler:self name:@"toPZ"]; [userContent addScriptMessageHandler:self name:@"toBJ"]; [userContent addScriptMessageHandler:self name:@"toSC"]; [userContent addScriptMessageHandler:self name:@"toWJ"]; [userContent addScriptMessageHandler:self name:@"keyBoard"]; [userContent addScriptMessageHandler:self name:@"approverCheckUsers"]; [userContent addScriptMessageHandler:self name:@"carbonCopyUsers"]; [userContent addScriptMessageHandler:self name:@"getType"]; configuration.userContentController = userContent; WKPreferences *preferences = [WKPreferences new]; preferences.javaScriptCanOpenWindowsAutomatically = YES; preferences.minimumFontSize = 40.0; configuration.preferences = preferences; // 初始化WKWebView _webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:configuration]; // UI代理 _webView.UIDelegate = self; // 导航代理 _webView.navigationDelegate = self; _webView.scrollView.delegate = self; } return _webView; } -(NSMutableArray *)shouJianArray{ if(!_shouJianArray){ _shouJianArray = [[NSMutableArray alloc] init]; } return _shouJianArray; } -(NSMutableArray *)chaoShongArray{ if(!_chaoShongArray){ _chaoShongArray = [[NSMutableArray alloc] init]; } return _chaoShongArray; } #pragma mark - KeyBoard - (void)keyBoardWillShow:(NSNotification *)note { // 获取用户信息 NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo]; // 获取键盘高度 CGRect keyBoardBounds = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; self.keyBoardH = keyBoardBounds.size.height; [self.webView evaluateJavaScript:@"textFocus()" completionHandler:^(id _Nullable data, NSError * _Nullable error) { NSLog(@"keyShow"); }]; } - (void)keyBoardWillHide:(NSNotification *)note { self.keyBoardH = 0.f; [self.webView evaluateJavaScript:@"blur()" completionHandler:^(id _Nullable data, NSError * _Nullable error) { NSLog(@"keyHidden"); }]; } #pragma mark - WKScriptMessageHandler - (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message { WS(weakSelf); NSLog(@"messageName:%@",message.name); if ([message.name isEqualToString:@"chosePic"]) { [self chatBarDidPhotoAction]; } if ([message.name isEqualToString:@"toPZ"]) { [[LYLPhotoTailoringTool sharedTool] selectPhotoWithPhoroOrCamera:SelectPhotoWithTypePhoroOrCamera2 crop:YES showImgBlock:^(NSString *imageUrlStr) { } choosImgBlock:^(UIImage *image) { [weakSelf didSelectImage:@[image]]; }]; } if ([message.name isEqualToString:@"toBJ"]) { [[FWZGetNoteBookTool sharedTool] openNoteBookListChooseNoteBookBlock:^(NSMutableArray * _Nonnull noteArr) { NSLog(@"SmartBarNotes %@",noteArr); [weakSelf disSelectNoteBook:noteArr]; }]; } if ([message.name isEqualToString:@"toSC"]) { [[FWZGetNoteBookTool sharedTool] openCollectListChooseCollectBlock:^(NSMutableArray * _Nonnull collectArr) { NSLog(@"SmartBarCollection %@",collectArr); [weakSelf disSelectCollect:collectArr]; }]; } if ([message.name isEqualToString:@"toWJ"]) { [[FWZFileGetTool sharedTool] openFileWithCrop:YES showImgBlock:^(NSString * _Nonnull fileUrlStr) { } choosFileBlock:^(NSData * _Nonnull fileData, NSString * _Nonnull fileName) { SHOWLOADING [[HttpManager sharedHttpManager] HeaderUploadFileUrl:Host(Modify_UserImages_Post) parameters:@{} fileData:fileData fileKey:@"file" fileName:fileName mimeType:@"multipart/form-data" success:^(id _Nonnull responseObject) { REMOVESHOW NSLog(@"上传成功的文件%@",responseObject); NSString *jsonString = [NSString stringWithFormat:@"getAndroidImg('%@','%@','%ld')",responseObject[@"AbsolutePath"],responseObject[@"FileName"],(long)CollectDataType_File]; [weakSelf upDateAction:jsonString]; } failure:^(NSError * _Nonnull error) { REMOVESHOW }]; }]; } if ([message.name isEqualToString:@"keyBoard"]) { NSString *jsonString = [NSString stringWithFormat:@"getIosKeyBorad('%f')",self.keyBoardH]; [self.webView evaluateJavaScript:jsonString completionHandler:^(id _Nullable data, NSError * _Nullable error) { }]; } if ([message.name isEqualToString:@"approverCheckUsers"]) { self.isShoujianren = YES; self.isChaosongren = NO; [self selectPeopleWithType:1]; } if ([message.name isEqualToString:@"carbonCopyUsers"]) { self.isShoujianren = NO; self.isChaosongren = YES; [self selectPeopleWithType:2]; } if ([message.name isEqualToString:@"getType"]) { NSString *jsonString = [NSString stringWithFormat:@"getType('%d','%d','%d','%@')",1,1,622,USERDEFAULTSGET(@"LOGINTOKEN")]; [self.webView evaluateJavaScript:jsonString completionHandler:^(id _Nullable data, NSError * _Nullable error) { NSLog(@"data:%@",data); NSLog(@"error:%@",error); }]; } } - (void)selectPeopleWithType:(NSInteger)type { AddLookUpUserSecondVC *vc = [[AddLookUpUserSecondVC alloc] init]; vc.isAllSelected = YES; Department *defaltGroupSetion = [[Department alloc]init]; defaltGroupSetion.Name = @"单位通讯录"; defaltGroupSetion.Id = 0; defaltGroupSetion.SourceId = 0; defaltGroupSetion.SourceType = 1; defaltGroupSetion.SourceName = @"单位通讯录"; defaltGroupSetion.MiddleType = type; Department *myGroupSetion = [[Department alloc]init]; myGroupSetion.Name = @"自建通讯录"; myGroupSetion.Id = 0; myGroupSetion.MiddleType = type; myGroupSetion.SourceType = 3; myGroupSetion.SourceId = 0; myGroupSetion.SourceName = @"自建通讯录"; vc.departSourceDataArray = @[defaltGroupSetion,myGroupSetion].mutableCopy; vc.isDefalutPage = 1; vc.titleStr = @"选人"; [self.navigationController pushViewController:vc animated:YES]; } - (void)recviveChaoSongRen:(NSNotification *)notification{ if (self.isShoujianren) { NSMutableArray * array = notification.userInfo[@"selectPeople"]; if (array.count > 0) { NSLog(@"shouJianArray结果数据组%@",array); NSString *jsonString = [NSString stringWithFormat:@"getApproverCheckUsersList('%@')",[self arrayToJSONModel:array]]; [self.webView evaluateJavaScript:jsonString completionHandler:^(id _Nullable data, NSError * _Nullable error) { NSLog(@"data:%@",data); NSLog(@"error:%@",error); }]; } } if (self.isChaosongren) { NSMutableArray * array = notification.userInfo[@"selectPeople"]; if (array.count > 0) { NSLog(@"chaoShongArray结果数据组%@",array); NSString *jsonString = [NSString stringWithFormat:@"getCarbonCopyUsersList('%@')",[self arrayToJSONModel:array]]; [self.webView evaluateJavaScript:jsonString completionHandler:^(id _Nullable data, NSError * _Nullable error) { NSLog(@"data:%@",data); NSLog(@"error:%@",error); }]; } } } #pragma mark - 选择图片 - (void)chatBarDidPhotoAction { WS(weakSelf); [self.view endEditing:YES]; TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:nil]; [imagePickerVc setNavLeftBarButtonSettingBlock:^(UIButton *leftButton){ leftButton.hidden = YES; }]; imagePickerVc.showSelectBtn = NO; imagePickerVc.allowCrop = YES; imagePickerVc.cropRect = CGRectMake(0, (SCREEN_HEIGHT - SCREEN_WIDTH) * 0.5, SCREEN_WIDTH, SCREEN_WIDTH); imagePickerVc.allowTakePicture = NO; imagePickerVc.allowTakeVideo = NO; imagePickerVc.allowPickingOriginalPhoto = NO; imagePickerVc.allowPickingGif = NO; [imagePickerVc setIsStatusBarDefault:YES]; [imagePickerVc setNaviTitleColor:[UIColor blackColor]]; [imagePickerVc setBarItemTextColor:[UIColor blackColor]]; [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray *photos, NSArray *assets, BOOL isSelectOriginalPhoto) { PHAsset *asset = assets.firstObject; switch (asset.mediaType) { case PHAssetMediaTypeVideo: { } break; case PHAssetMediaTypeImage: { [weakSelf didSelectImage:photos]; } break; case PHAssetMediaTypeAudio: break; case PHAssetMediaTypeUnknown: break; default: break; } }]; [self presentViewController:imagePickerVc animated:YES completion:nil]; } - (void)didSelectImage:(NSArray *)images { NSMutableArray * array = [NSMutableArray array]; for (UIImage * image in images) { NSData *data = UIImageJPEGRepresentation(image, 1); [array addObject:data]; } WS(weakSelf); NSString *urlString = [[NSString alloc] initWithFormat:@"%@%@",BaseUrl,Modify_UserImages_Post]; [[HttpManager sharedHttpManager] HeaderUploadUrl:urlString parameters:@{} pictureArray:array pictureKey:@"file" success:^(id _Nonnull responseObject) { NSLog(@"%@",responseObject); for (NSDictionary * dict in responseObject) { NSString *jsonString = [NSString stringWithFormat:@"getAndroidImg('%@','%@','%ld')",dict[@"AbsolutePath"],dict[@"FileName"],(long)CollectDataType_IMG]; [weakSelf upDateAction:jsonString]; } } failure:^(NSError * _Nonnull error) { }]; } #pragma mark - 选择笔记 - (void)disSelectNoteBook:(NSMutableArray*_Nonnull )noteArr{ for (MyNoteBookSubModel *dataModel in noteArr ) { if (dataModel.AttributeValue == 1) { NSString *jsonString = [NSString stringWithFormat:@"getAndroidNoteCollection('%ld','%@','%ld','%@')",(long)CollectDataType_Note,dataModel.Title,(long)dataModel.MiddleId,dataModel.Name]; [self upDateAction:jsonString]; }else{ NSString *jsonString = [NSString stringWithFormat:@"getAndroidNoteCollection('%ld','%@','%ld','%@')",(long)CollectDataType_NoteFile,dataModel.FolderName,(long)dataModel.Id,[AppUserModel sharedAppUserModel].Name]; [self upDateAction:jsonString]; } } } #pragma mark - 选择收藏 - (void)disSelectCollect:(NSMutableArray * _Nonnull) collectArr{ for (MyFavoriteSubModel *dataModel in collectArr ) { if(dataModel.AttributeValue == 1) { NSString *jsonString = [NSString stringWithFormat:@"getAndroidNoteCollection('%ld','%@','%ld','%@')",(long)[ZYCTool returnDataType:dataModel.CollectionType],dataModel.Title,(long)dataModel.CollectionDataId,dataModel.Data.Author]; [self upDateAction:jsonString]; }else{ NSString *jsonString = [NSString stringWithFormat:@"getAndroidNoteCollection('%ld','%@','%ld','%@')",(long)CollectDataType_CollectFile,dataModel.FolderName,(long)dataModel.Id,[AppUserModel sharedAppUserModel].Name]; [self upDateAction:jsonString]; } } } #pragma mark - WKScriptMessageHandler -(NSString *)convertToJson:(NSDictionary *)dict { NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString; if (!jsonData) { NSLog(@"%@",error); }else{ jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; } NSMutableString *mutStr = [NSMutableString stringWithString:jsonString]; NSRange range = {0,jsonString.length}; //去掉字符串中的空格 [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range]; NSRange range2 = {0,mutStr.length}; //去掉字符串中的换行符 [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2]; return mutStr; } #pragma mark - WKUIDelegete - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(nonnull NSString *)message initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(void))completionHandler { NSLog(@"%@",message); completionHandler(); } - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(nonnull NSString *)message initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(BOOL))completionHandler { NSLog(@"223123"); completionHandler(YES); } - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(nonnull NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(NSString * _Nullable))completionHandler { NSLog(@"323123"); completionHandler(@"111"); } #pragma mark - 提交富文本 - (void)submit { NSString *jsonString = [NSString stringWithFormat:@"getEditorText()"]; [self.webView evaluateJavaScript:jsonString completionHandler:^(id _Nullable data, NSError * _Nullable error) { NSLog(@"submit:%@",data); NSDictionary * dict = (NSDictionary *)data; switch (self.type) { case CreateNoticeType: { [self submitNotice:dict]; } break; case CreateTopicType: { [self submitTopic:dict]; } break; default: break; } }]; } #pragma mark - 提交通知 - (void)submitNotice:(NSDictionary *)dict { NSString * html = dict[@"html"]; NSArray * jsonArray = dict[@"json"]; NSMutableDictionary * paraDict = [NSMutableDictionary dictionary]; [paraDict setObject:dict[@"Title"] forKey:@"Title"]; [paraDict setObject:@([AppUserModel sharedAppUserModel].Id) forKey:@"UserId"]; [paraDict setValue:self.isDraft ? @(2) : @(1) forKey:@"NoticeType"]; if (self.isFolder) { [paraDict setValue:@(self.FolderId) forKey:@"FolderId"]; } [paraDict setObject:html forKey:@"HtmlContent"]; [paraDict setObject:dict[@"AddresseeUserMiddles"] forKey:@"AddresseeUserMiddles"]; [paraDict setObject:dict[@"CcUserMiddles"] forKey:@"CcUserMiddles"]; [paraDict setObject:[self arrayToJSONString:jsonArray] forKey:@"Content"]; if (self.isEdit) { [paraDict setObject:@(self.Id) forKey:@"id"]; [self sentChangeNotice:paraDict withNoticeType:self.isDraft ? 2 : 1]; }else{ [self sentNoticeRequeast:paraDict withNoticeType:self.isDraft ? 2 : 1]; } } - (void)sentChangeNotice:(NSMutableDictionary *)dic withNoticeType:(NSInteger)NoticeType{ WS(weakSelf); [[HttpManager sharedHttpManager] POSTUrl:Host(API_NOTICE_EDIT) parameters:dic responseStyle:DATA success:^(id _Nonnull responseObject) { REMOVESHOW if(NoticeType == 1){ SHOWSUCCESS(@"通知已经发送"); }else{ SHOWSUCCESS(@"通知已经存放草稿箱"); } [weakSelf.navigationController popViewControllerAnimated:YES]; } failure:^(NSError * _Nonnull error) { SHOWERROR([ZYCTool handerResultData:error]); }]; } - (void)sentNoticeRequeast:(NSMutableDictionary *)dic withNoticeType:(NSInteger)NoticeType{ WS(weakSelf); [[HttpManager sharedHttpManager] PUTUrl:Host(API_NOTICE_ADD) parameters:dic success:^(id _Nonnull responseObject) { REMOVESHOW if(NoticeType == 1){ SHOWSUCCESS(@"通知已经发送"); }else{ SHOWSUCCESS(@"通知已经存放草稿箱"); } [weakSelf.navigationController popViewControllerAnimated:YES]; } failure:^(NSError * _Nonnull error) { SHOWERROR([ZYCTool handerResultData:error]); }]; } #pragma mark - 提交话题 - (void)submitTopic:(NSDictionary *)dict { NSString * html = dict[@"html"]; NSArray * jsonArray = dict[@"json"]; NSMutableDictionary * paraDict = [NSMutableDictionary dictionary]; [paraDict setObject:dict[@"Title"] forKey:@"Title"]; [paraDict setObject:@([AppUserModel sharedAppUserModel].Id) forKey:@"UserId"]; [paraDict setObject:@(0) forKey:@"FolderId"]; [paraDict setObject:@[] forKey:@"TopicAddresseeUserIds"]; [paraDict setObject:html forKey:@"HtmlContent"]; [paraDict setObject:[self arrayToJSONString:jsonArray] forKey:@"Content"]; SHOWLOADING [[HttpManager sharedHttpManager] POSTUrl:Host(APP_Topic_Add) parameters:paraDict responseStyle:DATA success:^(id _Nonnull responseObject) { NSLog(@"%@",responseObject); REMOVESHOW SHOWSUCCESS(@"创建成功"); } failure:^(NSError * _Nonnull error) { REMOVESHOW SHOWERROR([ZYCTool handerResultData:error]) }]; } - (NSString *)arrayToJSONModel:(NSArray *)array { NSMutableArray * mArray = [NSMutableArray array]; for (SelectModel * model in array) { NSDictionary * dict = [model modelToJSONObject]; [mArray addObject:@{@"SourceType":dict[@"SourceType"],@"SourceId":dict[@"SourceId"],@"SourceName":dict[@"SourceName"],@"MiddleType":@(self.type)}]; } return [self arrayToJSONString:mArray]; } - (NSString *)arrayToJSONString:(NSArray *)array { NSError *error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSMutableString *mutStr = [NSMutableString stringWithString:jsonString]; NSRange range = {0,jsonString.length}; //去掉字符串中的空格 [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range]; NSRange range2 = {0,mutStr.length}; //去掉字符串中的换行符 [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2]; return mutStr; } - (void)dealloc { WKUserContentController *userCC = self.webView.configuration.userContentController; [userCC removeScriptMessageHandlerForName:@"chosePic"]; [userCC removeScriptMessageHandlerForName:@"toPZ"]; [userCC removeScriptMessageHandlerForName:@"toBJ"]; [userCC removeScriptMessageHandlerForName:@"toSC"]; [userCC removeScriptMessageHandlerForName:@"toWJ"]; [userCC removeScriptMessageHandlerForName:@"keyBoard"]; [userCC removeScriptMessageHandlerForName:@"getType"]; [userCC removeScriptMessageHandlerForName:@"approverCheckUsers"]; [userCC removeScriptMessageHandlerForName:@"carbonCopyUsers"]; [[NSNotificationCenter defaultCenter] removeObserver:self]; [self.webView stopLoading]; self.webView.UIDelegate = nil; self.webView.navigationDelegate = nil; self.webView.scrollView.delegate = nil; [self.webView removeFromSuperview]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore]; [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] completionHandler:^(NSArray * __nonnull records) { for (WKWebsiteDataRecord *record in records) { [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes forDataRecords:@[record] completionHandler:^{ NSLog(@"Cookies for %@ deleted successfully",record.displayName); }]; } }]; } @end