//
//  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];
    [MobClick beginLogPageView:@"storeSetting"];//("PageOne"为页面名称，可自定义)

    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self setUpdata];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"storeSetting"];
}
- (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 = model.name;
    self.labelDescription.text = model.internalBaseClassDescription;
    [self.imgViewIcon sd_setImageWithURL:[NSURL URLWithString:model.pictures] placeholderImage:[UIImage imageNamed:@"default_commodity_placeholder"]];
    int grade = (int)model.grade;
    
    
    for (int i = 0; i < 5; i++) {
        UIImageView *imgView = (UIImageView *)[self.view viewWithTag:1000 + i];
        imgView.hidden = YES;
    }
    
    for (int i = 0; i < grade; i++) {
        UIImageView *imgView = (UIImageView *)[self.view viewWithTag:1000 + i];
        imgView.hidden = NO;
    }
}


- (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.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://o93sl2fym.bkt.clouddn.com/%@", imageUrl];
    UserInfo *user = [UserInfo shareInstance];
    NSDictionary *dicShop = [self.shopModel dictionaryRepresentation];
    NSDictionary *params = @{@"operCtx" : @{@"time" : [[NSDate date] timeStampNumber],
                                            @"domain" : kDomain,
                                            @"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:self.labelName.text content:self.labelDescription.text url:self.urlStr image:self.imgViewIcon.image];
    
    [[ShareInstance shareInstace] shareShopWithTitle:self.labelName.text shopDescription:self.labelDescription.text url:self.urlStr image:self.imgViewIcon.image imageUrl:self.shopModel.pictures];
    
}

//二维码界面
- (IBAction)QRCodeAction:(id)sender {
    StoreQRCodeViewController *QRCodeVC = [[StoreQRCodeViewController alloc] initWithNibName:@"StoreQRCodeViewController" bundle:nil];
    QRCodeVC.urlStr = self.urlStr;
    QRCodeVC.shopName = self.labelName.text;
    QRCodeVC.shopDescription = self.labelDescription.text;
    QRCodeVC.shopImage = self.imgViewIcon.image;
    QRCodeVC.shopImageUrl = self.shopModel.pictures;
    
    [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.title = @"店铺简介";
    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
