//
//  PensionContributionVC.m
//  Open
//
//  Created by qinxuyang on 2022/2/23.
//  Copyright © 2022 QXY. All rights reserved.
//

#import "PensionContributionVC.h"
#import "PensionContributionCell.h"
#import "PensionSectionView.h"
//百度
#import <BMKLocationKit/BMKLocationComponent.h>
@interface PensionContributionVC ()<UICollectionViewDelegate,UICollectionViewDataSource,BMKLocationManagerDelegate>
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *promptView;
@property (nonatomic, strong) NSMutableArray *historyArr;
@property (nonatomic, strong) NSArray *hotArr;
@property (nonatomic, strong) NSArray *dataArr;
@property (nonatomic, strong) NSDictionary *currentprovince;
//百度
@property (nonatomic, strong)BMKLocationManager *locationManager;
@end

@implementation PensionContributionVC
- (NSMutableArray *)historyArr{
    if (_historyArr == nil) {
        NSArray* historyCity = [UserDefault objectForKey:@"historyCity"];
        if (historyCity.count > 0) {
            _historyArr = [NSMutableArray arrayWithArray:historyCity];
        }else{
            _historyArr = [NSMutableArray array];
        }
       
    }
    return _historyArr;
}
- (NSArray *)hotArr{
    if (_hotArr == nil) {
        _hotArr = [NSArray array];
    }
    return _hotArr;
}
- (NSArray *)dataArr{
    if (_dataArr == nil) {
        _dataArr = [NSArray array];
    }
    return _dataArr;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0xFB7C23] image:nil isOpaque:YES];//颜色
    
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self navConfig];
    
    [self.view addSubview:self.collectionView];
    
    [self loadData];
}
- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = K_MainColor;
    [self.view addSubview:navView];
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight + 9.5, 50, 25);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateHighlighted];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitle:@"返回" forState:UIControlStateHighlighted];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    

    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.text = @"养老金缴纳";
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];

    UIView *promptView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(navView.frame), ScreenWidth, 40)];
    promptView.backgroundColor = [UIColor colorWithHex:0xe4f4ff];
    self.promptView = promptView;
    [self.view addSubview:promptView];
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth - 60, 40)];
    lab.text = @"选择您缴纳“城乡居民社保养老保险”的省份";
    lab.textColor = [UIColor colorWithHex:0x1075bd];
    lab.font = [UIFont systemFontOfSize:14.0];
    [promptView addSubview:lab];
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 40, 5, 30, 30)];
    [button setImage:[UIImage imageNamed:@"blueClose"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(removePromp) forControlEvents:UIControlEventTouchUpInside];
    [promptView addSubview:button];
}
#pragma mark - 移除视图
- (void)removePromp{
    [self.promptView removeFromSuperview];
    self.collectionView.frame = CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight);
}
#pragma mark - 返回
- (void)backClick:(UIButton *)button{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (self.historyArr.count > 0) {
        return 4;
    }
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        if (self.historyArr.count > 0) {
            return self.historyArr.count;
        }else{
            return self.hotArr.count;
        }
    }else if (section == 2){
        if (self.historyArr.count > 0) {
            return self.hotArr.count;
        }else{
            return self.dataArr.count;
        }
    }else{
        return self.dataArr.count;
    }
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PensionContributionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PensionContributionCell" forIndexPath:indexPath];
    cell.titleLabel.text = @"";
    if (indexPath.section == 0) {
        NSString* province = [UserDefault objectForKey:@"locationProvince"];
        if (province.length > 0) {
            cell.titleLabel.text = province;
        }else{
            cell.titleLabel.text = @"定位失败，重新获取";
        }
    }else if (indexPath.section == 1){
        if (self.historyArr.count > 0) {
            NSDictionary *dic = self.historyArr[indexPath.row];
            cell.titleLabel.text = dic[@"province"];
        }else{
            NSDictionary *dic = self.hotArr[indexPath.row];
            cell.titleLabel.text = dic[@"province"];
        }
    }else if (indexPath.section == 2){
        if (self.historyArr.count > 0) {
            NSDictionary *dic = self.hotArr[indexPath.row];
            cell.titleLabel.text = dic[@"province"];
        }else{
            NSDictionary *dic = self.dataArr[indexPath.row];
            cell.titleLabel.text = dic[@"province"];
        }
    }else{
        NSDictionary *dic = self.dataArr[indexPath.row];
        cell.titleLabel.text = dic[@"province"];
    }
    return cell;
}
/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NSString* province = [UserDefault objectForKey:@"locationProvince"];
        if (province.length == 0) {
            CGFloat width = ScreenWidth / 2.0;
            CGFloat height = 40;
            return CGSizeMake(width, height);
        }
    }
    CGFloat width = ScreenWidth / 4.0;
    CGFloat height = 40;
    return CGSizeMake(width, height);
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    PensionSectionView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"PensionSectionView" forIndexPath:indexPath];
    headerView.backgroundColor = [UIColor whiteColor];
    for(UIView *view in  headerView.subviews) {
         [view removeFromSuperview];

    }
    NSArray *sectionTitle = [NSArray array];
    if (self.historyArr.count > 0) {
        sectionTitle = @[@"当前定位",@"历史查看",@"热门缴纳省份",@"更多缴纳省份"];
    }else{
        sectionTitle = @[@"当前定位",@"热门缴纳省份",@"更多缴纳省份"];
    }
     
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 20, ScreenWidth - 30, 20)];
    label.text = @"";
    label.text = sectionTitle[indexPath.section];
    label.textColor = [UIColor colorWithHex:0x333333];
    label.font = [UIFont systemFontOfSize:17.0];
    [headerView addSubview:label];
    return headerView;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NSString* province = [UserDefault objectForKey:@"locationProvince"];
        if (province.length > 0) {
            if (self.currentprovince.count > 0) {
                [self jumpToSmallProgram:self.currentprovince[@"url"]];
                [self updateHistory:self.currentprovince];
            }else{
                [XYProgressHUD showMessage:@"当前地区不在可缴纳省份"];
            }

        }else{
            [self locationDisplay];
        }
    }else if (indexPath.section == 1){
        if (self.historyArr.count > 0) {
            NSDictionary *dic = self.historyArr[indexPath.row];
            NSString *type=dic[@"type"];
            if ([type longLongValue ]==0L) {
                [self jumpToSmallProgram:dic[@"url"]];
            }else if([type longLongValue ] ==1L){
                [self jumpToAliPayProgram:dic[@"url"]];
            }
            [self updateHistory:dic];
        }else{
            NSDictionary *dic = self.hotArr[indexPath.row];
            NSString *type=dic[@"type"];
            if ([type longLongValue ]==0L) {
                [self jumpToSmallProgram:dic[@"url"]];
            }else if([type longLongValue ] ==1L){
                [self jumpToAliPayProgram:dic[@"url"]];
            }
            [self updateHistory:dic];
        }
    }else if (indexPath.section == 2){
        if (self.historyArr.count > 0) {
            NSDictionary *dic = self.hotArr[indexPath.row];
            NSString *type=dic[@"type"];
            if ([type longLongValue ]==0L) {
                [self jumpToSmallProgram:dic[@"url"]];
            }else if([type longLongValue ] ==1L){
                [self jumpToAliPayProgram:dic[@"url"]];
            }
            [self updateHistory:dic];
        }else{
            NSDictionary *dic = self.dataArr[indexPath.row];
            NSString *type=dic[@"type"];
            if ([type longLongValue ]==0L) {
                [self jumpToSmallProgram:dic[@"url"]];
            }else if([type longLongValue ] ==1L){
                [self jumpToAliPayProgram:dic[@"url"]];
            }
            [self updateHistory:dic];
        }
    }else{
        NSDictionary *dic = self.dataArr[indexPath.row];
        NSString *type=dic[@"type"];
        if ([type longLongValue ]==0L) {
            [self jumpToSmallProgram:dic[@"url"]];
        }else if([type longLongValue ] ==1L){
            [self jumpToAliPayProgram:dic[@"url"]];
        }
        [self updateHistory:dic];
    }
}

