//
//  ShareViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/9/12.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "ShareViewController.h"

#import "ShareFriendsCollectionViewCell.h"

#import "Constants.h"
#import "InviteRegulationView.h"
#import "InvitePackageView.h"

#import "CTAPIBaseManager.h"

#import "UIImageView+WebCache.h"
#import "WXApi.h"
#import "CoinsCenterViewController.h"

@interface ShareViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>

@property (nonatomic, strong)UIScrollView *scrollView;

@property (nonatomic, strong)UIView *backView;


@property (nonatomic, strong)UIImageView *img_back;

@property (nonatomic, strong)UIImageView *strategyImg;

@property (nonatomic, strong)UIButton *btn_invite;

@property (nonatomic, strong)UIImageView *img_hand;

@property (nonatomic, strong)UIView *whiteCardView;

@property (nonatomic, strong)UIView *redLineView;

@property (nonatomic, strong)UILabel *lb_strategyTitle;

@property (nonatomic, strong)NSArray *imagesArray;
@property (nonatomic, strong)NSArray *titleArray;

@property (nonatomic, strong)NSMutableArray *imageViewArray;

@property (nonatomic, strong)NSMutableArray *lbsArray;

@property (nonatomic, strong)UIView *redLineView2;

@property (nonatomic, strong)UILabel *lb_strategyTitle2;

@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, strong)UIView *emptyView;

@property (nonatomic, strong)UIView *redLineView3;

@property (nonatomic, strong)UILabel *lb_strategyTitle3;

@property (nonatomic, strong)UILabel *lb_content;

@property (nonatomic, strong)UIButton *rightBtn;

@property (nonatomic, strong)CTAPIBaseManager *manager;

@property (nonatomic, strong)NSArray *dataArray;

@property (nonatomic, strong) NSDictionary *ShareDic;

@end

@implementation ShareViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.scrollView];
    [self navConfig];

    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
    
    
    self.navigationItem.rightBarButtonItem = rightItem;
    
     NSMutableArray *vcArr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    
    for (UIViewController* vc in vcArr) {
        if ([vc isKindOfClass:[WebVC class]]) {
            [vcArr removeObject:vc];
            break;
        }
    }
    self.navigationController.viewControllers = vcArr;
    
    
    [self loadData];
    
    [self getShareUrl];
   
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [GTCountSDK trackCountEvent:@"life_invitePeople" withArgs:@{}];//个推统计
//    WeakSelf
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHex:0xf24b2a];
//
//    [self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
//        weakSelf.navigationController.navigationBar.barTintColor = [UIColor colorWithHex:0xf24b2a];
//    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
//    }];
//
//     self.navigationController.navigationBar.translucent = NO;
    
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0xf24b2a] image:nil isOpaque:YES];//颜色
         
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
    
//    [UIView animateWithDuration:0.7 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
//        [UIView setAnimationRepeatCount:MAXFLOAT];
//        weakSelf.img_hand.transform = CGAffineTransformMakeScale(1.2, 1.2);
//    } completion:^(BOOL finished) {
//
//        weakSelf.img_hand.transform = CGAffineTransformMakeScale(1.0, 1.0);
//    }];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    WeakSelf
    [self.redLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(16 * WIDTHRADIU);
        make.left.offset(8 * WIDTHRADIU);
        make.height.offset(16);
        make.width.offset(2);
    }];
    
    [self.lb_strategyTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.redLineView);
        make.left.equalTo(weakSelf.redLineView.mas_right).offset(5);
        make.height.offset(16);
    }];
    
