//
//  StoreManagermentViewController.m
//  ALand
//
//  Created by Z on 16/4/1.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "StoreManagermentViewController.h"
#import "StoreQRCodeViewController.h"
#import "SelectPhotoView.h"
#import "CoverShadowView.h"
#import "StoreNameViewController.h"
#import "introductionViewController.h"
#import "CommodityManagementViewController.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"

@interface StoreManagermentViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UMSocialUIDelegate>
@property (nonatomic, strong) SelectPhotoView *photoView;
@property (nonatomic, strong) CoverShadowView *shadowView;
@property (nonatomic, strong) JavenShopModel *shopModel;
@property (weak, nonatomic) IBOutlet UIButton *buttonBac;
@property (weak, nonatomic) IBOutlet UILabel *labelName;
@property (weak, nonatomic) IBOutlet UILabel *labelDescription;
@property (weak, nonatomic) IBOutlet UIImageView *imgViewIcon;
@property (nonatomic, copy) NSString *urlStr;



@end

@implementation StoreManagermentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.buttonBac.imageView.contentMode = UIViewContentModeScaleAspectFit;
    UserInfo *userInfo = [UserInfo shareInstance];
    self.urlStr = [NSString stringWithFormat:@"%@Wap/index_shop/shop_id/%@.html", userInfo.webShopBaseUrl, userInfo.shop.uuid];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self setUpdata];
}


- (void)setUpdata {
    
    WS(weakSelf)
    [[HTTPCilent shareCilent] GET:[NSString stringWithFormat:@"shop/get/%@", [UserInfo shareInstance].shop.uuid] parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (weakSelf.shopModel) {
            [weakSelf.shopModel updateWithDictionary:responseObject[@"shop"]];
        }else{
            weakSelf.shopModel = [JavenShopModel modelObjectWithDictionary:responseObject[@"shop"]];
        }
        CLog(@"%p",weakSelf.shopModel);
        
        [weakSelf setUpViewWithModel:weakSelf.shopModel];
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


- (void)setUpViewWithModel:(JavenShopModel *)model {
    self.labelName.text = self.shopModel.name;
    self.labelDescription.text = self.shopModel.internalBaseClassDescription;
    [self.imgViewIcon sd_setImageWithURL:[NSURL URLWithString:self.shopModel.pictures] placeholderImage:[UIImage imageNamed:@"default_commodity_placeholder"]];
    
}


- (SelectPhotoView *)photoView {
    if (!_photoView) {
        _photoView = [SelectPhotoView viewWithNibName:@"SelectPhotoView"];
        _photoView.frame = CGRectMake(0, kHeight, kWidth, 100);
        _shadowView = [[CoverShadowView alloc] initOnTopWithHeight:kHeight];
        [self.view.window addSubview:_shadowView];
        [_shadowView addSubview:_photoView];
        
        WS(weakSelf)
        //拍照
        _photoView.takePhotoBlock = ^{
            [weakSelf takePhotoAction];
            
        };
        
        //相册
        _photoView.galleryBlock = ^{
            [weakSelf gallery];
        };
        
        //阴影点击事件
        _shadowView.tapAction = ^{
            [weakSelf hide];
        };
        
    }
    
    return _photoView;
}

- (void)takePhotoAction {
    [self hide];
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"找不到相机" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    } else {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//        picker.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        picker.videoQuality = UIImagePickerControllerQualityTypeLow;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)gallery {
    [self hide];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;//是否可以编辑
        //打开相册选择照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 模态进入相册
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
 
    //得到图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    
    MBProgressHUD *hud = [MBProgressHUD Javen_showMessage:@"修改中" onView:self.view];
    
    //上传七牛
    [[JavenQNManager shareInstance] upLoadImage:image isMD5Name:YES name:nil commpelete:^(NSString *key) {
        
        NSDictionary *params = [self getParamsWithImageUrl:key];
        
        //上传成功之后把URL传给aland服务器
        WS(weakSelf)
        [[HTTPCilent shareCilent] POST:@"shop/save" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
            if ([responseObject[@"code"] isEqualToNumber:@0]) {
                
                [hud hide:YES];
                [MBProgressHUD Javen_showSuccess:@"修改成功！" onView:weakSelf.view  delay:0.7 complete:^{
                    [weakSelf setUpdata];
                }];
            }
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        
    }];
   
    
    // 模态返回
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//生成上传图片URL的参数
- (NSDictionary *)getParamsWithImageUrl:(NSString *)imageUrl {
    
    self.shopModel.pictures = [NSString stringWithFormat:@"http://7xtefo.com2.z0.glb.qiniucdn.com/%@", imageUrl];
    UserInfo *user = [UserInfo shareInstance];
    NSDictionary *dicShop = [self.shopModel dictionaryRepresentation];
    NSDictionary *params = @{@"operCtx" : @{@"time" : [[NSDate date] timeStampNumber],
                                            @"domain" : user.domain,
                                            @"operator" : @{@"id" : user.uuid,
                                                            @"fullName" : user.name}},
                             @"shop" : dicShop};
    return params;
}





/**
 *  显示阴影和底部的弹框
 */
- (void)show {
    [self.photoView showView];
    [self.shadowView show];
}

- (void)hide {
    [self.photoView hideView];
    [self.shadowView hide];
}

#pragma mark =========== actions ===========
- (IBAction)actionCommodityManagement:(id)sender {
    CommodityManagementViewController *commodityVC = [[CommodityManagementViewController alloc] init];
    commodityVC.isShowNavigationBar = YES;
    [self.navigationController pushViewController:commodityVC animated:YES];
}

- (IBAction)actionShare:(id)sender {
    
    [[ShareInstance shareInstace] showWithTitle:@"Aland" content:@"快来看看我的小店吧！ " url:self.urlStr image:[UIImage imageNamed:@"btn_share_shop"]];
    
}

//二维码界面
- (IBAction)QRCodeAction:(id)sender {
    StoreQRCodeViewController *QRCodeVC = [[StoreQRCodeViewController alloc] initWithNibName:@"StoreQRCodeViewController" bundle:nil];
    QRCodeVC.urlStr = self.urlStr;
    [self.navigationController pushViewController:QRCodeVC animated:YES];
    
}
- (IBAction)actionBack:(id)sender {
    [self PopViewControllerAnimated:YES];
}

- (IBAction)headSculpture:(id)sender {
    CLog(@"头像");
    [self show];
}

- (IBAction)shopName:(id)sender {
    StoreNameViewController *nameVC = [[StoreNameViewController alloc] initWithNibName:@"StoreNameViewController" bundle:nil];
    nameVC.isShowNavigationBar = YES;
    nameVC.shopModel = self.shopModel;
    [self.navigationController pushViewController:nameVC animated:YES];
}
- (IBAction)shopIntroduction:(id)sender {
    introductionViewController *introVC = [[introductionViewController alloc] initWithNibName:@"introductionViewController" bundle:nil];
    introVC.isShowNavigationBar = YES;
    introVC.shopModel = self.shopModel;
    [self.navigationController pushViewController:introVC animated:YES];
}
- (IBAction)shopLV:(id)sender {
    
}

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