//
//  ExperienceCentreViewController.m
//  Lighting
//
//  Created by 曹云霄 on 16/6/1.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ExperienceCentreViewController.h"
#import "SceneViewController.h"
#import "sceneScreeningCollectionViewCell.h"
#import "ProductScreeningTableViewCell.h"
#import "GoodsImageView.h"
#import "ShareGoodsViewController.h"
#import "DeviceDirectionManager.h"
#import "HelpController.h"
#import "ShoppingBagViewController.h"


#define LEFTWIDTH 100
#define RIGHTWIDTH 200
#define TOPWIDTH 300

@interface ExperienceCentreViewController ()<AddImagesDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,SharePicturedelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>



@end

@implementation ExperienceCentreViewController



- (NSMutableArray *)sceneDatasArray
{
    if (!_sceneDatasArray) {
        
        _sceneDatasArray = [NSMutableArray array];
    }
    return _sceneDatasArray;
}


- (NSMutableArray *)productDatasArray
{
    if (!_productDatasArray) {
        
        _productDatasArray = [NSMutableArray array];
    }
    return _productDatasArray;
}


- (NSMutableArray *)shareGoodsArray
{
    if (!_shareGoodsArray) {
        
        _shareGoodsArray = [NSMutableArray array];
    }
    return _shareGoodsArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
}


#pragma mark -UI
- (void)uiConfigAction
{
    //场景
    self.sceneLayout.itemSize = CGSizeMake(133, 100);
    self.sceneLayout.minimumLineSpacing = 10;
    self.sceneLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    self.sceneScrollview.delegate = self;
    self.sceneScrollview.dataSource = self;
    //产品
    self.productScrollview.dataSource = self;
    self.productScrollview.delegate = self;
    if (self.boolValue) {
        SceneListModel *model = [self.sceneDatasArray firstObject];
        [self.sceneImageView sd_setImageWithURL:[NSURL URLWithString:model.pricure] placeholderImage:REPLACEIMAGE];
    }
}

#pragma mark -UICollectionViewDataSource场景
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.sceneDatasArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    sceneScreeningCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"sceneScreeningCollectionViewCell" forIndexPath:indexPath];
     SceneListModel *model = [self.sceneDatasArray objectAtIndex_opple:indexPath.item];
    [cell.selectedScrenImageView sd_setImageWithURL:[NSURL URLWithString:model.pricure] placeholderImage:REPLACEIMAGE];
    cell.selectedScrenImageView.layer.masksToBounds = YES;
    cell.selectedScrenImageView.layer.cornerRadius = kCornerRadius;
    if (model.isSelectedSate) {
        cell.selectedScrenImageView.layer.borderWidth = 2.0f;
        cell.selectedScrenImageView.layer.borderColor = kMainBlueColor.CGColor;
    }else
    {
        cell.selectedScrenImageView.layer.borderWidth = 0;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    for (SceneListModel *model in self.sceneDatasArray) {
        model.isSelectedSate = NO;
    }
   SceneListModel *model = [self.sceneDatasArray objectAtIndex_opple:indexPath.item];
    model.isSelectedSate = YES;
    [self.sceneImageView sd_setImageWithURL:[NSURL URLWithString:model.pricure] placeholderImage:REPLACEIMAGE];
    [self.sceneScrollview reloadData];
}