//    UILabel *lb = self.lbsArray[0];
    
    [self.redLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.btn_invite.mas_bottom).offset(20 * WIDTHRADIU);
        make.left.offset(8 * WIDTHRADIU);
        make.height.offset(16);
        make.width.offset(2);
    }];
    
    [self.lb_strategyTitle2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.redLineView2);
        make.left.equalTo(weakSelf.redLineView2.mas_right).offset(5);
        make.height.offset(16);
    }];
    
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(8 * WIDTHRADIU);
        make.right.offset(-8 * WIDTHRADIU);
        make.top.equalTo(weakSelf.redLineView2.mas_bottom).offset(4 * WIDTHRADIU);
        make.height.offset(140);
    }];
    
    
    [self.redLineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.collectionView.mas_bottom).offset(2 * WIDTHRADIU);
        make.left.offset(8 * WIDTHRADIU);
        make.height.offset(16);
        make.width.offset(2);
    }];
    
    [self.lb_strategyTitle3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.redLineView3);
        make.left.equalTo(weakSelf.redLineView3.mas_right).offset(5);
        make.height.offset(16);
    }];
    
    [self.lb_content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10 * WIDTHRADIU);
        make.right.offset(-10 * WIDTHRADIU);
        make.top.equalTo(weakSelf.redLineView3.mas_bottom).offset(15);
    }];

}

- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor colorWithHex:0xf22a2a];
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    backBtn.frame = CGRectMake(10, cl_kStatusBarHeight, 60, 44);
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel* lb_title = [UILabel new];
    lb_title.text = self.title;
    lb_title.font = [UIFont boldSystemFontOfSize:18];
    lb_title.textAlignment = NSTextAlignmentCenter;
    lb_title.textColor = [UIColor whiteColor];
    [navView addSubview:backBtn];
    [navView addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.centerX.equalTo(navView);
        make.height.offset(44);
    }];
    
    [navView addSubview:self.rightBtn];
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.right.offset(-10);
        make.width.offset(80);
        make.height.offset(44);
    }];
    
    [self.view addSubview:navView];
}

#pragma mark - load api

- (void)loadData
{
    NSString *url = [NSString stringWithFormat:@"%@/socialsecurity/recommendService/getALLRecommendRecord",IPDIZHI];

    NSDictionary *params = @{
                             @"recommendId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"recommendTelphone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
                             };
    [NetworkRequest SBAuthPost:url Params:params Success:^(id _Nonnull responseObject) {
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            
            if ([code isKindOfClass:[NSNumber class]]) {
                
                
                if (code.integerValue == 0) {
                    NSDictionary *results = responseObject[@"result"];
                    
                    NSArray *array = results[@"recommendRecord"];
                    
                    if ([array isKindOfClass:[NSArray class]]) {
                        self.dataArray = array;
                    }
                    
                    NSNumber *recommendNums = responseObject[@"result"][@"recommendNums"];
                    NSNumber *totalScore = responseObject[@"result"][@"totalScore"];
                    if ([recommendNums isKindOfClass:[NSNumber class]] && [totalScore isKindOfClass:[NSNumber class]]) {
                        if (recommendNums.integerValue > 0 && totalScore.integerValue > 0) {
                            InvitePackageView *packageView = [[InvitePackageView alloc]initWithCoinsNumber:[NSString stringWithFormat:@"%d",totalScore.intValue] friendsNumber:[NSString stringWithFormat:@"%d",recommendNums.intValue] buttonTitle:@"确认"];
                            [packageView show];
                        }
                    }
                    
                    [self.collectionView reloadData];
                }
            }
        }
        
    } Failure:^(NSError * _Nonnull error) {
        
    }];
    
    
   
}



- (void)extracted:(NSMutableDictionary *)params url:(NSString *)url {
    WeakSelf
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            if ([code isKindOfClass:[NSNumber class]]) {
                if (code.integerValue == 1006) {
                    //@1缩放s动画
                    
                    NSDate *oldDate = [NSDate date];
                    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"shareLastTime"];
                    [[NSUserDefaults standardUserDefaults]synchronize];
                    
                    NSNumber *score = responseObject[@"result"][@"score"];
                    if ([score isKindOfClass:[NSNumber class]]) {
                        
                        
                        [weakSelf alertWithScore:score];
                        if (weakSelf.clickBlock) {
                                           weakSelf.clickBlock(YES);
                                       }else{
                                           NSLog(@"block为nil");
                                       }
                    }
                    
                    
                    
                }
                
               
                
            }
            
           
        }
    }];
}

