//
//  AttractionDetailController.m
//  ArcGis
//
//  Created by Mac Book DQ02 on 16/3/25.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "AttractionDetailController.h"
#import "UMSocialSinaHandler.h"
#import <UShareUI/UShareUI.h>

@interface AttractionDetailController ()

@end

@implementation AttractionDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor blackColor];
    
    self.navigationItem.title = self.titleString;
    
    //设置导航栏的返回按钮
 //
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(backBtnIsClicked:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //设置导航栏透明
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsCompact)];
    [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:0];
    //设置导航栏文字偏好属性
    [Manager setNaviAttributesWithBlo:^(NSDictionary *attributes) {
        self.navigationController.navigationBar.titleTextAttributes= attributes;
    }];
#pragma mark --如果是空字符串不会报错，但是如果是空类型，服务器那边会报错
    if (self.areaId == nil || [self.areaId isKindOfClass:[NSNull class]]) {
        self.areaId = @"";
    }
    if (self.code == nil || [self.code isKindOfClass:[NSNull class]]) {
        self.code = @"";
    }
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(freshWeb) name:@"freshSpotDetailWebview" object:nil];
    
    
    if (!_webView) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, self.view.frame.size.height+64)];
        _webView.backgroundColor = [UIColor whiteColor];
         [_webView setOpaque:NO];//opaque是不透明的意思
        _webView.delegate = self;
        [_webView setScalesPageToFit:YES];//自动缩放以适应屏幕
    }
    [self.view addSubview:_webView];
    //加载网页的方式1.有网，加载在线的，出错后，加载本地出错页面  2.没网：先加载离线的，没有离线的，加载本地出错页面
    MapInfo *info = [MapInfo shareMapInfo];
    if (info.internetStatus != AFNetworkReachabilityStatusNotReachable) {
        NSString *urlString = [NSString stringWithFormat:@"%@/terminal/scenic/area_info?code=%@&id=%@",localRequestUrl,self.code,self.areaId];
        NSURL *url = [NSURL URLWithString:urlString];
        [_webView loadRequest:[NSURLRequest requestWithURL:url]];
        return;
    }
    NSString * codestr = [NSString stringWithFormat:@"%@.html",self.code];
    NSString *cache = [FileDownloadTool getTheCachePath];
    cache = [cache stringByAppendingString:@"/create_scenic_area_info/view/"];
    cache = [cache stringByAppendingString:codestr];
    BOOL fileExist = [FileDownloadTool whetherFileExist:cache];
    if (fileExist) {
         NSURL *baseUrl = [NSURL URLWithString:cache];
        NSString *htmlstring=[[NSString alloc]initWithContentsOfFile:cache  encoding:NSUTF8StringEncoding error:nil];
        [_webView loadHTMLString:htmlstring baseURL:baseUrl];
        
    }
    
   
}


-(void)freshWeb
{
    Singleton *single = [Singleton defaultSingleton];
    NSString *urlString = [NSString stringWithFormat:@"%@/terminal/scenic/area_info?code=%@&id=%@&sesskey=%@",localRequestUrl,self.code,self.areaId,single.sesskey];
    NSURL *url = [NSURL URLWithString:urlString];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}


#pragma mark 返回按钮点击事件
-(void)backBtnIsClicked:(id)sender
{
    [self dismissViewControllerAnimated:NO completion:nil];
}


