//
//  XEWebViewController.m
//  Open
//
//  Created by qinxuyang on 2021/12/22.
//  Copyright © 2021 QXY. All rights reserved.
//

#import "XEWebViewController.h"
#import "XEHNGradientProgressView.h"
@interface XEWebViewController ()<XEWebViewDelegate, XEWebViewNoticeDelegate>
// 网页
@property (nonatomic, strong) XEWebView *webView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *reloadBtn;
@property (nonatomic, strong) UIButton *shareBtn;
// 返回按钮
//@property (nonatomic, strong) UIBarButtonItem *backItem;
//// 关闭按钮
//@property (nonatomic, strong) UIBarButtonItem *closeItem;
// 刷新按钮
//@property (nonatomic, strong) UIBarButtonItem *reloadItem;
//// 分享按钮
//@property (nonatomic, strong) UIBarButtonItem *shareItem;

@property (nonatomic, strong) XEHNGradientProgressView *progressView;

@end

@implementation XEWebViewController

- (void)dealloc
{
    _webView.delegate = nil;
    _webView.noticeDelegate = nil;
    _webView = nil;
    // SDK 退出登录 清除 Cookie 等信息
    [XESDK.shared logout];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self navConfig];
    [self.view addSubview:self.webView];

//    // 初始化 navigationItem
//    self.navigationItem.leftBarButtonItem = self.backItem;
//    self.navigationItem.rightBarButtonItems = @[self.shareItem, self.reloadItem];
//    self.navigationItem.rightBarButtonItem.enabled = NO;//默认分享按钮不可用
    
    // 加载网页请求
    [self loadAndLoadUrl:self.loadUrlString];
    
}
- (void)navConfig
{
    UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = K_MainColor;
    [self.view addSubview:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(onClickBack) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(cl_kNavBarHeight);
    }];
    
    UILabel*titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"店铺主页";
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    self.titleLabel = titleLabel;
    [nav addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(120);
        make.height.offset(cl_kNavBarHeight);
    }];
    
    UIButton*shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn setTitle:@"刷新" forState:UIControlStateNormal];
    [shareBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(onClickRefresh) forControlEvents:UIControlEventTouchUpInside];
    shareBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
//    shareBtn.enabled = NO;//默认分享按钮不可用
    self.shareBtn = shareBtn;
    [nav addSubview:shareBtn];
    
    [shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(60);
        make.height.offset(cl_kNavBarHeight);
    }];
//    UIButton*reloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [reloadBtn setTitle:@"刷新" forState:UIControlStateNormal];
//    [reloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [reloadBtn addTarget:self action:@selector(onClickRefresh) forControlEvents:UIControlEventTouchUpInside];
//    reloadBtn.titleLabel.textAlignment = NSTextAlignmentRight;
//    reloadBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
//    self.reloadBtn = reloadBtn;
//    [nav addSubview:reloadBtn];
//
//    [reloadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(shareBtn.mas_left);
//        make.top.offset(cl_kStatusBarHeight);
//        make.width.offset(60);
//        make.height.offset(cl_kNavBarHeight);
//    }];
}
- (XEWebView *)webView{
    if (_webView == nil) {
        _webView = [[XEWebView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight)];
        _webView.delegate = self;
        _webView.noticeDelegate = self;
    }
    return _webView;
}
#pragma mark - 网页请求  (SDK网页请求-必须接入)
/// 加载 URL
- (void)loadAndLoadUrl:(NSString *)urlString
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [self.webView loadRequest:request];
}
#pragma mark - XEWebViewNotice Delegate  (SDK代理回调-必须接入)

