//
//  RCTItemOrderViewManager.m
//  RNAliTop
//
//  Created by 王发果 on 2018/7/18.
//  Copyright © 2018年 王发果. All rights reserved.
//

#import "RCTItemOrderViewManager.h"
#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import <AlibabaAuthSDK/ALBBSDK.h>

@implementation RCTItemOrderViewManager
@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(RCTItemOrderView)

RCT_EXPORT_VIEW_PROPERTY(itemId, NSString*)

RCT_EXPORT_VIEW_PROPERTY(onChange, RCTBubblingEventBlock)

- (UIView *)view {
    RCTItemOrderView* orderView = [[RCTItemOrderView alloc] init];
    orderView.delegate = self;
    if([[ALBBSession sharedInstance] isLogin]){
        id rootcontroller = [[UIApplication sharedApplication] delegate].window.rootViewController;
        id<AlibcTradeService> tradeService = [[AlibcTradeSDK sharedInstance] tradeService];
        id<AlibcTradePage> myOrdersPage = [AlibcTradePageFactory myOrdersPage:0 isAllOrder:NO];
        AlibcTradeShowParams* showParam = [[AlibcTradeShowParams alloc] init];
        showParam.openType = AlibcOpenTypeH5;
        showParam.backUrl = @"tbopen23140447";
        showParam.isNeedPush = YES;
        [tradeService show:rootcontroller webView:orderView page:myOrdersPage showParams:showParam taoKeParams:nil trackParam:nil tradeProcessSuccessCallback:^(AlibcTradeResult * _Nullable result) {
            
        } tradeProcessFailedCallback:^(NSError * _Nullable error) {
            
        }];
    }
    return orderView;
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
    
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
//    NSLog(@"webViewDidFinishLoad");
    
    NSString *jsToGetHTMLSource = @"document.getElementsByTagName('body')[0].innerHTML";
    NSString *HTMLSource = [webView stringByEvaluatingJavaScriptFromString:jsToGetHTMLSource];
    
//    NSLog(@"HTMLSource = %@",HTMLSource);
    if(![[ALBBSession sharedInstance] isLogin]){
        NSDictionary* event = @{
                                @"type": @"onChangHtml",
                                @"params": @{@"html":@"",@"openId":@""}
                                };
        [self sendEvent:(RCTItemOrderView *)webView params:event];
        return;
    }
    NSString *openId = [[[ALBBSession sharedInstance] getUser] openId] ? : @"";
    NSDictionary* event = @{
                            @"type": @"onChangHtml",
                            @"params": @{@"html":HTMLSource,@"openId":openId}
                            };
    [self sendEvent:(RCTItemOrderView *)webView params:event];

}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return  YES;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
}

-(void)sendEvent:(RCTItemOrderView *) orderView params:(NSDictionary *) params {
    if (!orderView.onChange) {
        return;
    }
     NSLog(@"orderView.onChange");
    orderView.onChange(params);
}

@end
