//
//  GasStationDetailsVC.m
//  Open
//
//  Created by qinxuyang on 2021/11/18.
//  Copyright © 2021 QXY. All rights reserved.
//

#import "GasStationDetailsVC.h"
#import "GasStationDetailsCell.h"
#import "GasStationDetailsHeaderView.h"
#import "GasStationDetailsFooterView.h"
#import "PopupView.h"
#import "TYWebViewController.h"

//穿山甲
#import <BUAdSDK/BUAdSDK.h>


@interface GasStationDetailsVC ()<UITableViewDelegate,UITableViewDataSource,BUNativeExpressBannerViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) GasStationDetailsHeaderView *headerView;
@property (nonatomic, strong) GasStationDetailsFooterView *footerView;
@property (nonatomic, strong) PopupView *Popup;
@property (nonatomic, copy) NSString *oilNo;
@property (nonatomic, copy) NSString *oilName;
@property (nonatomic, strong) NSMutableArray *gasNoList;
@property (nonatomic, strong) NSArray *oilPriceList;
@property (nonatomic, copy) NSString *gunNo;

@property (nonatomic, strong) NSDictionary *sizeDcit;
//@property (nonatomic, strong) BUNativeExpressBannerView *bannerView;
@property (nonatomic, strong) UIImageView *bannerView;
@end

@implementation GasStationDetailsVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
   
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    
    if (@available(iOS 11.0, *)) {
           self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
       self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];
    
    self.tableView.tableFooterView = self.footerView;
    
    [self configNav];
    
    [self requestGasPrice];
    
    
    self.bannerView = [[UIImageView alloc]initWithFrame:CGRectMake(10, ScreenHeight - 120 - cl_kTabbarSafeBottomMargin, ScreenWidth - 20, 104)];
    self.bannerView.image = [UIImage imageNamed:@"GasStationDetailsBanner"];
    self.bannerView.userInteractionEnabled = YES;
    self.bannerView.layer.cornerRadius = 10 * WIDTHRADIU;
    self.bannerView.layer.masksToBounds = YES;
    [self.view addSubview:self.bannerView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bannerTap)];
    [self.bannerView addGestureRecognizer:tap];
    