- (void)webView:(id<XEWebView>)webView didReceiveNotice:(XENotice *)notice
{
    switch (notice.type) {
        case XENoticeTypeReady:
        {
            // Web页面加载完成回调，APP端按需处理
            
            // 例如：此时可以分享，但注意此事件并不作为是否可分享的标志事件
//            self.shareBtn.enabled = YES;
        }
            break;
        case XENoticeTypeLogin:
        {
            // SDK需要登录态通知回调 （APP端需要接入小鹅登录态API流程）
            // 小鹅登录态接入流程文档 https://admin.xiaoe-tech.com/helpCenter/problem?first_id=241&second_id=242&document_id=doc_5dca0f61d8b1c_jYm6p
            [self loginXESDK];
        }
            break;
        case XENoticeTypeShare:
        {
            // 当前网页分享内容结果回调 （需先触发webview的share方法）
            NSDictionary *dict = (NSDictionary *)notice.response;
//            NSString *content = [[NSString alloc] initWithFormat:@"%@", dict];
//            [self showAlertTitle: @"分享信息" content: content];
            NSLog(@"Notice: XENoticeTypeShare = %@", dict);
            
            if ([notice.response isKindOfClass:[NSDictionary class]]) {
                
                NSString *str = dict[@"share_link"];
                NSLog(@"yes: %@", str);
            } else {
                NSLog(@"No");
            }
        }
            break;
        
        case XENoticeTypeTitleChange:
        {
            // 网页标题改变回调，APP端按需处理
            NSDictionary *param = notice.response;
            if ([param isKindOfClass:[NSDictionary class]]) {
                NSString *title = param[@"title"];
                if (title.length > 0) {
                    self.titleLabel.text = title;
                }else{
                    self.titleLabel.text = @"店铺主页";
                }
                
            }
        }
            break;
        case XENoticeTypeOutLinkUrl:
        {
            // 外部链接回调，APP端按需处理，规则为带参数 needoutlink=1 的链接,例：https://xiaoe-tech.com/?needoutlink=1
            NSDictionary *param = notice.response;
            NSLog(@"自定义链接: %@", param);
//            [self showAlertTitle:param[@"out_link_url"] content: nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark - XEWebViewDelegate Delegate (SDK代理回调-可选接入)

- (BOOL)webView:(id<XEWebView>)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"shouldStartLoadWithRequest");
    return YES;
}

- (void)webViewDidStartLoad:(id<XEWebView>)webView
{
    [self.progressView startLoad];
}

- (void)webViewDidFinishLoad:(id<XEWebView>)webView
{
    [self.progressView finished];
}

- (void)webView:(id<XEWebView>)webView didFailLoadWithError:(NSError *)error
{
    [self.progressView finished];
}

- (void)webViewWebContentProcessDidTerminate:(id<XEWebView>)webView
{
    
}
#pragma mark - XEWebViewNotice Delegate  (SDK其它功能-可选接入)
/**
 点击刷新按钮
 */
- (void)onClickRefresh
{
    [self.webView reload];
}

/**
 点击分享按钮
 */
- (void)onClickShare
{
    [self.webView share];
}

/**
 点击返回按钮
 */
- (void)onClickBack
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
//        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    } else {
//        [self onClickClose];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 以下为APP端自身业务处理 ，按需处理

- (void)loginXESDK
{
    /**
    获取登录态 token（仅作测试使用）
    注意：该登录态获取接口仅作为小鹅内嵌课堂SDK的官方Demo测试使用，
       正式对接时，你应该请求贵方的APP服务端后台封装的正式登录态接口获取数据,
    
    @param openUID  APP登录用户唯一码
    @param completionBlock 回调
    */
//    NSString *url = [NSString stringWithFormat:@"%@xiaoe/login",@"http://172.16.10.18:8017/"];
    NSString *url = [NSString stringWithFormat:@"%@xiaoe/login",[NetworkConfig ipYinShuConfig]];
    NSDictionary *params = @{
        @"uid":@([getPeopleID PeopleID]),
    };
    [KKLoadingAnimationView show];
    WeakSelf
    [NetworkRequest PostNomal:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                    [XESDK.shared synchronizeCookieKey: objc[@"result"][@"token_key"]
                                             cookieValue:objc[@"result"][@"token_value"]];
                    [weakSelf onClickRefresh];
            }else{
                [XYProgressHUD showMessage:describe];
            }
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
        [KKLoadingAnimationView dismiss];
    }];
}
/// 分享弹窗
- (void)showAlertTitle:(NSString *)title content:(NSString *)content
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle: @"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

/// 登录弹窗
- (void)showLoginView
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"登录" message:@"" preferredStyle:UIAlertControllerStyleAlert];
//    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//        textField.placeholder = @"请输入账号";
//        textField.tag = 0;
//    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self loginXESDK];
    }];
    UIAlertAction *action_cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        [weakSelf.webView cancelLogin];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    [alertController addAction:action];
    [alertController addAction:action_cancel];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (XEHNGradientProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[XEHNGradientProgressView alloc] initWithFrame:CGRectMake(0, NAV_BAR_HEIGHT, ScreenWidth, 3)];
        _progressView.bgProgressColor = [UIColor whiteColor];
        _progressView.colorArr = @[(id)[UIColor greenColor].CGColor, (id)[UIColor whiteColor].CGColor];
        _progressView.progress = 0.1;
        [self.view addSubview:_progressView];
    }
    return _progressView;
}
@end