//雷俊博,认证成功获取金币
- (void)loadData2{
    
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"shareLastTime"];
    
    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }
    
    
    NSString *url = [NSString stringWithFormat:@"%@score/increateScore",CoinsBaseUrl];
    NSDictionary *dic = @{
                          @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":@"1008",
                          @"reqTimesTamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2"
                          };
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&Kanwf574",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    
    
    
    
    
    
    [self extracted:params url:url];
    
}





#pragma mark -  UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        NSLog(@"%f",offsetY);
        
        if (offsetY <= 0) {
            scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0);
        }
    }
}




#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    
    if (self.dataArray.count == 0) {
        collectionView.backgroundView = self.emptyView;
    }else{
        collectionView.backgroundView = nil;
    }
    
    return self.dataArray.count;
    
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    ShareFriendsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    NSDictionary *dic = self.dataArray[indexPath.item];
    
    [cell.img_icon sd_setImageWithURL:[NSURL URLWithString:dic[@"icoUrl"]] placeholderImage:[UIImage imageNamed:@"my_information_headportrait_default"]];
    
    cell.lb_name.text =  [EnercryTool decryptUseDES:dic[@"accountName"] key:DESKEY];
    
    
    return cell;
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
   
    CGFloat width = (CGRectGetWidth(collectionView.bounds) - 4 * 5) / 5;
    CGFloat realWidth = (CGRectGetWidth(collectionView.bounds) - 4 * 5) - floor(width) * 4;
    // CGFloat itemW = K_ScreenWidth/array.count;
    if (indexPath.row%5 == 0) {
        return CGSizeMake(realWidth, 66);
    }else {
        return CGSizeMake(floor(width), 66);
    }
}
/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5.0;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 5.0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}

#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"CoinCenterShowLastTime"];

    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
        return;
    }
    
    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"CoinCenterShowLastTime"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    WeakSelf
    [GuideAlertView showWithImageName:@"guide_sign" VC:self Block:^(BOOL success) {
        [weakSelf goToCoinCenterVC];
    }];
    return;
    
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)inviteFriendsClick:(UIButton *)sender
{
    NSLog(@"点击立即邀请按钮");
    
    [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
}

- (void)btnClick:(UIButton *)sender
{
    [self showDeclareAlertView];
//    [self showPackageView];
}

- (void)showDeclareAlertView {
    NSString *str = @"1、每天首次分享可获得100金币；\n2、分享好友（每个用户只能被邀请一次），你和好友各得5000金币，仅限新用户，下载看看生活并登录成功才算邀请成功；\n3、已成功邀请的好友会在“我的好友”中显示；\n4、邀请家人、朋友、同学、同事或分享微信群成功率更高；\n5、本活动最终解释权归看看生活所有。";
    
    InviteRegulationView *alertView = [[InviteRegulationView alloc]initWithTitle:@"规则说明" message:str delegate:self ButtonTitle:@"知道了"];
    
    [alertView show];
    
}

- (void)showPackageView
{
    InvitePackageView *packageView = [[InvitePackageView alloc]initWithCoinsNumber:@"500" friendsNumber:@"1" buttonTitle:@"确认"];
    [packageView show];
}

#pragma mark - 金币中心
- (void)goToCoinCenterVC
{
    CoinsCenterViewController *vc = [[CoinsCenterViewController alloc]init];
    vc.title = @"金币中心";
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - private methods

// 判断是否是同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}

-(NSInteger )getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSInteger timeSp = [datenow timeIntervalSince1970]*1000;
    
    return timeSp;
}

//网页分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }
    if (self.ShareDic.count == 0) {
        return;
    }
    
    WeakSelf
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    //创建网页内容对象
//    NSString* thumbURL =  UMS_THUMB_IMAGE;
//    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"安全认证 轻松领钱" descr:@"邀您一起拿金币,赢大奖" thumImage:[UIImage imageNamed:@"login_icon"]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.ShareDic[@"title"] descr:self.ShareDic[@"description"] thumImage:[UIImage imageNamed:@"login_icon"]];

    //设置网页地址
//    NSString *url = [NSString stringWithFormat:@"%@?userid=%ld&telephone=%@&appName=kksh",self.ShareDic[@"targetUrl"],[getPeopleID PeopleID],[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]];//外网
//    NSString *url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/lesson/award/shareapp/index.html?userid=%ld&telephone=%@&appName=kksh",[getPeopleID PeopleID],[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]];//外网
    shareObject.webpageUrl = self.ShareDic[@"targetUrl"];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
            
            [weakSelf loadData2];
        }
        
    }];
}

