//
//  ZCMerchantViewController.m
//  UniversalApp
//
//  Created by 凯朱 on 2019/6/3.
//  Copyright © 2019 徐阳. All rights reserved.
//

#import "ZCMerchantViewController.h"
#import "ZCMerchantBaseCell.h"
#import "ZCMerchantModel.h"
#import "ZCMerchantDetailCell.h"
#import "ZCMerchantEditViewController.h"
#import "ZCHomeService.h"
#import "ZCShowPhotoView.h"

static  NSString *const kBaseCellId = @"ZCMerchantBaseCell";
static  NSString *const kDetailCellId = @"ZCMerchantDetailCell";

@interface ZCMerchantViewController ()<UITableViewDelegate,UITableViewDataSource,ZCMerchantDetailCellDelegate,ZCMerchantEditViewControllerDelegate>
{
    ZCMerchantModel *_model;
    UIButton *_editBtn;
    NSMutableDictionary *_imageHeightDict;
}
/**列表*/
@property (nonatomic, strong)UITableView *myTableView;
@end

@implementation ZCMerchantViewController

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

-(void)setUpUI{
    [self.view addSubview:self.myTableView];
    [self setTitle:@"商户管理" fontSize:20];
    _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _editBtn.frame = CGRectMake(0, KScreenHeight-45-SafeAreaTopHeight,kScreenWidth, 45);
    _editBtn.backgroundColor = KColor_O;
    [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    _editBtn.titleLabel.font = kFont(15);
    [_editBtn setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [_editBtn addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_editBtn];
    self.view.backgroundColor = KWhiteColor;
}

-(void)loadData{
    
    [ZCTool showHudOnView:self.view];
    [ZCHomeService postHomeMerchantDetailInfoWithParams:@{} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideHudOnView:self.view];
        if (isSuccessed == NO){
            kShowToast(message);
            return;
        }
        
        if (![result[@"data"] isKindOfClass:[NSDictionary class]]) return;
        
        _model = [ZCMerchantModel modelWithDictionary:result[@"data"]];
        [_myTableView reloadData];
        
        //异步计算商店环境图片cell高度
        if (_model.around_images.count > 0) {
            _imageHeightDict = [[NSMutableDictionary alloc] init];
            __block NSInteger count = _model.around_images.count;
            [_model.around_images enumerateObjectsUsingBlock:^(NSString *url, NSUInteger idx, BOOL * _Nonnull stop) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:kUrlImgae(url) options:SDWebImageDownloaderAllowInvalidSSLCertificates progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                        count --;
                        CGFloat height = (kScreenWidth-30)/image.size.width * image.size.height;
                        [_imageHeightDict setObject:@(height) forKey:url];
                        if (count == 0) {
                            dispatch_main_async_safe(^{
                                [_myTableView reloadData];
                            });
                        }
                    }];
                });
            }];
        }
    }];
}

/**
 编辑商店
 */
-(void)editAction{
    ZCMerchantEditViewController *editVC = [[ZCMerchantEditViewController alloc] init];
    editVC.model = _model;
    editVC.delegate = self;
    [self.navigationController pushViewController:editVC animated:YES];
}

/**
 编辑完成回调
 */
-(void)zcMerchantEditViewControllerEditFinished{
    [self loadData];
}

/**
 查看证书
 */
-(void)zcMerchantDetailCellCheckCertificateAction:(NSString *)cerUrl{
    if (cerUrl.length == 0) {
        [ZCTool showToastOnKeyWindowWith:@"您还未上传营业执照"];
        return;
    }
    ZCShowPhotoView *showPhotoView = [[ZCShowPhotoView alloc] initWithImageUrls:@[cerUrl] writable:@"0"];
    [self.navigationController pushViewController:showPhotoView animated:NO];
}

#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2+_model.around_images.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZCMerchantDetailCell *detailCell = [tableView dequeueReusableCellWithIdentifier:kDetailCellId];
    detailCell.delegate = self;
    ZCMerchantBaseCell *baseCell = [tableView dequeueReusableCellWithIdentifier:kBaseCellId];
    UITableViewCell *imageCell = [tableView dequeueReusableCellWithIdentifier:@"imageCellId"];
    baseCell.selectionStyle = UITableViewCellSelectionStyleNone;
    imageCell.selectionStyle = UITableViewCellSelectionStyleNone;
    detailCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.section == 0) {
        [baseCell paddingWithModel:_model];
        return baseCell;
    }
    else if (indexPath.section == 1){
        [detailCell paddingWithModel:_model];
        return detailCell;
    }
    else{
        
        UIImageView *imgView = [imageCell viewWithTag:100];
        NSString *imageUrl = _model.around_images[indexPath.section-2];
        if (imgView == nil) {
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, kScreenWidth-30, 150)];
            if (_imageHeightDict) {
                imgView.height = [_imageHeightDict[_model.around_images[indexPath.section-2]] floatValue];
            }
            imgView.layer.backgroundColor = [UIColor colorWithRed:216/255.0 green:216/255.0 blue:216/255.0 alpha:1.0].CGColor;
            imgView.layer.cornerRadius = 3;
            imgView.layer.masksToBounds = YES;
            [imageCell.contentView addSubview:imgView];
            imgView.tag = 100;
            [imgView zc_setImageWithUrlStr:imageUrl];
            
        }else{
            if (_imageHeightDict) {
                imgView.height = [_imageHeightDict[_model.around_images[indexPath.section-2]] floatValue];
            }
            [imgView zc_setImageWithUrlStr:imageUrl];
        }
        
        return imageCell;
    }
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return [ZCMerchantBaseCell cellHeightWithModel:_model];
    }
    else if (indexPath.section == 1){
        return [ZCMerchantDetailCell cellHeightWithModel:_model];
    }
    else{
        NSString *imageUrl = _model.around_images[indexPath.section-2];
        if (_imageHeightDict) {
            return [_imageHeightDict[imageUrl] floatValue];
        }
        return 150;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 0.1;
    }
    return 15;
}

/**
 header实现
 */
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, KScreenWidth, 0.1);
        headview.backgroundColor = KWhiteColor;
    }
    return headview;
}

/**
 footer实现
 */
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, KScreenWidth, 15);
        footerView.contentView.backgroundColor = KWhiteColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,KScreenWidth , KScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-45) style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _myTableView.showsVerticalScrollIndicator = NO;
        _myTableView.backgroundColor = KWhiteColor;
        [_myTableView registerNib:[UINib nibWithNibName:kBaseCellId bundle:nil] forCellReuseIdentifier:kBaseCellId];
        [_myTableView registerNib:[UINib nibWithNibName:kDetailCellId bundle:nil] forCellReuseIdentifier:kDetailCellId];
        [_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"imageCellId"];
        
    }
    return _myTableView;
}

@end