#pragma mark -UITableViewDataSource商品
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.productDatasArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductScreeningTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductScreeningTableViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    TOGoodsEntityModel *model = [self.productDatasArray objectAtIndex_opple:indexPath.row];
    if (model.isSelectedState) {
        cell.selectedGoodsImageView.layer.borderWidth = 2.0f;
        cell.selectedGoodsImageView.layer.borderColor = kMainBlueColor.CGColor;
    }else
    {
        cell.selectedGoodsImageView.layer.borderWidth = 0;
    }
    NSArray *imags = [model.pictures componentsSeparatedByString:@","];
    [cell.selectedGoodsImageView sd_setImageWithURL:[NSURL URLWithString:[imags firstObject]]];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ProductScreeningTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    TOGoodsEntityModel *model = [self.productDatasArray objectAtIndex_opple:indexPath.row];
    CGRect cellRect = [cell convertRect:cell.bounds toView:self.view];
    GoodsImageView *imageView = [[GoodsImageView alloc]initWithFrame:cellRect];
    imageView.model = model;
    [imageView setDelectedBlock:^(TOGoodsEntityModel *delectedModel) {
        //删除先判断数量
        for (TOGoodsEntityModel *newModel in self.shareGoodsArray) {
            if ([newModel.fid isEqualToString:delectedModel.fid]) {
                if (newModel.goodsNumber <= 1) {
                    [self.shareGoodsArray removeObject:delectedModel];
                }else
                {
                    newModel.goodsNumber --;
                }
                break;
            }
        }
    }];
    imageView.userInteractionEnabled = YES;
    [UIView animateWithDuration:0.5 animations:^{
        
        imageView.frame = CGRectMake((ScreenWidth-266)/2, (ScreenHeight-200)/2, 266, 200);
    }];
    for (TOGoodsEntityModel *model in self.productDatasArray) {
        model.isSelectedState = NO;
    }
    model.isSelectedState = YES;
    
    //判断选中的商品是否已经存在
    if ([self.shareGoodsArray containsObject:model]) {
        for (TOGoodsEntityModel *newModel in self.shareGoodsArray) {
            if ([newModel.fid isEqualToString:model.fid]) {
                newModel.goodsNumber ++;
                break;
            }
        }
    }else
    {
       [self.shareGoodsArray addObject:model];
    }
    NSArray *imags = [model.pictures componentsSeparatedByString:@","];
    [imageView sd_setImageWithURL:[NSURL URLWithString:[imags firstObject]] placeholderImage:REPLACEIMAGE];
    [self.sceneBackView addSubview:imageView];
    [self.productScrollview reloadData];
}