- (void)alertWithScore:(NSNumber *)score
{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"每日分享成功"
                                                    message:[NSString stringWithFormat:@"赠送%@金币",score]
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"确定", @"确定")
                                          otherButtonTitles:nil];
    [alert show];
}

//渐变色
- (UIImage *)convertViewToImage:(UIView *)v
{
    CGSize s = v.bounds.size;
    //UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
    format.opaque = NO;
    format.scale = [[UIScreen mainScreen] scale];
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:s format:format];
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(NSAttributedString *)getAttributedStringWithString:(NSString *)string lineSpace:(CGFloat)lineSpace {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace; // 调整行间距
    NSRange range = NSMakeRange(0, [string length]);
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    return attributedString;
}

- (void)zoom
{
    // 比例缩放
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    // 1秒后执行
    animation.beginTime = CACurrentMediaTime() + 1;
    // 持续时间
    animation.duration = 2.5;
    // 重复次数
    animation.repeatCount = 0;
    // 起始scale
    animation.fromValue = @(1.0);
    // 终止scale
    animation.toValue = @(1.5);
    // 添加动画
    [self.img_hand.layer addAnimation:animation forKey:@"zoom"];
}


#pragma mark - getters and setters
- (UIView *)getNavBackView
{
    UIView*backView = [[UIView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth,cl_kNavigationBarHeight)];
    CAGradientLayer*gradientLayer = [CAGradientLayer layer];
    gradientLayer.locations = @[@0.0, @1.0];
    gradientLayer.startPoint = CGPointMake(1, 0);
    gradientLayer.endPoint = CGPointMake(1, 1);
    [gradientLayer setColors:@[(id)[[UIColor colorWithHex:0xff5633] CGColor],(id)[[UIColor colorWithHex:0xf8502c] CGColor]]];//渐变数组
    gradientLayer.frame = backView.frame;
    [backView.layer addSublayer:gradientLayer];
    return backView;
}


#pragma mark  - getters and setters

- (CTAPIBaseManager *)manager
{
    if (!_manager) {
        _manager = [[CTAPIBaseManager alloc]init];
    }
    return _manager;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight)];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentSize = CGSizeMake(ScreenWidth, ScreenHeight * 1.3 + 90);
        _scrollView.delegate = self;
        
        
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        
        [_scrollView addSubview:self.backView];
    }
    return _scrollView;
}

- (UIView *)backView
{
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight * 1.3 + 90)];
        _backView.backgroundColor = [UIColor whiteColor];
        
        [_backView addSubview:self.img_back];
//        [_backView addSubview:self.btn_invite];
//        [_backView addSubview:self.img_hand];
        [_backView addSubview:self.whiteCardView];
    }
    return _backView;
}


- (UIImageView *)img_back
{
    if (!_img_back) {
        _img_back = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 298 * WIDTHRADIU)];
        _img_back.image = [UIImage imageNamed:@"bg_inviteFriend"];
    }
    return _img_back;
}

