//
//  H6ViewController.m
//  smartRhino
//
//  Created by niuzhen on 2020/2/21.
//  Copyright © 2020 tederen. All rights reserved.
//

#import "H6ViewController.h"
#import "LYLPhotoTailoringTool.h"
#import "FWZGetNoteBookTool.h"
#import "FWZFileGetTool.h"
#import "H5ViewController.h"
#import "NoticeUnreadVC.h"

@interface H6ViewController ()<WKUIDelegate,WKNavigationDelegate,UIScrollViewDelegate,WKScriptMessageHandler>
@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic,assign) CGFloat   keyBoardH;
@end

@implementation H6ViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsMake(64, 0, 0, 0));
    }];
//    NSURL *pathUrl = [NSURL URLWithString:@"http://192.168.0.118:8080/#/mobile/editor"];
    NSURL *pathUrl = [NSURL URLWithString:@"http://192.168.0.119:8080/#/mobile/noticeDetails"];
    NSURLRequest *request = [NSURLRequest requestWithURL:pathUrl];
//    [self getData];
    [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];

}
- (void)getData
{
    WS(weakSelf);
    [[HttpManager sharedHttpManager] POSTUrl:Host(APP_Topic_App_Detail) parameters:@{@"Id":@(712),@"UserId":@([AppUserModel sharedAppUserModel].Id)} responseStyle:JOSN success:^(id  _Nonnull responseObject) {
        NSLog(@"话题正文%@",responseObject);
//        NSMutableDictionary * mdict = [NSMutableDictionary  dictionaryWithDictionary:responseObject];
//        [mdict removeObjectForKey:@"HtmlContent"];
        NSString *jsonString = [NSString stringWithFormat:@"getData('%@')",USERDEFAULTSGET(@"LOGINTOKEN")];
        [weakSelf.webView evaluateJavaScript:jsonString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
            NSLog(@"data:%@",data);
            NSLog(@"error:%@",error);
        }];
    } failure:^(NSError * _Nonnull error) {
        SHOWERROR([ZYCTool handerResultData:error]);
    }];
}
- (void)upDateAction:(NSString *)action
{
    [self.webView evaluateJavaScript:action completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        NSLog(@"上传成功");
    }];
}

- (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:@"delelteAction"];
        [userContent addScriptMessageHandler:self name:@"editAction"];
        [userContent addScriptMessageHandler:self name:@"postTopicDetailsData"];
        [userContent addScriptMessageHandler:self name:@"alreadyRead"];

        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;
}
#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);
    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<MyNoteBookSubModel *> * _Nonnull noteArr) {
            NSLog(@"SmartBarNotes %@",noteArr);
            [weakSelf disSelectNoteBook:noteArr];
        }];
    }
    if ([message.name isEqualToString:@"toSC"]) {
        [[FWZGetNoteBookTool sharedTool] openCollectListChooseCollectBlock:^(NSMutableArray<MyFavoriteSubModel *> * _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:@"delelteAction"]) {
        [self deleteButtonHander:714];
    }
    if ([message.name isEqualToString:@"editAction"]) {
        [self editorButtonHander:714];
    }

    if ([message.name isEqualToString:@"postTopicDetailsData"]) {
        NSString *jsonString = [NSString stringWithFormat:@"getNoticeDetailsData('%ld','%@','%d')",(long)622,USERDEFAULTSGET(@"LOGINTOKEN"),1];
//        NSString *jsonString = [NSString stringWithFormat:@"getData('%ld','%@')",(long)714,USERDEFAULTSGET(@"LOGINTOKEN")];
        [self.webView evaluateJavaScript:jsonString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
            NSLog(@"data:%@",data);
            NSLog(@"error:%@",error);
        }];
    }
    if ([message.name isEqualToString:@"alreadyRead"]) {
        NSLog(@"msgBody:%@",message.body);
        NSDictionary * dict = (NSDictionary *)message.body;
        NoticeUnreadVC *vc = [NoticeUnreadVC initNoticeUnreadVC];
        vc.Id = 622;
        vc.type = ReadNoticeType;
        vc.readCount = [dict[@"ReadCount"] integerValue];
        vc.unReadCount = [dict[@"AllCount"] integerValue] - [dict[@"ReadCount"] integerValue];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#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<UIImage *> *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<MyNoteBookSubModel *>*_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<MyFavoriteSubModel *> * _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;
        NSString * html = dict[@"html"];
        NSArray * jsonArray = dict[@"json"];
        
        NSMutableDictionary * paraDict = [NSMutableDictionary dictionary];
        [paraDict setObject:@"话题" forKey:@"Title"];
        [paraDict setObject:@([AppUserModel sharedAppUserModel].Id) forKey:@"UserId"];
        [paraDict setObject:@(0) forKey:@"ReadCount"];//没有
        [paraDict setObject:@(0) forKey:@"SourceType"];//没有
        [paraDict setObject:@(0) forKey:@"SourceId"];//没有
        [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])
        }];
    }];
}

#pragma mark - 撤回
- (void)deleteButtonHander:(NSInteger)deleteId{
    WS(weakSelf);
    SHOWLOADING
    NSString * url = [NSString stringWithFormat:@"%@%ld",Host(API_NOTICE_RECALL),(long)deleteId];
    [[HttpManager sharedHttpManager] PUTUrl:url parameters:@{} responseStyle:DATA success:^(id  _Nonnull responseObject) {
        REMOVESHOW
        SHOWSUCCESS(@"撤回成功");
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError * _Nonnull error) {
        REMOVESHOW
    }];
}
#pragma mark - 编辑
- (void)editorButtonHander:(NSInteger)editId{
    H5ViewController * vc = [[H5ViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSString *)arrayToJSONString:(NSArray *)array
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}
- (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:@"delelteAction"];
    [userCC removeScriptMessageHandlerForName:@"delelteAction"];
    [userCC removeScriptMessageHandlerForName:@"postTopicDetailsData"];
    [[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