#pragma mark -返回
- (IBAction)ReturnButtonClickAction:(UIButton *)sender {
    
    SHARED_APPDELEGATE.sceneArray = nil;
    SHARED_APPDELEGATE.productArray = nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -购物袋
- (IBAction)ShoppingBagButtonClickAction:(UIButton *)sender {
    
    sender.selected = YES;
    ShoppingBagViewController *shoppingBag = [[self getStoryboardWithName] instantiateViewControllerWithIdentifier:@"shoppingbagController"];
    [shoppingBag setDismissBlock:^{
        sender.selected = NO;
    }];
    shoppingBag.modalPresentationStyle = UIModalPresentationOverFullScreen;
    UIPopoverPresentationController *pop = shoppingBag.popoverPresentationController;
    pop.sourceView = shoppingBag.view;
    shoppingBag.datasArray = self.shareGoodsArray;
    [self presentViewController:shoppingBag animated:YES completion:nil];
}

#pragma mark -分享
- (IBAction)ShareButtonClickAction:(UIButton *)sender {
    
    if (!self.shareGoodsArray.count) {
        [self ErrorMBProgressView:@"没有选择需要分享的商品"];
        return;
    }
    ShareGoodsViewController *shareController = [[ShareGoodsViewController alloc]init];
    //商品id拼接
    NSMutableString *goodsID = [[NSMutableString alloc]init];
    for (TOGoodsEntityModel *model in self.shareGoodsArray) {
        [goodsID appendFormat:@"%@,",model.fid];
    }
    shareController.goodsIds = goodsID;
    shareController.shareImage = [self capture];
    shareController.delegate = self;
    shareController.preferredContentSize = CGSizeMake(290, 120);
    shareController.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *popover = shareController.popoverPresentationController;
    popover.permittedArrowDirections = UIPopoverArrowDirectionLeft;
    popover.sourceView = shareController.view;
    popover.sourceRect =  CGRectMake(sender.mj_x, sender.mj_y-30, sender.mj_w, sender.mj_h);
    [self presentViewController:shareController animated:YES completion:nil];
}

#pragma mark -拍照
- (IBAction)TakingPhotoButtonClickAction:(UIButton *)sender {
    
    sender.selected = YES;
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIImagePickerController *PcCamera = [[UIImagePickerController alloc]init];
    PcCamera.delegate = self;
    [DeviceDirectionManager instance].isHorizontal=YES;
    [alertView addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypeCamera];
            PcCamera.allowsEditing = YES;
            [self presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [self ErrorMBProgressView:@"相机无法使用"];
            sender.selected = NO;
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册中选择
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            PcCamera.allowsEditing = YES;
            [self presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [self ErrorMBProgressView:@"相册无法打开"];
            sender.selected = NO;
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.takingPicturesButton.selected = NO;
        [alertView dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark -拍照、从相册选择
#pragma -mark -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *Headimage = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.sceneImageView.image = Headimage;
    self.takingPicturesButton.selected = NO;
}

#pragma mark -截屏
- (UIImage *)capture
{
    // 创建一个context
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
    //把当前的全部画面导入到栈顶context中并进行渲染
    [self.sceneBackView.layer renderInContext:UIGraphicsGetCurrentContext()];
    // 从当前context中创建一个新图片
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return img;
}


#pragma mark -全屏
- (IBAction)AmplificationButtonClickAction:(UIButton *)sender {
    
    if (!sender.selected) {
        
        [UIView animateWithDuration:0.75 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            
            self.returnButton.frame = CGRectMake(self.returnButton.mj_x-LEFTWIDTH, self.returnButton.mj_y, self.returnButton.mj_w, self.returnButton.mj_h);
            self.shoppingbagButton.frame = CGRectMake(self.shoppingbagButton.mj_x-LEFTWIDTH, self.shoppingbagButton.mj_y, self.shoppingbagButton.mj_w, self.shoppingbagButton.mj_h);
            self.shareButton.frame = CGRectMake(self.shareButton.mj_x-LEFTWIDTH, self.shareButton.mj_y, self.shareButton.mj_w, self.shareButton.mj_h);
            self.takingPicturesButton.frame = CGRectMake(self.takingPicturesButton.mj_x-LEFTWIDTH, self.takingPicturesButton.mj_y, self.takingPicturesButton.mj_w, self.takingPicturesButton.mj_h);
            self.helpButton.frame = CGRectMake(self.helpButton.mj_x-LEFTWIDTH, self.helpButton.mj_y, self.helpButton.mj_w, self.helpButton.mj_h);
            self.sceneSelectedButton.frame = CGRectMake(self.sceneSelectedButton.mj_x, self.sceneSelectedButton.mj_y+RIGHTWIDTH, self.sceneSelectedButton.mj_w, self.sceneSelectedButton.mj_h);
            self.sceneScrollview.frame = CGRectMake(self.sceneScrollview.mj_x, self.sceneScrollview.mj_y+RIGHTWIDTH, self.sceneScrollview.mj_w, self.sceneScrollview.mj_h);
            self.productSelectedButton.frame = CGRectMake(self.productSelectedButton.mj_x+RIGHTWIDTH, self.productSelectedButton.mj_y, self.productSelectedButton.mj_w, self.productSelectedButton.mj_h);
            self.productScrollview.frame = CGRectMake(self.productScrollview.mj_x+RIGHTWIDTH, self.productScrollview.mj_y, self.productScrollview.mj_w, self.productScrollview.mj_h);
             self.amplificationButton.frame = CGRectMake(self.amplificationButton.mj_x, self.amplificationButton.mj_y-(RIGHTWIDTH+LEFTWIDTH), self.amplificationButton.mj_w, self.amplificationButton.mj_h);
            
        } completion:nil];
    }else
    {
        [UIView animateWithDuration:0.75 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            
            self.returnButton.frame = CGRectMake(self.returnButton.mj_x+LEFTWIDTH, self.returnButton.mj_y, self.returnButton.mj_w, self.returnButton.mj_h);
            self.shoppingbagButton.frame = CGRectMake(self.shoppingbagButton.mj_x+LEFTWIDTH, self.shoppingbagButton.mj_y, self.shoppingbagButton.mj_w, self.shoppingbagButton.mj_h);
            self.shareButton.frame = CGRectMake(self.shareButton.mj_x+LEFTWIDTH, self.shareButton.mj_y, self.shareButton.mj_w, self.shareButton.mj_h);
            self.takingPicturesButton.frame = CGRectMake(self.takingPicturesButton.mj_x+LEFTWIDTH, self.takingPicturesButton.mj_y, self.takingPicturesButton.mj_w, self.takingPicturesButton.mj_h);
            self.helpButton.frame = CGRectMake(self.helpButton.mj_x+LEFTWIDTH, self.helpButton.mj_y, self.helpButton.mj_w, self.helpButton.mj_h);
            self.sceneSelectedButton.frame = CGRectMake(self.sceneSelectedButton.mj_x, self.sceneSelectedButton.mj_y-RIGHTWIDTH, self.sceneSelectedButton.mj_w, self.sceneSelectedButton.mj_h);
            self.sceneScrollview.frame = CGRectMake(self.sceneScrollview.mj_x, self.sceneScrollview.mj_y-RIGHTWIDTH, self.sceneScrollview.mj_w, self.sceneScrollview.mj_h);
            self.productSelectedButton.frame = CGRectMake(self.productSelectedButton.mj_x-RIGHTWIDTH, self.productSelectedButton.mj_y, self.productSelectedButton.mj_w, self.productSelectedButton.mj_h);
            self.productScrollview.frame = CGRectMake(self.productScrollview.mj_x-RIGHTWIDTH, self.productScrollview.mj_y, self.productScrollview.mj_w, self.productScrollview.mj_h);
            self.amplificationButton.frame = CGRectMake(self.amplificationButton.mj_x, self.amplificationButton.mj_y+(RIGHTWIDTH+LEFTWIDTH), self.amplificationButton.mj_w, self.amplificationButton.mj_h);
            
        } completion:nil];
    }
    sender.selected = !sender.selected;
}

#pragma mark -帮助
- (IBAction)HelpButtonClickAction:(UIButton *)sender {
    
    sender.selected = YES;
    HelpController *helpView = [[HelpController alloc]init];
    helpView.backButtonPoint = self.returnButton.mj_origin;
    helpView.shoppingbagPoint = self.shoppingbagButton.mj_origin;
    helpView.sharePoint = self.shareButton.mj_origin;
    helpView.photoPoint = self.takingPicturesButton.mj_origin;
    helpView.fullScreenPoint = self.amplificationButton.mj_origin;
    helpView.helpPoint = self.helpButton.mj_origin;
    helpView.scenePoint = self.sceneSelectedButton.center;
    helpView.productPoint = self.productSelectedButton.center;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissAction:)];
    [helpView.view addGestureRecognizer:tap];
    [self.view addSubview:helpView.view];
}