- (UIButton *)btn_invite
{
    if (!_btn_invite) {
        _btn_invite = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn_invite.frame = CGRectMake(45 * WIDTHRADIU, 180 * WIDTHRADIU, ScreenWidth - 90 * WIDTHRADIU, 45 * WIDTHRADIU);
        _btn_invite.backgroundColor = [UIColor colorWithHex:0xf22a2a];
        _btn_invite.layer.cornerRadius = 22.5 * WIDTHRADIU;
        [_btn_invite setTitle:@"立即邀请" forState:UIControlStateNormal];
        [_btn_invite setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _btn_invite.titleLabel.font = [UIFont systemFontOfSize:17];
        [_btn_invite addTarget:self action:@selector(inviteFriendsClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _btn_invite.layer.shadowColor = [UIColor colorWithHex:0xfd7b70].CGColor;
        // 阴影偏移，默认(0, -3)
        _btn_invite.layer.shadowOffset = CGSizeMake(0,0);
        // 阴影透明度，默认0
        _btn_invite.layer.shadowOpacity = 0.7;
        // 阴影半径，默认3
        _btn_invite.layer.shadowRadius = 3;
        
        CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animation.fromValue=[NSNumber numberWithFloat:0.9];
        animation.toValue=[NSNumber numberWithFloat:1.1];
        animation.duration=0.5;
        animation.autoreverses=YES;
        animation.repeatCount=HUGE_VALF;
        animation.removedOnCompletion=NO;
        animation.fillMode=kCAFillModeForwards;
        [_btn_invite.layer addAnimation:animation forKey:@"zoom"];
        
    }
    return _btn_invite;
}

- (UIImageView *)img_hand
{
    if (!_img_hand) {
        _img_hand = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 130 * WIDTHRADIU, 190 * WIDTHRADIU, 33 * WIDTHRADIU, 31 * WIDTHRADIU)];
        _img_hand.image = [UIImage imageNamed:@"手势"];
        
        CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animation.fromValue=[NSNumber numberWithFloat:0.9];
        animation.toValue=[NSNumber numberWithFloat:1.1];
        animation.duration=0.5;
        animation.autoreverses=YES;
        animation.repeatCount=HUGE_VALF;
        animation.removedOnCompletion=NO;
        animation.fillMode=kCAFillModeForwards;
        [_img_hand.layer addAnimation:animation forKey:@"zoom"];
      
    }
    return _img_hand;
}
- (UIImageView *)strategyImg
{
    if (!_strategyImg) {
        _strategyImg = [[UIImageView alloc]initWithFrame:CGRectMake(36 * WIDTHRADIU, 56 * WIDTHRADIU, ScreenWidth - 72 * WIDTHRADIU , 101 * WIDTHRADIU)];
        _strategyImg.image = [UIImage imageNamed:@"攻略"];
    }
    return _strategyImg;
}
- (UIView *)whiteCardView
{
    if (!_whiteCardView) {
        _whiteCardView = [[UIView alloc]initWithFrame:CGRectMake(0, 298 * WIDTHRADIU, ScreenWidth , 350 * WIDTHRADIU+ 90)];
        _whiteCardView.backgroundColor = [UIColor whiteColor];
        
//        _whiteCardView.layer.cornerRadius = 7;
        
        [_whiteCardView addSubview:self.redLineView];
        [_whiteCardView addSubview:self.lb_strategyTitle];
        [_whiteCardView addSubview:self.strategyImg];
        [_whiteCardView addSubview:self.btn_invite];
        [_whiteCardView addSubview:self.img_hand];
        
        [_whiteCardView addSubview:self.redLineView2];
        [_whiteCardView addSubview:self.lb_strategyTitle2];
        [_whiteCardView addSubview:self.collectionView];
        [_whiteCardView addSubview:self.redLineView3];
        [_whiteCardView addSubview:self.lb_strategyTitle3];
        [_whiteCardView addSubview:self.lb_content];
        
//        for (int i=0; i < 3; i++) {
//            UIImageView *imgView = [[UIImageView alloc]init];
//            imgView.image = [UIImage imageNamed:self.imagesArray[i]];
//
//            UILabel *lb = [[UILabel alloc]init];
//            lb.attributedText = [self getAttributedStringWithString:self.titleArray[i] lineSpace:5];
//            lb.font = [UIFont systemFontOfSize:13];
//            lb.textAlignment = NSTextAlignmentCenter;
//            lb.textColor = [UIColor colorWithHex:0x78370c];
//            lb.numberOfLines = 0;
//
//
//
//            if (i == 0) {
//                imgView.frame = CGRectMake(30 * WIDTHRADIU, 36 * WIDTHRADIU + 16, 48 * WIDTHRADIU, 52 * WIDTHRADIU);
//            }else if (i == 1){
//                imgView.frame = CGRectMake((_whiteCardView.bounds.size.width - 48 * WIDTHRADIU)/2, 36 * WIDTHRADIU + 16, 48 * WIDTHRADIU, 52 * WIDTHRADIU);
//            }else if (i == 2){
//                 imgView.frame = CGRectMake((_whiteCardView.bounds.size.width - 78 * WIDTHRADIU), 36 * WIDTHRADIU + 16, 48 * WIDTHRADIU, 52 * WIDTHRADIU);
//            }
//
//            [_whiteCardView addSubview:imgView];
//            [_whiteCardView addSubview:lb];
//            [lb mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.centerX.equalTo(imgView);
//                make.top.equalTo(imgView.mas_bottom).offset(15 * WIDTHRADIU);
//            }];
//
//            [self.imageViewArray addObject:imgView];
//            [self.lbsArray addObject:lb];
//
//        }
//
//        for (int i = 0 ; i < 2; i++) {
//            UIImageView *imgView = [[UIImageView alloc]init];
//            imgView.image = [UIImage imageNamed:@"箭头"];
//
//            UIImageView *v1 = self.imageViewArray[0];
//            UIImageView *v2 = self.imageViewArray[1];
//            CGFloat distance = CGRectGetMinX(v2.frame) - CGRectGetMaxX(v1.frame);
//            if (i == 0) {
//                imgView.center = CGPointMake(CGRectGetMaxX(v1.frame) + distance/2, v1.center.y + 4 * WIDTHRADIU);
//            }else if (i == 1){
//                imgView.center = CGPointMake(CGRectGetMaxX(v2.frame) + distance/2, v1.center.y + 4 * WIDTHRADIU);
//            }
//            imgView.bounds = CGRectMake(0, 0, 54, 10);
//            [_whiteCardView addSubview:imgView];
//
//        }
    }
    return _whiteCardView;
}

- (UIView *)redLineView
{
    if (!_redLineView) {
        _redLineView = [[UIView alloc]init];
        _redLineView.backgroundColor = [UIColor colorWithHex:0xea3320];
    }
    return _redLineView;
}

- (UILabel *)lb_strategyTitle
{
    if (!_lb_strategyTitle) {
        _lb_strategyTitle = [[UILabel alloc]init];
        _lb_strategyTitle.text = @"邀请好友攻略";
        _lb_strategyTitle.textColor = [UIColor colorWithHex:0x4d4d4d];
        _lb_strategyTitle.font = [UIFont systemFontOfSize:16];
    }
    return _lb_strategyTitle;
}

- (UIView *)redLineView2
{
    if (!_redLineView2) {
        _redLineView2 = [[UIView alloc]init];
        _redLineView2.backgroundColor = [UIColor colorWithHex:0xea3320];
    }
    return _redLineView2;
}

- (UILabel *)lb_strategyTitle2
{
    if (!_lb_strategyTitle2) {
        _lb_strategyTitle2 = [[UILabel alloc]init];
        _lb_strategyTitle2.text = @"我的好友";
        _lb_strategyTitle2.textColor = [UIColor colorWithHex:0x4d4d4d];
        _lb_strategyTitle2.font = [UIFont systemFontOfSize:16];
    }
    return _lb_strategyTitle2;
}

- (NSArray *)imagesArray
{
    if (!_imagesArray) {
        _imagesArray = @[@"分享",@"输入手机号",@"获得奖励金"];
    }
    return _imagesArray;
}

- (NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = @[@"分享链接\n给好友",@"好友在链接中输入手机号\n下载并注册看看生活",@"双方各得\n5000金币"];
    }
    return _titleArray;
}