#pragma mark webview的加载事件
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    Singleton *singleton = [Singleton defaultSingleton];
     NSLog(@"首页:%@", request.URL.absoluteString);
    if ([request.URL.absoluteString containsString:@"scenic/area_info?code="] &&![request.URL.absoluteString containsString:@"sesskey="] &&
        [singleton.string isEqualToString:@"9002"]) {
    
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@&sesskey=%@",request.URL.absoluteString,singleton.sesskey]]]];
        [self.view addSubview:_webView];
    
        return YES;
    }
    
    if ([request.URL.absoluteString containsString:@"scenic/area_info?isLogin=false"]) {
        //未登录的时候点击评论，给粗提示，说没登录，请登录
       // [FileDownloadTool alert:@"您还未登录，请先登录" view:self.view];
        //未登录情况下，点击评论，跳转至登录界面
        LoginViewController *vc = [[LoginViewController alloc]init];
        vc.skipFrom = @"SpotDetaiComment";
        UINavigationController *na = [[UINavigationController alloc]initWithRootViewController:vc];
        [self presentViewController:na animated:NO completion:nil];
        return NO;
        
    }
    
    if ([request.URL.absoluteString containsString:@"terminal/scenic/area_info/call_phone?phone="])
    {
        //拨打电话，调用电话功能
        
        NSArray *ary = [request.URL.absoluteString componentsSeparatedByString:@"phone="];//电话号码截取出来
        NSString *phone = [ary objectAtIndex:1];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt:%@",phone]]];
        return NO;
    }
    if ([request.URL.absoluteString containsString:@"area_info?type=ditu&code="]){
        NSArray *componArr = [request.URL.absoluteString componentsSeparatedByString:@"&code="];
        NSString *code = [componArr objectAtIndex:1];
        self.code = code;
        //地图页面的景点详情页面，点击地图，直接将本页面pop掉，不再继续跳新页面
        if (self.isFromGuid) {
            [self dismissViewControllerAnimated:NO completion:nil];
        }else
        {
            NSString *name = self.titleString;
            if ([self.titleString containsString:@"("]) {
                NSArray *arr = [self.titleString componentsSeparatedByString:@"("];
                name = [arr objectAtIndex:0];
            }
            [Manager spotDetailMapClicked:self andName:name andCode:self.code];
        }
        
        return NO;
    }
    
    if ([request.URL.absoluteString containsString:@"area_info?type=share&id="]) {
        NSArray *arr = [request.URL.absoluteString componentsSeparatedByString:@"&imgUrl="];
#pragma 分享到微博
        [self getShareImage:[arr objectAtIndex:1]];
      //  [Manager shareToSinaEvent:self viewController:self andImgUrl:[arr objectAtIndex:1] andSpotname:self.titleString];
        return NO;
    }
    
    if ([request.URL.absoluteString containsString:@"scenic/area_info?type=favorite"]) {
        if ([singleton.string isEqualToString:@"9002"]) {
            //表示登录状态
            NSArray *arr = [request.URL.absoluteString componentsSeparatedByString:@"type=favorite&id="];
            NSArray *arr2 = [[arr objectAtIndex:1] componentsSeparatedByString:@"&imgUrl="];
            
            [Manager requestForCollection:self andAreaId:[arr2 objectAtIndex:0]];
        }else
        {
            [Manager collectionBtnClicked:self andAreaId:self.areaId];
        }
        
        return NO;
    }
    return YES;
    
}

#pragma 先获得新浪微博需要分享的图片
-(void)getShareImage:(NSString *)imgUrl{
    if (imgUrl == nil) {
        UIImage *image = [UIImage imageNamed:@"120X"];
       // [UITool shareClickOn:self :goodName :@"" :@"":image :self.lastUrl];
        return;
    }
    
    NSURLSessionDownloadTask *task = [[Manager initSessionManager] downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imgUrl]] progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //沙盒的Documents路径
        NSString *downLoadPath = [NSString stringWithFormat:@"%@/Documents/spot.jpg",NSHomeDirectory()];
        //先判断，内存里是否有这个图片，有就删除
        NSFileManager *manager = [NSFileManager defaultManager];
        if([manager fileExistsAtPath:downLoadPath])
        {
            [manager removeItemAtPath:downLoadPath error:nil];
        }
        
        
        /**        区分:fileURLWithPath:与urlWithString:        前者用于网络(AFNetWorking),后者用于(NSURLConnection等系统的数据请求类)        */
        
        //返回下载后保存文件的路径
        
        return [NSURL fileURLWithPath:downLoadPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"goodImagPath = %@",filePath);
        NSMutableString *abs = [NSMutableString stringWithString:filePath.absoluteString];
        NSRange ran = NSMakeRange(0,7);
        [abs deleteCharactersInRange:ran];
        UIImage *image = [UIImage imageWithContentsOfFile:abs];
       // [UITool shareClickOn:self :goodName :@"" :@"":image :self.lastUrl];
        [self shareToSina:image :@"" :@""];
    }];
    [task resume];
}

#pragma mark --根据获得的图片，再分享到微博
-(void)shareToSina:(id)image :(NSString *)spotUrl :(NSString *)spotName
{
    //分享
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_Sina)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        messageObject.text = self.navigationItem.title;
        UMShareImageObject *shareImg = [[UMShareImageObject alloc]init];
        [shareImg setShareImage:image];

        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareImg;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    UMSocialLogInfo(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
            
        }];
        
    }];

}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
     
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if (error) {
        
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"freshSpotDetailWebview" object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
