//
//  CommodityDetailViewController.m
//  ALand
//
//  Created by Z on 16/3/28.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "CommodityDetailViewController.h"
#import "CommodityDetailBottomView.h"
#import "CommodityDetailTopView.h"
#import "CommodityMutipleSelectBottomView.h"
#import <WebKit/WebKit.h>
#import "JavenCustomerService.h"
@interface CommodityDetailViewController ()<WKNavigationDelegate>
@property (nonatomic, weak) WKWebView * webView;
@property (nonatomic, strong) CommodityDetailBottomView *bottomView;
@property (nonatomic, strong) CommodityDetailTopView *topView;

@end

@implementation CommodityDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.view.backgroundColor = kBacroundColor;
    
    [self setUpWebView];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.bottomView];
    self.bottomView.userInteractionEnabled = NO;
    //添加点击事件
    kButtonAddAction(self.bottomView.buttonShop, addCommodity);
    kButtonAddAction(self.bottomView.buttonShare, shareAction);
    kButtonAddAction(self.topView.buttonBack, backAction);
    kButtonAddAction(self.topView.buttonHome, homeAction);
    kButtonAddAction(self.bottomView.buttonPhone, startCustomerServices);
    

    [self checkIsFavorite];
    // Do any additional setup after loading the view.
}



/** 检查是否收藏 */
- (void)checkIsFavorite {

    WS(weakSelf);
    [[UserInfo shareInstance] checkGoodIsAddedWithGoodUuid:self.model.uuid result:^(BOOL isAdded) {
        weakSelf.bottomView.buttonShop.selected = isAdded;
    }];
}

#pragma mark - action

- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)homeAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 添加商品发送请求
- (void)addCommodity
{
    
    NSString *postUrl;
    NSString *commpleteInfo;
    NSDictionary *params;
    if (self.bottomView.buttonShop.isSelected) {
        postUrl = @"shop/removeGoods";
        commpleteInfo = @"移除成功！";
        params = [self getRemoveGoodsParams];
    }else{
        postUrl = @"shop/addGoods";
        commpleteInfo = @"添加成功！";
        params = [self getGoodsParams];
    }
    
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:postUrl parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToNumber: @0]) {
            
            [MBProgressHUD Javen_showSuccess:commpleteInfo onView:weakSelf.view delay:0.7 complete:nil];
            [weakSelf checkIsFavorite];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];

    }];
    
}

- (NSDictionary *)getGoodsParams
{
    UserInfo *info = [UserInfo shareInstance];
    
    NSDictionary *param = @{
                            @"operCtx": @{
                                    @"time": [[NSDate date] timeStampNumber],
                                    @"domain": info.domain,
                                    @"operator": @{
                                            @"id": info.uuid,
                                            @"fullName": info.name
                                            }
                                    },
                            @"shopUuid": info.shop.uuid,
                            @"goodsUuid":self.model.uuid
                            };
    return param;
}

- (NSDictionary *)getRemoveGoodsParams
{
    UserInfo *info = [UserInfo shareInstance];
    
    NSDictionary *param = @{
                            @"operCtx": @{
                                    @"time": [[NSDate date] timeStampNumber],
                                    @"domain": info.domain,
                                    @"operator": @{
                                            @"id": info.uuid,
                                            @"fullName": info.name
                                            }
                                    },
                            @"shopUuid": info.shop.uuid,
                            @"listGoodsUuid": @[self.model.uuid]
                            };
    return param;
}

- (void)setUpWebView
{
    UserInfo *userInfo = [UserInfo shareInstance];
    NSString *urlStr = [NSString stringWithFormat:@"%@Wap/detail/shop_id/%@/id/%@/hastbar/1/.html", userInfo.webShopBaseUrl, userInfo.shop.uuid, self.model.uuid];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 67)];
    NSURL *url = [NSURL URLWithString:urlStr];
    self.webView = webView;
    [webView loadRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:10]];
    webView.navigationDelegate = self;
    [self.view addSubview:webView];
    webView.userInteractionEnabled = YES;
    
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    
    [MBProgressHUD showHUDAddedTo:webView animated:YES];
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    self.bottomView.userInteractionEnabled = YES;
    [MBProgressHUD hideHUDForView:webView];
}


- (void)shareAction
{
    
    UserInfo *userInfo = [UserInfo shareInstance];
    WS(weakSelf)
    [userInfo checkGoodIsAddedWithGoodUuid:self.model.uuid result:^(BOOL isAdded) {
        if (isAdded) {
            
            [[ShareInstance shareInstace] shareGoodsWithGoodsModel:self.model image:self.image];
            
        }else{
            [MBProgressHUD Javen_showError:@"请先添加到店铺！" onView:weakSelf.view delay:0.7 complete:nil];
        }
    }];
    
    
}

- (void)startCustomerServices {
    [JavenCustomerService startCustomerServices:self];
}


#pragma mark =========== lazy loading ===========
- (CommodityDetailBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [CommodityDetailBottomView viewWithNibName:@"CommodityDetailBottomView"];
        _bottomView.frame = CGRectMake(0, kHeight - 67, kWidth, 67);
  
    }
    return _bottomView;
}

- (CommodityDetailTopView *)topView {
    if (!_topView) {
        _topView = [CommodityDetailTopView viewWithNibName:@"CommodityDetailTopView"];
        _topView.frame = CGRectMake(0, 0, kWidth, 86);
    }
    return _topView;
}

- (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