- (NSMutableArray *)imageViewArray
{
    if (!_imageViewArray) {
        _imageViewArray = [[NSMutableArray alloc]init];
    }
    return _imageViewArray;
}

- (NSMutableArray *)lbsArray
{
    if (!_lbsArray) {
        _lbsArray = [[NSMutableArray alloc]init];
    }
    return _lbsArray;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        
        // _collectionView.backgroundColor = K_GrayColor;
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        //布局
        fl.minimumLineSpacing = 0;
        fl.minimumInteritemSpacing = 0;
        
        //cell注册
        [_collectionView registerNib:[UINib nibWithNibName:@"ShareFriendsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        //         [_collectionView registerNib:[UINib nibWithNibName:@"BannerCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"bannerCell"];
        //         [_collectionView registerNib:[UINib nibWithNibName:@"RadioCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"radioHeader"];
    }
    return _collectionView;
}

- (UIView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth - 36 * WIDTHRADIU, 145)];
        
        UILabel *lb = [[UILabel alloc]init];
        lb.attributedText = [self getAttributedStringWithString:@"您还没有好友\n邀好友，赚金币，快去试试" lineSpace:5];
        lb.font = [UIFont systemFontOfSize:15];
        lb.textAlignment = NSTextAlignmentCenter;
        lb.textColor = [UIColor colorWithHex:0xbfbfbf];
        lb.numberOfLines = 0;
        
        [_emptyView addSubview:lb];
        
        [lb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self->_emptyView);
            make.top.offset(40);
        }];
        
    }
    return _emptyView;
}