#pragma mark -销毁
- (void)dismissAction:(UITapGestureRecognizer *)tap
{
    self.helpButton.selected = NO;
    [tap.view removeFromSuperview];
}


/**************************功能区**************************/
#pragma mark -场景筛选
- (IBAction)SceneSelectedButtonClickAction:(UIButton *)sender {
    
    sender.selected = YES;
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"SCENE"];
    SceneViewController *sceneVC = [[self getStoryboardWithName] instantiateViewControllerWithIdentifier:@"SceneController"];
    [sceneVC setDismissBlock:^{
        sender.selected = NO;
    }];
    sceneVC.view.backgroundColor = [UIColor clearColor];
    sceneVC.titleLabe.text = @"选择场景";
    sceneVC.searchBackView.hidden = YES;
    sceneVC.materialButton.hidden = YES;
    sceneVC.priceButton.hidden = YES;
    sceneVC.typeButton.hidden = YES;
    sceneVC.delegate = self;
    sceneVC.endAnimationPoint = self.sceneSelectedButton.center;
    sceneVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    UIPopoverPresentationController *pop = sceneVC.popoverPresentationController;
    pop.sourceView = sceneVC.view;
    [self presentViewController:sceneVC animated:YES completion:nil];
}

#pragma mark -产品筛选
- (IBAction)ProductSelectedButtonClickAction:(UIButton *)sender {
    
    sender.selected = YES;
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"SCENE"];
    SceneViewController *sceneVC = [[self getStoryboardWithName] instantiateViewControllerWithIdentifier:@"SceneController"];
    [sceneVC setDismissBlock:^{
        sender.selected = NO;
    }];
    sceneVC.view.backgroundColor = [UIColor clearColor];
    sceneVC.titleLabe.text = @"选择商品";
    sceneVC.searchBackView.hidden = NO;
    sceneVC.materialButton.hidden = NO;
    sceneVC.priceButton.hidden = NO;
    sceneVC.typeButton.hidden = NO;
    sceneVC.delegate = self;
    sceneVC.endAnimationPoint = self.productSelectedButton.center;
    sceneVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    UIPopoverPresentationController *pop = sceneVC.popoverPresentationController;
    pop.sourceView = sceneVC.view;
    [self presentViewController:sceneVC animated:YES completion:nil];
}