#pragma mark - 跳转支付宝小程序
- (void)jumpToAliPayProgram:(NSString *)url{
    if (url.length == 0) {
        return;
    }
    NSURL * alipay_app_url = [NSURL URLWithString:@"alipay://"];
    BOOL ali = [[UIApplication sharedApplication] canOpenURL:alipay_app_url];
    if (ali) {
        //NSString *url = url;
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:nil completionHandler:nil];
    }else{
        //未安装支付宝
        [XYProgressHUD showMessage:@"请安装支付宝后重试！"];
    }
}

#pragma mark - 跳转微信小程序
- (void)jumpToSmallProgram:(NSString *)url{
    if (url.length == 0) {
        return;
    }
    NSString *userName = url;
    NSString *path = @"";
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = userName; //拉起的小程序的username
    launchMiniProgramReq.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        
    }];
}

#pragma mark - 更新历史数据
- (void)updateHistory:(NSDictionary *)dic{
    for (NSDictionary *existingDic in [self.historyArr copy]) {
        if ([dic[@"province"] isEqualToString:existingDic[@"province"]]) {
            [self.historyArr removeObject:dic];
        }
    }
    [self.historyArr insertObject:dic atIndex:0];
    if (self.historyArr.count > 4) {
        [self.historyArr removeObjectAtIndex:4];
    }
    [UserDefault setObject:self.historyArr forKey:@"historyCity"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    [self.collectionView reloadData];
}

#pragma mark-初始化collectionView
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight + 40, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - 40) collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        //隐藏滚动条
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[PensionSectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PensionSectionView"];
        [_collectionView registerNib:[UINib nibWithNibName:@"PensionContributionCell" bundle:nil] forCellWithReuseIdentifier:@"PensionContributionCell"];
    }
    return _collectionView;
}
- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.minimumLineSpacing = 20;
        _flowLayout.minimumInteritemSpacing = 0;
        _flowLayout.headerReferenceSize = CGSizeMake(ScreenWidth, 50);
    }
    return _flowLayout;
}
#pragma mark - 定位
//定位
-(void)locationDisplay
{
    
    _locationManager = [[BMKLocationManager alloc] init];
     //设置delegate
    _locationManager.delegate = self;
     //设置返回位置的坐标系类型
    _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
     //设置距离过滤参数
    _locationManager.distanceFilter = kCLDistanceFilterNone;
     //设置预期精度参数
    _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
     //设置应用位置类型
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
     //设置是否自动停止位置更新
    _locationManager.pausesLocationUpdatesAutomatically = NO;
     //设置是否允许后台定位
     //_locationManager.allowsBackgroundLocationUpdates = YES;
     //设置位置获取超时时间
    _locationManager.locationTimeout = 10;
     //设置获取地址信息超时时间
    _locationManager.reGeocodeTimeout = 10;
    
    //[_locationManager startUpdatingLocation];
     [_locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        [self->_locationManager stopUpdatingLocation]; //停止定位
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        
        if (location) { //得到定位信息，添加annotation
            if (location.location) {
                NSLog(@"LOC = %@",location.location);
            }
            if (location.rgcData) {
                NSLog(@"rgc = %@",[location.rgcData description]);
            }
            
            if (location.rgcData.poiList) {
                for (BMKLocationPoi * poi in location.rgcData.poiList) {
                    NSLog(@"poi = %@", poi.name);
                }
            }
            
            
            if (location.rgcData) {
                NSLog(@"定位信息:%@%@%@%@%@",location.rgcData.province,location.rgcData.city,location.rgcData.district,location.rgcData.street,location.rgcData.streetNumber);
                
                NSString *address = [NSString stringWithFormat:@"%@%@%@%@%@%@(%@)",[NSString validBlankStr:location.rgcData.province],[NSString validBlankStr:location.rgcData.city],[NSString validBlankStr:location.rgcData.district],[NSString validBlankStr:location.rgcData.town],[NSString validBlankStr:location.rgcData.street],[NSString validBlankStr:location.rgcData.streetNumber],[NSString validBlankStr:location.rgcData.locationDescribe]];
                
                

                 [[NSUserDefaults standardUserDefaults]setObject:location.rgcData.province forKey:@"locationProvince"];
                [[NSUserDefaults standardUserDefaults]setObject:location.rgcData.city forKey:@"locationCity"];
                [[NSUserDefaults standardUserDefaults]setObject:location.rgcData.district forKey:@"locationCounty"];
                [[NSUserDefaults standardUserDefaults]setObject:address forKey:@"locationAddress"];
                [UserDefault setObject:[NSString stringWithFormat:@"%f,%f",location.location.coordinate.longitude,location.location.coordinate.latitude] forKey:@"locationCoordinate"];
                [[NSUserDefaults standardUserDefaults]synchronize];
                
                [self.collectionView reloadData];
            }
        }
     }];
}
#pragma mark - loadData
- (void)loadData{
    WeakSelf
    NSString*version = nil;
    NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray*vArr = [v componentsSeparatedByString:@"."];
    for (int i = 0; i < vArr.count; i++) {
        if (version == nil) {
            version = [NSString stringWithFormat:@"%@",vArr[i]];
        }else{
            version = [version stringByAppendingFormat:@"%@",vArr[i]];
        }
    }
    NSURL * alipay_app_url = [NSURL URLWithString:@"alipay://"];
    BOOL ali = [[UIApplication sharedApplication] canOpenURL:alipay_app_url];
    NSString *alipay=nil;
    if (ali) {
        alipay=@"1";
    }else{
        //未安装支付宝
        alipay=@"0";
    }
    //+version+@"&alipay="+alipay
    NSString *url = @"https://stt.weface.com.cn/app/get_shebao_pay?os=iOS&ver=";
    url=[url stringByAppendingFormat:@"%@%@%@",version,@"&alipay=",alipay];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [NetworkRequest Get4:url Params:param Success:^(id _Nonnull responseObject) {

        NSLog(@"========responseObject:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            weakSelf.hotArr = responseObject[@"result"][@"hot"];
           
            weakSelf.dataArr = responseObject[@"result"][@"all"];
            NSString* province = [UserDefault objectForKey:@"locationProvince"];
            if (province.length > 0) {
                for (NSDictionary *dic in weakSelf.dataArr) {
                    if ([province containsString:dic[@"province"]]) {
                        weakSelf.currentprovince = dic;
                    }
                }
            }
            
            [weakSelf.collectionView reloadData];
        }
      
    } Failure:^(NSError * _Nonnull 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