- (UIView *)redLineView3
{
    if (!_redLineView3) {
        _redLineView3 = [[UIView alloc]init];
        _redLineView3.backgroundColor = [UIColor colorWithHex:0xea3320];
    }
    return _redLineView3;
}

- (UILabel *)lb_strategyTitle3
{
    if (!_lb_strategyTitle3) {
        _lb_strategyTitle3 = [[UILabel alloc]init];
        _lb_strategyTitle3.text = @"邀请说明";
        _lb_strategyTitle3.textColor = [UIColor colorWithHex:0x4d4d4d];
        _lb_strategyTitle3.font = [UIFont systemFontOfSize:16];
    }
    return _lb_strategyTitle3;
}

- (UILabel *)lb_content
{
    if (!_lb_content) {
        _lb_content = [[UILabel alloc]init];
        NSString *text = @"1、每天首次分享可获得100金币；\n2、好友打开分享链接下载注册看看生活，你和好友各得5000金币；\n3、每个用户只能被邀请一次，多邀多得，上不封顶(仅展示最近邀请的20人)；\n4、邀请家人、朋友、同学、同事或分享微信群成功率更高；\n";
        
        
        //行间距
        NSMutableParagraphStyle * paragraphstyle =[[NSMutableParagraphStyle alloc]init];
        [paragraphstyle setLineSpacing:8];
        paragraphstyle.alignment = NSTextAlignmentLeft;
        
        NSMutableAttributedString * attribustring =[[NSMutableAttributedString alloc]initWithString: text attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14*WIDTHRADIU],NSForegroundColorAttributeName:[UIColor colorWithHex:0x808080],NSParagraphStyleAttributeName:paragraphstyle}];

        _lb_content.attributedText = attribustring;
        _lb_content.numberOfLines = 0;
    }
    
    return _lb_content;
}

- (UIButton *)rightBtn
{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.frame = CGRectMake(0, 0, 80, 40);
        [_rightBtn setTitle:@"规则说明" forState:UIControlStateNormal];
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        
        [_rightBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}

#pragma mark - 获取分享地址
- (void)getShareUrl{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    app_Version = [app_Version stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSString *url = [NSString stringWithFormat:@"%@shareservice/getShareUrl",CoinsBaseUrl];
//    NSString *url = [NSString stringWithFormat:@"%@scoreService/shareservice/getShareUrl",@"http://172.16.10.215:8080/"];
    NSDictionary *params1 = @{
        @"userId":@([getPeopleID PeopleID]),
        @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
        @"shareType":@"21002",
        @"fromModel":@(2),
        @"platform":@"kksh",
        @"version":app_Version,
    };
    WeakSelf
    [NetworkRequest Post11:url Params:params1 Success:^(id _Nonnull objc) {
        if ([objc[@"result"] isKindOfClass:[NSDictionary class]]) {
            weakSelf.ShareDic = objc[@"result"];
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
/*
#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