#pragma mark -AddImagesDelegate选中图片
- (void)SelectedImageswithModel:(JSONModel *)model withisScene:(BOOL)isScene returnResponse:(void (^)(BOOL))isThere
{
    if (isScene) {
        //场景
        SceneListModel *sceneModel = [(SceneListModel *)model copy];
        for (SceneListModel *objc in self.sceneDatasArray) {
            if ([objc.fid isEqualToString:sceneModel.fid]) {
                isThere(YES);
                [self.sceneDatasArray removeObject:objc];
                [self.sceneScrollview reloadData];
                return;
            }
        }
        isThere(NO);
        sceneModel.isSelectedSate = NO;
        [self.sceneDatasArray addObject:sceneModel];
        SHARED_APPDELEGATE.sceneArray = self.sceneDatasArray;
        
    }else
    {
        //产品
        TOGoodsEntityModel *goodsModel = [(TOGoodsEntityModel *)model copy];
        for (TOGoodsEntityModel *objc in self.productDatasArray) {
            if ([objc.fid isEqualToString:goodsModel.fid]) {
                isThere(YES);
                [self.productDatasArray removeObject:objc];
                [self.productScrollview reloadData];
                return;
            }
        }
        isThere(NO);
        goodsModel.isSelectedState = NO;
        [self.productDatasArray addObject:goodsModel];
        SHARED_APPDELEGATE.productArray = self.productDatasArray;
    }
}

#pragma mark -刷新
- (void)RefreshSceneAndProduct:(BOOL)isScene
{
    if (isScene) {
        
        [self.sceneScrollview reloadData];
        [self.sceneScrollview selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.sceneDatasArray.count-1 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionRight];
        
    }else
    {
        [self.productScrollview reloadData];
        [self.productScrollview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.productDatasArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}



#pragma mark ---SharePicturedelegate
#pragma mark -上传图片进度
- (void)UploadImageProgress:(double)progress
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self ShowProgressView:progress];
    });
}

#pragma mark -上传图片完成
- (void)UploadImageSuccess
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.TCHud.labelText = @"上传完成";
        [self RemoveMBProgressHUDLoding];
    });
}

#pragma mark -上传图片失败
- (void)UploadImageFailue
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.TCHud.labelText = @"上传失败";
        [self RemoveMBProgressHUDLoding];
    });
}

#pragma mark -分享失败
- (void)CodeNotEqualZero:(NSString *)message
{
    [self ErrorMBProgressView:message];
}


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