//   self.bannerView = [[BUNativeExpressBannerView alloc] initWithSlotID:@"947180123" rootViewController:self adSize:CGSizeMake(300, 130)];
//   self.bannerView.frame = CGRectMake((ScreenWidth - 300) / 2, CGRectGetMaxY(self.tableView.frame) + 30, 300, 130);
//   self.bannerView.delegate = self;
//   [self.bannerView loadAdData];
}
- (void)bannerTap{
    [self jumpToHTML5:@"http://t.fxyf99.com/XWOF3U8W" andJAnalytics:@"保险"];
}
-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
    WebViewController *tc=[WebViewController new];
    tc.URL =[NSURL URLWithString:url];
            tc.hidesBottomBarWhenPushed =YES;
    tc.janalytics = janalytics;
    [self.navigationController pushViewController:tc animated:YES];

}
- (void)configNav
{
   UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = [UIColor clearColor];
    [self.view addSubview:nav];
    [self.view bringSubviewToFront:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
}
- (void)backClick{
    [self.Popup removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - 250) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//推荐该方法
//        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeader)];
//        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upDown)];
        [_tableView registerNib:[UINib nibWithNibName:@"GasStationCell" bundle:nil] forCellReuseIdentifier:@"GasStationCell"];
    }
    return _tableView;
}
- (GasStationDetailsHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [[[NSBundle mainBundle] loadNibNamed:@"GasStationDetailsHeaderView" owner:self options:nil] firstObject];
        _headerView.frame  = CGRectMake(0, 0, ScreenWidth, 290 + cl_kNavigationBarHeight);
        _headerView.adverView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.6];
        _headerView.adverView.layer.masksToBounds = YES;
        _headerView.adverView.layer.cornerRadius = 2;
        _headerView.headerView.layer.borderWidth = 0.5;
        _headerView.headerView.layer.borderColor = [UIColor colorWithHex:0xf2f2f2].CGColor;
        [_headerView.OilnoBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
        [_headerView.OilnoBtn addTarget:self action:@selector(OilnoBtn:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView.gasLogoBig sd_setImageWithURL:[NSURL URLWithString:_Model.gasLogoBig] completed:nil];
        _headerView.NoticeLab.text =  _gasStationNotice.firstObject;
        _headerView.gasName.text = _Model.gasName;
        _headerView.gasAddress.text = [NSString stringWithFormat:@"%@",_Model.gasAddress];
        _headerView.distance.text = [NSString stringWithFormat:@"%@km",_Model.distance];
        [_headerView.appleMapBtn addTarget:self action:@selector(appleMap:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headerView;
}
- (GasStationDetailsFooterView *)footerView
{
    if (!_footerView) {
        _footerView = [[[NSBundle mainBundle] loadNibNamed:@"GasStationDetailsFooterView" owner:self options:nil] firstObject];
        _footerView.frame = CGRectMake(0,0, ScreenWidth, 90);
        [_footerView.NextBtn addTarget:self action:@selector(nextBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 0;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    GasStationDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GasStationDetailsCell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"GasStationDetailsCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 10;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;;
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
//    lineView.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
//    return lineView;
//}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    lineView.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    return lineView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
#pragma mark - 油站油价信息
- (void)requestGasPrice{
    NSString *url = [NSString stringWithFormat:@"%@tuanyou/gas/price",[NetworkConfig ipGasStationConfig]];
    NSDictionary *params = @{
        @"tel":[getPeopleID PeopleIphoneNmber],
        @"gasIds":self.Model.gasId
    };
    typeof(self) wSelf = self;
    [NetworkRequest PostGasStation:url Params:params Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                NSDictionary *dic = [objc[@"result"] firstObject];
                NSString *str = [NSString stringWithFormat:@"%@",dic[@"oilPriceList"]];
                if ([str isEqualToString:@"<null>"] || [str isEqualToString:@""]) {
                    return;
                }
                NSArray *arr = dic[@"oilPriceList"];
                if (arr.count > 0) {
                    wSelf.oilPriceList = dic[@"oilPriceList"];
                    NSArray *gunNos = wSelf.oilPriceList.firstObject[@"gunNos"];
                    wSelf.oilNo = wSelf.oilPriceList.firstObject[@"oilNo"];
                    wSelf.oilName = wSelf.oilPriceList.firstObject[@"oilName"];
                    wSelf.gunNo = gunNos.firstObject[@"gunNo"];
                    [wSelf.headerView.OilnoBtn setTitle:wSelf.oilName forState:UIControlStateNormal];
                    [wSelf.headerView.OilnoBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleRight imageTitleSpace:5.0];
                    wSelf.headerView.price.text = wSelf.oilPriceList.firstObject[@"priceYfq"];
                    wSelf.headerView.priceGun.text = wSelf.oilPriceList.firstObject[@"priceGun"];
                    wSelf.headerView.priceOfficial.text = wSelf.oilPriceList.firstObject[@"priceOfficial"];
                    wSelf.gasNoList = [NSMutableArray array];
                    //汽油
                    NSMutableArray *gasolineArr = [NSMutableArray array];
                    //柴油
                    NSMutableArray *dieselArr = [NSMutableArray array];
                    //天然气
                    NSMutableArray *NaturaArr = [NSMutableArray array];
                    for (NSDictionary *dic in arr) {
                        if ([dic[@"oilType"] intValue] == 1) {
                              //汽油
                            [gasolineArr addObject:dic];
                        }else if ([dic[@"oilType"] intValue] == 2) {
                            //柴油
                            [dieselArr addObject:dic];
                        }else if ([dic[@"oilType"] intValue] == 3) {
                            //天然气
                            [NaturaArr addObject:dic];
                        }
                    }
                    if (gasolineArr.count > 0) {
                        [wSelf.gasNoList addObject:gasolineArr];
                    }
                    if (dieselArr.count > 0) {
                        [wSelf.gasNoList addObject:dieselArr];
                    }
                    if (NaturaArr.count > 0) {
                        [wSelf.gasNoList addObject:NaturaArr];
                    }
                }
                [wSelf.tableView reloadData];
            }
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
#pragma mark - 立即加油
- (void)nextBtn{
    NSString *url = [NSString stringWithFormat:@"%@tuanyou/pay/url",[NetworkConfig ipGasStationConfig]];
    NSDictionary *params = @{
        @"tel":[getPeopleID PeopleIphoneNmber],
        @"gasId":self.Model.gasId,
        @"gunNo":self.gunNo
    };
    typeof(self) wSelf = self;
    [NetworkRequest PostGasStation:url Params:params Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                TYWebViewController * vc = [TYWebViewController new];
                vc.title= @"团油";
                vc.url = objc[@"result"];
                vc.hidesBottomBarWhenPushed = YES;
                [wSelf.navigationController pushViewController:vc animated:YES];
            }
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
#pragma mark - 油号选择
- (void)OilnoBtn:(UIButton *)button{
    typeof(self) weakSelf = self;
    //油号
    if (self.gasNoList.count > 0) {
        PopupView *Popup =  [[[NSBundle mainBundle] loadNibNamed:@"PopupView" owner:self options:nil] lastObject];
        Popup.type = PopupTypeOilno;
        Popup.menuItems = self.gasNoList;
        Popup.indexStr = self.oilNo;
        self.Popup = Popup;
        [Popup showMenuInView:XYKEYWINDOW];
        Popup.blockParm = ^(NSDictionary * _Nonnull parm) {
            weakSelf.oilNo = [NSString stringWithFormat:@"%@",parm[@"oilNo"]];
            weakSelf.oilName = parm[@"oilName"];
            NSArray *gunNos = parm[@"gunNos"];
            if (gunNos.count > 0) {
                weakSelf.gunNo = gunNos.firstObject[@"gunNo"];
            }
            
            [button setTitle:parm[@"oilName"] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
            weakSelf.headerView.price.text = parm[@"priceYfq"];
            weakSelf.headerView.priceGun.text = parm[@"priceGun"];
            weakSelf.headerView.priceOfficial.text = parm[@"priceOfficial"];
            [button layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleRight imageTitleSpace:5.0];
            [weakSelf.Popup removeFromSuperview];
            [weakSelf.tableView.mj_header beginRefreshing];
            return;
        };
        Popup.blockDiss = ^{
            [button setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
            [button layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleRight imageTitleSpace:5.0];
            [weakSelf.Popup removeFromSuperview];
            return;
        };
    }
}
//苹果原生地图
- (void)appleMap:(UIButton *)button{
    NSString *ToName =  [NSString stringWithFormat:@"%@%@%@%@",_Model.provinceName,_Model.cityName,_Model.countyName,_Model.gasAddress];
    NSString *locationCoordinate = [UserDefault objectForKey:@"locationCoordinate"];
    NSArray  *locationArray = nil;
    if (locationCoordinate) {
       locationArray =  [locationCoordinate componentsSeparatedByString:@","];
    }
    NSString *clientLng = locationArray ?locationArray[0] :@"121.48";
    NSString *clientLat = locationArray ?locationArray[1] :@"31.22";
    
    CLLocationCoordinate2D desCoordinate = CLLocationCoordinate2DMake([clientLat longLongValue], [clientLng longLongValue]);
    
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    currentLocation.name = @"我的位置";
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:desCoordinate addressDictionary:nil]];
    toLocation.name = ToName;
    
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeTransit,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}

#pragma mark - BUNativeExpressBannerViewDelegate
- (void)nativeExpressBannerAdViewDidLoad:bannerAdView{
    NSLog(@"加载成功");
}
- (void)nativeExpressBannerAdView:(BUNativeExpressBannerView *)bannerAdView didLoadFailWithError:(NSError *_Nullable)error;{
    NSLog(@"加载失败：%@",error);
}
- (void)nativeExpressBannerAdViewRenderSuccess:(BUNativeExpressBannerView *)bannerAdView {
 //在此回调方法中进行广告的展示，可保证播放流畅和展示流畅，用户体验更好。
    [self showBanner];
}
- (void)showBanner {
    [self.view addSubview:self.bannerView];
}
/*
#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
