//
//  TourComboBoxViewController.m
//  TakeTours
//
//  Created by Vae on 2019/1/9.
//

#import "TourComboBoxViewController.h"
#import "TourSearchBoxViewController.h"
#import "Utility.h"
#import "UIToolkit.h"
#import "CocoaUtils.h"
#import "StringUtils.h"
#import "DrawUtils.h"
#import "WebService.h"
#import "Area.h"
#import "Region.h"
#import "SDK.h"
#import "DZNEmptyDataSetDefault.h"
#import "TourBottomViewController.h"
#import "TourSheetViewController.h"
#import "GetTourSearchSourceResponseJsonMapper.h"
#import <libextobjc/EXTScope.h>
#import <YYModel/YYModel.h>
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <PINCache/PINCache.h>
#import <HMSegmentedControl/HMSegmentedControl.h>
#import "Vars.h"

#define ViewHeight CGRectGetHeight([UIScreen mainScreen].bounds)
#define ViewWidth CGRectGetWidth([UIScreen mainScreen].bounds)

static NSInteger const kBottomViewHeight = 50;

@interface TourComboBoxViewController ()<UITableViewDataSource, UITableViewDelegate,UISearchControllerDelegate,UISearchResultsUpdating,UISearchBarDelegate,DZNEmptyDataSetDefault,CAAnimationDelegate,UIGestureRecognizerDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) UISearchController *searchController;
@property(nonatomic, strong) TourSheetViewController *sheetViewController;
@property(nonatomic, strong) TourBottomViewController *bottomViewController;
@property(nonatomic, strong) HMSegmentedControl *segmentedControl;
@property(nonatomic, strong) UIWindow *topWindow;
@property(nonatomic, strong) CALayer *animationlayer;

@property(nonatomic, assign) NSInteger selectIndex;
@property(nonatomic, strong) NSMutableArray *cellDataArray;
@property(nonatomic, strong) NSArray *searchCellDataArray;
@property(nonatomic, strong) NSMutableArray *headerDataArray;
@property(nonatomic, strong) NSMutableArray *historyArray;

@property(nonatomic, strong) NSMutableDictionary *allAreaDictionary;
@property(nonatomic, strong) NSMutableDictionary *allCityDictionary;
@property(nonatomic, strong) NSMutableArray *object_regionlist;
@property(nonatomic, strong) NSMutableArray *defaultAreaDataArray;
@property(nonatomic, strong) NSMutableArray *relatedAreaDataArray;
@property(nonatomic, strong) NSMutableArray *selectedAreaArray;
@property(nonatomic, strong) NSMutableArray *rootAreaTitleArray;
@property(nonatomic, strong) NSMutableArray *relatedRootAreaTitleArray;
@property(nonatomic, strong) NSMutableArray *depatureAreaArray;
@property(nonatomic, strong) NSArray *allAreaArray;
@property(nonatomic, strong) NSArray *indexTitles;
@property(nonatomic, strong) NSArray *sortedArrays;

@property(nonatomic, assign) BOOL hasToursSearchParams;
@property(nonatomic, assign) BOOL isOnlyhasDestinationParam;
@property(nonatomic, assign) BOOL isRelationState;
@property(nonatomic, assign) BOOL geocoding;

@property(nonatomic, assign) CGFloat animationheight;
@property(nonatomic, strong, readwrite) CLPlacemark *currentPlacemark;
@property(nonatomic, copy) void (^didCancelBlock) (void);
@property(nonatomic, copy) id (^placemarkTransformationBlock) (CLPlacemark *placemark);
@property(nonatomic, copy) NSString *(^placemarkFormattingBlock) (CLPlacemark *placemark);
@property(nonatomic, copy) void (^geocodeBlock) (TourComboBoxViewController *viewController);
@property(nonatomic, copy) void (^selectionChangedBlock) (TourComboBoxViewController *viewController, id obj, id obj1);
@end

@implementation TourComboBoxViewController

- (void)viewDidLoad {
	self.selectIndex = 0;
	
	self.title =self.isDestinations ? IMLocalizedString(@"Search Destination") : IMLocalizedString(@"Search Departure");
	
	[super viewDidLoad];
	self.extendedLayoutIncludesOpaqueBars = YES;
	
	self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
	self.tableView.delegate = self;
	self.tableView.dataSource = self;
	self.tableView.emptyDataSetDelegate = self;
	self.tableView.emptyDataSetSource = self;
	[self.view addSubview:self.tableView];
	
	UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
	searchController.searchResultsUpdater = self;
	searchController.dimsBackgroundDuringPresentation = NO;
	searchController.searchBar.delegate = self;
	searchController.delegate = self;
	searchController.hidesNavigationBarDuringPresentation = NO;
	self.definesPresentationContext = YES;
	[searchController.searchBar setShowsCancelButton:YES animated:YES];
	searchController.searchBar.placeholder = self.isDestinations ? IMLocalizedString(@"Search Destination") : IMLocalizedString(@"Search Departure");
	self.searchController = searchController;
	
	if (@available(iOS 11, *)) {
		self.navigationItem.titleView = self.searchController.searchBar;
		self.navigationItem.hidesSearchBarWhenScrolling = false;
	}else{
		self.tableView.tableHeaderView = self.searchController.searchBar;
	}
	
	for(UIView *view in [[[searchController.searchBar subviews] objectAtIndex:0] subviews]){
		if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
			view.alpha = 0.0f;
		}else if([view isKindOfClass:NSClassFromString(@"UISearchBarTextField")] ){
			view.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
		}
	}

	if (self.isDestinations){
		self.topWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, ViewWidth, kBottomViewHeight)];
		TourBottomViewController *viewController = [[TourBottomViewController alloc] init];
		viewController.view.frame = CGRectMake(0, 0, ViewWidth, kBottomViewHeight);
		self.bottomViewController = viewController;
		viewController.bottomView.tapLeftView  = ^{
			if (self.selectedAreaArray.count > 0){
				[self showSheetView];
			}
		};
		viewController.bottomView.completeSelect = ^{
			[self complete];
		};
		self.topWindow.rootViewController = viewController;
		[self.topWindow makeKeyAndVisible];
	}
	//close return GestureRecognizer
	id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
	UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
	[self.view addGestureRecognizer:pan];
	
	UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancleEdit)];
	tapGesture.delegate = self;
	[self.view addGestureRecognizer:tapGesture];
	
	[self loadData];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	if (self.allowsLocation && self.geocodeBlock) {
		static dispatch_once_t onceToken;
		dispatch_once(&onceToken, ^{
			[self didStartGeocode];
		});
	}
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	self.topWindow = nil;
}

-(void)viewDidLayoutSubviews{
	self.tableView.frame = self.view.bounds;
	self.tableView.contentInset = UIEdgeInsetsMake(0, 0,  kBottomViewHeight , 0);
	if (@available(iOS 11, *)) {
		self.animationheight = ViewHeight - kBottomViewHeight -self.view.safeAreaInsets.bottom + 10;
		self.topWindow.frame = CGRectMake(0, ViewHeight - kBottomViewHeight - self.view.safeAreaInsets.bottom, ViewWidth, kBottomViewHeight);
	}else{
		self.animationheight = ViewHeight - kBottomViewHeight -self.view.layoutMargins.bottom + 10;
		self.topWindow.frame = CGRectMake(0, ViewHeight - kBottomViewHeight -self.view.layoutMargins.bottom, ViewWidth, kBottomViewHeight);
	}
}

- (void)loadData{
	GetTourSearchSourceResponseJsonMapper *mapper = [[GetTourSearchSourceResponseJsonMapper alloc] init];
	if (![Vars appDelegate].coreData.tourSearchDataSource){
		return;
	}
	[mapper parseWithJSONObject:[Vars appDelegate].coreData.tourSearchDataSource];
	GetTourSearchSourceResponse *response = mapper.response;
	self.allAreaArray = [NSArray arrayWithArray:response.object_list];
	[self formatDictionary:response.object_list];
	NSArray *areaIdArray = self.isDestinations ? response.destinations :response.departures;
	NSMutableArray *areaArray = [NSMutableArray array];
	for (NSString *areaId in areaIdArray) {
		Area *area = self.allAreaDictionary[areaId];
		if (area) {
			[areaArray addObject:area];
		}
	}
 	[self handleAreaDataWithArray:areaArray];
	
	if (self.hasToursSearchParams) {
		self.isRelationState = YES;
	}else{
		self.currentSearchObjectArray = nil;
	}
	
	if (self.isDestinations){
		[self.selectedAreaArray addObjectsFromArray:self.tourSearchParam.destinations];
	} else {
		if (![StringUtils isEmpty:self.tourSearchParam.dep_ids]) {
			[self.selectedAreaArray addObject:self.tourSearchParam.dep_ids];
		}
		self.depatureAreaArray = [NSMutableArray array];
		for (Region *region in  self.defaultAreaDataArray) {
			for (NSString *cityId in region.childArea){
				[self.depatureAreaArray  addObject:self.allAreaDictionary[cityId]];
			}
		}
	}
	
	if (self.isRelationState) {
		if (self.currentSearchObjectArray.count) {
			[self handleRelationDataWithDicArray:[self.currentSearchObjectArray copy]];
			[self loadHistoryAndSelectedData];
		}else{
			[self fetchTourSearchDataCommit:^{
				[self loadHistoryAndSelectedData];
			}];
		}
	}else{
		[self loadHistoryAndSelectedData];
	}
}

-(void)loadHistoryAndSelectedData{
	[self setHistoryValues:[CocoaUtils objectFromUserDefaultsForKey:UserDefaultsKeyHistoryTourSearchDestinationList]];
	[self.bottomViewController.bottomView changeSelectedCitycount:self.selectedAreaArray.count];
	[self reloadCellData];
}


#pragma mark - private
-(void)buildCellDataSource{
	NSMutableArray *arrays = [NSMutableArray array];
	@weakify(self)
	if (!self.isDestinations && self.selectedAreaArray.count > 0) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"Currently Selected");
			data.selectionStyle = UITableViewCellSelectionStyleNone;
			data.textFont = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, UITableViewCell *cell) {
				cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width * 2);
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData * data = [[TableViewCellData alloc] init];
			data.textFont = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
			[data setTextBlock:^NSString *{
				@strongify(self)
				Area *area = self.allAreaDictionary[self.selectedAreaArray[0]];
				if (area){
					return area.label;
				}else {
					return @"";
				}
			}];
			[data setTextColorBlock:^UIColor *{
				return [UIColor lightGrayColor];
			}];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
		[arrays addObject:array];
	}
	if (!self.isRelationState && self.selectedAreaArray.count == 0 && self.isDestinations) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseHeight = 30;
			data.style = UITableViewCellStyleSubtitle;
			data.detailText = IMLocalizedString(@"Current Location");
			data.selectionStyle = UITableViewCellSelectionStyleNone;
			data.detailTextFont = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
			data.textFont = [UIFont systemFontOfSize:5 weight:UIFontWeightSemibold];
			data.textColor = [UIColor whiteColor];
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, UITableViewCell *cell) {
				cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width * 2);
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData * data = [[TableViewCellData alloc] init];
			data.reuseHeight = 45;
			data.textFont = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
			[data setTextBlock:^NSString *{
				@strongify(self)
				if (self.currentPlacemark) {
					return self.placemarkFormattingBlock(self.currentPlacemark);
				} else {
					return self.geocoding ? IMLocalizedString(@"Geocoding...") : IMLocalizedString(@"Geocode not Available");
				}
			}];
			[data setTextColorBlock:^UIColor *{
				return [UIColor lightGrayColor];
			}];
			data.allowsTextLineWrapping = YES;
			[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.geocoding) {
					UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
					[activityIndicatorView startAnimating];
					return activityIndicatorView;
				} else {
					UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
					[button setAttributedTitle:[DrawUtils attributedStringWithFAKIcon:[FAKIonIcons iosNavigateOutlineIconWithSize:20] fillColor:[UIColor darkGrayColor]] forState:UIControlStateNormal];
					[button sizeToFit];
					[button bk_addEventHandler:^(id sender) {
						[self didStartGeocode];
					} forControlEvents:UIControlEventTouchUpInside];
					return button;
				}
				return nil;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.currentPlacemark && !self.geocoding) {
					id value =  [Destination localityTransformation:[self.allCityDictionary copy] objectForPlacemark:self.currentPlacemark];
					Area *item = self.allAreaDictionary[value];
					if (item) {
						if(![self.selectedAreaArray containsObject:item.label]){
							if (YES){
								CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
								CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
								[self startAnimationWithPosition:CGPointMake(CGRectGetMaxX(rectInSuperview), CGRectGetMaxY(rectInSuperview))];
							}
							self.isRelationState = YES;
							if (!self.isMultipleSelection){
								[self.selectedAreaArray removeAllObjects];
							}
							[self.selectedAreaArray addObject:item.area_id];
							if (!self.isDestinations){
								[self complete];
							} else {
								[self fetchTourSearchDataCommit:^{
									self.searchController.searchBar.text = @"";
									[self.bottomViewController.bottomView changeSelectedCitycount:self.selectedAreaArray.count];
									[self reloadCellData];
								}];
							}
						}
					}
				}
			}];
			[array addObject:data];
		}
		[arrays addObject:array];
	}
	if (!self.isRelationState && self.historyArray.count != 0 && self.selectedAreaArray.count == 0 && self.isDestinations) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseHeight = 30;
			data.selectionStyle = UITableViewCellSelectionStyleNone;
			data.text = IMLocalizedString(@"Recent Search");
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, UITableViewCell *cell) {
				cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width * 2);
			}];
			data.textFont = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
			[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				if (self.historyArray.count == 0){
					return nil;
				}
				UIButton *deleteButton = [[UIButton alloc] init];
				[deleteButton setImage:[UIImage imageNamed:@"deletes"] forState:UIControlStateNormal];
				[deleteButton sizeToFit];
				[deleteButton bk_addEventHandler:^(id  _Nonnull sender) {
					[self.historyArray removeAllObjects];
					[CocoaUtils synchronizeUserDefaultsBySettingWithObject:[[self.selectedAreaArray copy] componentsJoinedByString:@";"] forKey:UserDefaultsKeyHistoryTourSearchDestinationList];
					[self buildHeaderDataSource];
					[self buildCellDataSource];
					
				} forControlEvents:UIControlEventTouchUpInside];
				return deleteButton;
			}];
			[array addObject:data];
		}
		for (NSString *cityName in self.historyArray) {
			Area *area = self.allAreaDictionary[cityName];
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = area.label;
			data.textFont = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				self.isRelationState = YES;
				if(![self.selectedAreaArray containsObject:cityName]){
					if (YES){
						CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
						CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
						[self startAnimationWithPosition:CGPointMake(CGRectGetMaxX(rectInSuperview), CGRectGetMaxY(rectInSuperview))];
					}
					if (!self.isMultipleSelection){
						[self.selectedAreaArray removeAllObjects];
						[self.selectedAreaArray addObject:cityName];
					} else {
						[self.selectedAreaArray addObject:cityName];
					}
					if (!self.isDestinations){
						[self complete];
					} else {
						[self.bottomViewController.bottomView changeSelectedCitycount:self.selectedAreaArray.count];
						[self fetchTourSearchDataCommit:^{
							[self reloadCellData];
						}];
					}
				}
			}];
			[array addObject:data];
		}
		[arrays addObject:array];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.selectionStyle = UITableViewCellSelectionStyleNone;
		if (self.isDestinations){
			data.text = self.isRelationState ?IMLocalizedString(@"Related Destinations") : IMLocalizedString(@"All Destinations");
		} else {
			data.text = self.isRelationState ? IMLocalizedString(@"Related Departure") : IMLocalizedString(@"All Departures");
		}
		[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, UITableViewCell *cell) {
			cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width * 2);
		}];
		data.textFont = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
		[array addObject:data];
		[arrays addObject:array];
	}
	if (self.defaultAreaDataArray.count != 0 || self.relatedAreaDataArray.count !=0 ) {
		if ((self.isRelationState && self.relatedAreaDataArray.count == 0)|| (!self.isRelationState && self.defaultAreaDataArray.count == 0)){
		} else {
			NSMutableArray *array = [NSMutableArray array];
			[self makeIndexedCollation];
			for (int i = 0; i<self.indexTitles.count; i++){
				TableViewCellData *data = [[TableViewCellData alloc] init];
				data.text = [NSString stringWithFormat:@" %@",self.indexTitles[i]];
				data.style = UITableViewCellStyleValue1;
				data.reuseHeight = 30;
				data.selectionStyle = UITableViewCellSelectionStyleNone;
				data.textFont = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
				[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, UITableViewCell *cell) {
					cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width * 2);
				}];
				[array addObject:data];
				for (Area *tempArea in self.sortedArrays[i]) {
					TableViewCellData *data = [[TableViewCellData alloc] init];
					data.text = tempArea.label;
					data.selectionStyle = UITableViewCellSelectionStyleNone;
					data.textFont = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
					data.allowsTextLineWrapping = YES;
					[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, UITableViewCell *cell) {
						cell.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
					}];
					[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
						@strongify(self)
						self.isRelationState = YES;
						[self.searchController.searchBar resignFirstResponder];
						if(![self.selectedAreaArray containsObject:tempArea.area_id]){
							if (YES){
								CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
								CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
								[self startAnimationWithPosition:CGPointMake(CGRectGetMaxX(rectInSuperview), CGRectGetMaxY(rectInSuperview))];
							}
							if (!self.isMultipleSelection){
								[self.selectedAreaArray removeAllObjects];
							}
							[self.selectedAreaArray addObject:tempArea.area_id];

							if (!self.isDestinations){
								[self complete];
							} else {
								[self.bottomViewController.bottomView changeSelectedCitycount:self.selectedAreaArray.count];
								[self fetchTourSearchDataCommit:^{
									[self reloadCellData];
								}];
							}
						}
						
					}];
					[array addObject:data];
				}
			}
			[arrays addObject:array];
		}
	}
	self.cellDataArray = [NSMutableArray arrayWithArray:arrays];
	[self.tableView reloadData];
}

- (void)buildHeaderDataSource {
	self.headerDataArray = nil;
	NSMutableArray *array = [NSMutableArray array];
	NSInteger count =  self.historyArray.count  ? 3 : 2;
	if (self.isRelationState){
		if (self.isDestinations){
			count = 1;
		} else {
			if (self.selectedAreaArray.count){
				count = 2;
			} else {
				count = 1;
			}
		}
	}
	if (!self.isDestinations) {
		if (self.selectedAreaArray.count ) {
			count = 2;
		}else{
			count = 1;
		}
	}
	for (int section = 0;section < count; section++) {
		TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
		data.reuseHeight = 0;
		[array addObject:data];
	}
	if (YES) {
		TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
		data.reuseHeight = 44;
		[array addObject:data];
	}
	self.headerDataArray = [NSArray arrayWithArray:array];
}

-(void)showSheetView{
	if (self.sheetViewController) {
		[self.sheetViewController dismissViewControllerAnimated:YES completion:nil];
		self.sheetViewController = nil;
		return;
	}
	
	self.sheetViewController = [[TourSheetViewController alloc] init];
	self.sheetViewController.isDestinations = self.isDestinations;
	self.sheetViewController.cityArray = self.selectedAreaArray;
	self.sheetViewController.cityDictionary = [self.allAreaDictionary copy];
	@weakify(self)
	self.sheetViewController.updateSelectNumber = ^() {
		@strongify(self)
		[self.bottomViewController.bottomView changeSelectedCitycount:self.selectedAreaArray.count];
		if (self.selectedAreaArray.count == 0){
			self.isRelationState = NO;
			[self.sheetViewController dismissViewControllerAnimated:YES completion:nil];
			if (self.hasToursSearchParams) {
				self.isRelationState = YES;
			}
			if (self.isOnlyhasDestinationParam) {
				self.tourSearchParam.destinations = nil;
				self.isRelationState = NO;
				[self fetchTourSearchDataCommit:^{
					[self reloadCellData];
				}];
				return ;
			}
		}
		
		if (self.isRelationState) {
			[self fetchTourSearchDataCommit:^{
				[self reloadCellData];
			}];
		} else {
			[self reloadCellData];
		}
	};
	[self presentViewController:self.sheetViewController animated:YES completion:nil];
}

- (void)didStopGeocode {
	self.geocoding = NO;
	if (!self.isRelationState && self.isDestinations && self.cellDataArray) {
		[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
	}
}

- (void)didStartGeocode {
	self.geocoding = YES;
	if (!self.isRelationState) {
		if(self.cellDataArray.count > 1 && self.isDestinations){
			[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
		}
		
	}
	self.geocodeBlock(self);
}

- (void)makeIndexedCollation {
	NSMutableArray *array = [NSMutableArray array];
	Region *tempRegion = self.isRelationState ? self.relatedAreaDataArray[self.selectIndex] : self.defaultAreaDataArray[self.selectIndex];
	for (NSString *cityId in tempRegion.childArea){
		[array addObject:self.allAreaDictionary[cityId]];
	}
	IMLocalizedIndexedCollation *provider = [[IMLocalizedIndexedCollation alloc] initWithObjects:array sortedUsingSelector:@selector(label)];
	self.indexTitles = provider.sectionIndexTitles;
	self.sortedArrays = provider.sectionSortedArrays;
}

- (void)complete{
	[CocoaUtils synchronizeUserDefaultsBySettingWithObject:[[self.selectedAreaArray copy] componentsJoinedByString:@";"] forKey:UserDefaultsKeyHistoryTourSearchDestinationList];
	if (self.sheetViewController){
		[self dismissViewControllerAnimated:YES completion:nil];
	}
	if (self.selectionChangedBlock) {
		self.selectionChangedBlock(self,self.selectedAreaArray , [self.allAreaDictionary copy]);
	}
}

//将传入的结点数据源处理,返回两个字典
- (void)formatDictionary:(NSArray *)object_array{
	for (Area *area in object_array) {
		if (area.aliases.count != 0){
			for (Aliase *alies in area.aliases) {
				Area *aliesarea = [[Area alloc]init];
				aliesarea.area_id = alies.aliase_id;
				aliesarea.label = alies.label;
				[self.allAreaDictionary setObject:aliesarea forKey:aliesarea.area_id];
				[self.allCityDictionary setObject:aliesarea.label forKey:aliesarea.area_id];
			}
		}
		[self.allAreaDictionary setObject:area forKey:area.area_id];
		[self.allCityDictionary setObject:area.label forKey:area.area_id];
	}
}

//处理相关联的area结点的数据
- (void)handleRelationDataWithDicArray:(NSArray *)json_array{
	if (json_array.count > 0) {
		NSDictionary *jsondic = json_array.firstObject;
		NSArray *regionsarray = [jsondic[@"regions"] allKeys];
		NSArray *destinationsarray = [jsondic[@"destinations"] allKeys];
		NSArray *attractionsarray = [jsondic[@"attractions"] allKeys];
		NSArray *departurearray = [jsondic[@"departure"] allKeys];
		if (self.currentSearchObjectArray.count != 0){
			[self.currentSearchObjectArray removeAllObjects];
		}
		if (self.isDestinations){
			for (NSString *key in destinationsarray) {
				if (self.allAreaDictionary[key]){
					[self.currentSearchObjectArray addObject:self.allAreaDictionary[key]];
				}
			}
			for (NSString *key in attractionsarray) {
				if (self.allAreaDictionary[key]){
					[self.currentSearchObjectArray addObject:self.allAreaDictionary[key]];
				}
			}
			for (NSString *key in regionsarray) {
				if (self.allAreaDictionary[key]){
					[self.currentSearchObjectArray addObject:self.allAreaDictionary[key]];
				}
			}
		} else {
			for (NSString *key in departurearray) {
				if (self.allAreaDictionary[key]){
					[self.currentSearchObjectArray addObject:self.allAreaDictionary[key]];
				}
			}
		}
		for (NSString *areaId in self.selectedAreaArray) {
			for (NSInteger i = self.currentSearchObjectArray.count - 1; i >= 0 ; i--) {
				Area *area = self.currentSearchObjectArray[i];
				if ([areaId isEqualToString:area.area_id]) {
					[self.currentSearchObjectArray removeObjectAtIndex:i];
				}
			}
		}
		[self handleAreaDataWithArray:[self.currentSearchObjectArray copy]];
		self.selectIndex = 0;
	}
}

//处理area结点数据
- (void)handleAreaDataWithArray:(NSArray *)object_array{
	NSMutableArray *regionTempArray = [NSMutableArray array];
	for (Area *area in self.object_regionlist.count ? self.object_regionlist :self.allAreaArray) {
		//area通过此条件来判断根结点
		if(area.tier < 14 && area.type == 3 && ([area.parent_id isEqualToString:@"0"])){
			NSMutableArray *childArray = [NSMutableArray array];
			//从传入的area里面寻找子节点
			for (Area *childarea in object_array) {
				if ([self isSubNodeWith:area.area_id and:childarea.area_id]) {
					[childArray addObject:childarea];
				}
			}
			NSArray *tempChildArray = [childArray sortedArrayUsingComparator:^NSComparisonResult (Area *obj1, Area *obj2) {
				return [obj1.label compare:obj2.label];
			}];
			NSMutableArray *childIdArray = [NSMutableArray array];
			for (Area *templeArea in tempChildArray) {
				[childIdArray addObject:templeArea.area_id];
			}
			Region *region = [[Region alloc] init];
			region.area_id = area.area_id;
			region.tier = area.tier;
			region.childArea = [childIdArray copy];
			region.label = area.label;
			if (childArray.count > 0){
				[regionTempArray addObject:region];
			}
			
		}
	}
	//国家结点排序
	NSArray *contryTempArray = [regionTempArray sortedArrayUsingComparator:^NSComparisonResult (Region *obj1, Region *obj2) {
		if (obj1.tier > obj2.tier){
			return obj1.tier > obj2.tier;
		} else if ((obj1.tier == obj2.tier )&& (obj1.area_id.integerValue > obj2.area_id.integerValue)){
			return (obj1.area_id.integerValue > obj2.area_id.integerValue);
		}
		return obj1.tier > obj2.tier;
	}];
	[self.relatedAreaDataArray removeAllObjects];
	[self.rootAreaArray removeAllObjects];
	for (Region *region in contryTempArray) {
		[(self.isRelationState ? self.relatedAreaDataArray : self.defaultAreaDataArray) addObject:region];
		[(self.isRelationState ? self.rootAreaArray : self.rootAreaTitleArray) addObject:region.label];
	}
}

-(BOOL)isSubNodeWith:(NSString *)rootAreaId and:(NSString *)otherAreaId{
	Area *area = [self.allAreaDictionary objectForKey:otherAreaId];
	while (YES) {
		if ([area.parent_id isEqualToString:@"0"]) {
			return NO;
		}else if([area.parent_id isEqualToString:rootAreaId]){
			return YES;
		}else{
			area = [self.allAreaDictionary objectForKey:area.parent_id];
			if (!area) {
				return NO;
			}
		}
	}
	return NO;
}


-(void)reloadCellData{
	self.segmentedControl.selectedSegmentIndex = 0;
	self.segmentedControl.sectionTitles = self.isRelationState ? self.rootAreaArray : self.rootAreaTitleArray;
	[self buildHeaderDataSource];
	[self buildCellDataSource];
}

- (void)updateTableViewCellDataArrayBySearchString:(NSString *)searchString {
	if ([StringUtils isBlank:searchString]) {
		self.searchCellDataArray = @[];
		return;
	}
	if (self.currentSearchObjectArray.count == 0){
		if (self.isDestinations) {
			self.currentSearchObjectArray = [NSMutableArray arrayWithArray:self.allAreaArray];
		}else{
			[self.currentSearchObjectArray addObjectsFromArray:	self.depatureAreaArray];
		}
	}
	NSMutableArray *containAliasarray = [NSMutableArray array];
	if ([self.currentSearchObjectArray.firstObject isKindOfClass:[NSDictionary class]]) {
		[self handleRelationDataWithDicArray:self.currentSearchObjectArray];
	}
	
	for (Area *area in [NSMutableArray arrayWithArray:[self.currentSearchObjectArray copy]]) {
		if (area.aliases.count != 0){
			for (Aliase *alies in area.aliases) {
				Area *aliesarea = [[Area alloc]init];
				aliesarea.area_id = alies.aliase_id;
				aliesarea.label = alies.label;
				[containAliasarray addObject:aliesarea];
			}
		}
		[containAliasarray addObject:area];
		
	}
	NSMutableArray *searchItems = [NSMutableArray arrayWithArray:[containAliasarray copy]];
	
	if (searchItems.count < 500) {
		[searchItems filterUsingPredicate:[NSPredicate predicateWithFormat:@"label contains[cd] %@", searchString]];
	} else {
		[searchItems filterUsingPredicate:[NSPredicate predicateWithFormat:@"label contains[cd] %@", searchString]];
	}
	[searchItems sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"label" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]]];
	NSRegularExpression *highlightedRegex = [NSRegularExpression regularExpressionWithPattern:searchString options:NSRegularExpressionCaseInsensitive error:NULL];
	NSArray* reversedArray = [[searchItems reverseObjectEnumerator] allObjects];
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	for (Area *item in reversedArray) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		if (highlightedRegex) {
			NSArray *array = [highlightedRegex matchesInString:item.label options:0 range:NSMakeRange(0, item.label.length)];
			NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] im_initWithString:item.label];
			for (NSTextCheckingResult *result in array) {
				[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:result.range];
			}
			data.attributedText = [[NSAttributedString alloc] initWithAttributedString:attributedString];
		} else {
			data.text = item.label;
		}
		data.allowsTextLineWrapping = YES;
		data.accessoryType = UITableViewCellAccessoryNone;
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			if([self.selectedAreaArray containsObject:item.area_id]){
				[self.searchController.searchBar resignFirstResponder];
			} else {
				[self.searchController.searchBar resignFirstResponder];
				if (YES){
					CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
					CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
					[self startAnimationWithPosition:CGPointMake(CGRectGetMaxX(rectInSuperview), CGRectGetMidY(rectInSuperview))];
				}
				if (!self.isMultipleSelection){
					[self.selectedAreaArray removeAllObjects];
				}
				[self.selectedAreaArray addObject:item.area_id];
				if (!self.isDestinations){
					[self complete];
				} else {
					[self buildHeaderDataSource];
					[self fetchTourSearchDataCommit:^{
						self.searchController.searchBar.text = @"";
						self.segmentedControl.selectedSegmentIndex = 0;
						self.segmentedControl.sectionTitles = self.isRelationState ? self.rootAreaArray : self.rootAreaTitleArray;
						[self.bottomViewController.bottomView changeSelectedCitycount:self.selectedAreaArray.count];
					}];
				}
			}
			
		}];
		[array addObject:data];
	}
	self.searchCellDataArray = [NSArray arrayWithArray:array];
}

#pragma mark - Public

- (void)updatePlacemark:(CLPlacemark *)placemark {
	self.currentPlacemark = placemark;
	[self didStopGeocode];
}

#pragma mark - Network
- (void)fetchTourSearchDataCommit:(void (^)(void))commit {
	NSString *urlString = [[Vars javaSearchEndpoint] stringByAppendingString:@"/ajax.do"];
	
	NSMutableDictionary *requestDic = [NSMutableDictionary dictionaryWithDictionary:[self.tourSearchParam toParameters]];
	NSString *durstr = requestDic[@"duration"];
	if ([durstr containsString:@"All"] || [StringUtils isEmpty:durstr]) {
		requestDic[@"duration"] = @"";
	}
	if (self.isDestinations){
		requestDic[@"destinations"] = [self.selectedAreaArray componentsJoinedByString:@";"];
	} else {
		requestDic[@"dep_ids"] = [self.selectedAreaArray componentsJoinedByString:@";"];
	}
	[Utility getJSONFromRequestWithMethod:@"GET" url:urlString parameters:requestDic beforeSend:^{
		[CocoaUtils showBusyIndicator:self.view];
	} success:^(id jsonObject) {
		//NSLog(@"%@", jsonObject);
		NSArray *jsonArray = jsonObject;
		[self handleRelationDataWithDicArray:jsonArray];
		
	} complete:^{
		if (commit) {
			commit();
		}
		[CocoaUtils hideBusyIndicator:self.view];
	}];
}


#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
	if (self.tableView.contentOffset.y > 0) {
		[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
	}
	if (self.selectedAreaArray.count > 0 || ![StringUtils isEmpty:searchController.searchBar.text]) {
		self.isRelationState = YES;
	}else if (!self.currentSearchObjectArray.count) {
		self.isRelationState = NO;
	}
	if (self.hasToursSearchParams) {
		self.isRelationState = YES;
	}else if([StringUtils isEmpty:searchController.searchBar.text] && self.selectedAreaArray.count == 0) {
		self.isRelationState = NO;
	}
	
	if (self.isRelationState){
		[self updateTableViewCellDataArrayBySearchString:searchController.searchBar.text];
		self.cellDataArray = [self getDataSourceForRowWithTableView:self.tableView];
		[self buildHeaderDataSource];
		if (![StringUtils isEmpty:searchController.searchBar.text]){
			[self.tableView reloadData];
		} else {
			[self buildCellDataSource];
		}
	} else {
		[self reloadCellData];
	}
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
	self.navigationItem.titleView = nil;
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return self.cellDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.cellDataArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArray[indexPath.section][indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	TableViewSectionHeaderFooterData *data = self.headerDataArray[section];
	return [UIToolkit tableView:tableView inSection:section headerTitleWithData:data];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	TableViewSectionHeaderFooterData *data = self.headerDataArray[section];
	return [UIToolkit tableView:tableView inSection:section headerHeightWithData:data];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
	if (self.isDestinations) {
		if (section == self.headerDataArray.count -1 || section == self.headerDataArray.count - 2) {
			return 0;
		}
	}else{
		if (self.selectedAreaArray.count > 0 && section == 0){
			return 10;
		}else{
			return 0;
		}
	}
	return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
	TableViewSectionHeaderFooterData *data = self.headerDataArray[section];
	if (data.reuseHeight == 44) {
		return self.segmentedControl;
	}
	return nil;
}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
	if (!self.isRelationState) {
		NSMutableArray *array = [NSMutableArray array];
		[array addObject:UITableViewIndexSearch];
		if (self.indexTitles) {
			[array addObjectsFromArray:self.indexTitles];
		}
		return [NSArray arrayWithArray:array];
	}
	return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
	NSInteger row = 0;
	NSInteger section = 0;
	if (self.isDestinations) {
		if (self.historyArray.count) {
			section = 3;
		}else{
			section = 2;
		}
	}else{
		if (self.selectedAreaArray.count) {
			section = 2;
		}else{
			section = 1;
		}
	}
	for (int i = 0 ; i < index - 1; i++) {
		row += [self.sortedArrays[i] count];
	}
	row += (index - 1);
	if (index == 0) {
		[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
	} else {
		[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
	}
	
	if (@available(iOS 10, *)) {
		UIImpactFeedbackGenerator *impactFeedBack = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
		[impactFeedBack prepare];
		[impactFeedBack impactOccurred];
	}
	return NSNotFound;
}

#pragma mark - animation

- (void)startAnimationWithPosition:(CGPoint)position{
	if (self.isDestinations) {
		UIBezierPath *path = [UIBezierPath bezierPath];
		[path moveToPoint:position];
		[path addQuadCurveToPoint:CGPointMake(25 , self.animationheight) controlPoint:CGPointMake(ViewWidth - 100, position.y)];
		CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
		animation.path = path.CGPath;
		animation.rotationMode = kCAAnimationRotateAuto;
		CABasicAnimation *expandAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
		expandAnimation.duration = 0.2f;
		expandAnimation.fromValue = [NSNumber numberWithFloat:1];
		expandAnimation.toValue = [NSNumber numberWithFloat:1.2f];
		expandAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
		
		CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
		narrowAnimation.beginTime = 0.2;
		narrowAnimation.fromValue = [NSNumber numberWithFloat:1.5f];
		narrowAnimation.duration = 0.2f;
		narrowAnimation.toValue = [NSNumber numberWithFloat:0.5f];
		
		narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
		
		CAAnimationGroup *groups = [CAAnimationGroup animation];
		groups.animations = @[animation,expandAnimation,narrowAnimation];
		groups.duration = 0.4f;
		groups.removedOnCompletion = NO;
		groups.fillMode = kCAFillModeForwards;
		groups.delegate = self;
		[self.animationlayer addAnimation:groups forKey:@"group"];
	}
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
	if (anim == [self.animationlayer animationForKey:@"group"]) {
		[self.animationlayer removeFromSuperlayer];
		self.animationlayer = nil;
		CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
		shakeAnimation.beginTime = 0;
		shakeAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
		shakeAnimation.duration = 0.2f;
		shakeAnimation.toValue = [NSNumber numberWithFloat:1.5f];
		shakeAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
		[ self.bottomViewController.bottomView.countLabel.layer addAnimation:shakeAnimation forKey:nil];
	}
}

- (void)cancleEdit{
	[self.searchController.searchBar resignFirstResponder];
}

#pragma mark - tap delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
	if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"] ||[NSStringFromClass([touch.view class]) isEqualToString:@"HMScrollView"]) {
		[self cancleEdit];
		return NO;
	}
	return  YES;
}

#pragma mark - <DZNEmptyDataSetSource>
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
	return [DrawUtils imageWithFAKIcon:[FAKFontAwesome suitcaseIconWithSize:48] fillColor:[UIColor darkGrayColor]];
}

#pragma mark - Protetry

- (NSMutableArray *)currentSearchObjectArray {
	if (!_currentSearchObjectArray){
		_currentSearchObjectArray = [NSMutableArray array];
	}
	return _currentSearchObjectArray;
}

- (NSMutableDictionary *)allAreaDictionary {
	if (!_allAreaDictionary){
		_allAreaDictionary = [NSMutableDictionary dictionary];
	}
	return _allAreaDictionary;
}

- (NSMutableArray *)object_regionlist {
	if (!_object_regionlist){
		_object_regionlist = [NSMutableArray array];
	}
	return _object_regionlist;
}


- (NSMutableDictionary *)allCityDictionary {
	if (!_allCityDictionary){
		_allCityDictionary = [NSMutableDictionary dictionary];
	}
	return _allCityDictionary;
}

- (NSMutableArray *)rootAreaArray {
	if (!_relatedRootAreaTitleArray) {
		_relatedRootAreaTitleArray = [NSMutableArray array];
	}
	return _relatedRootAreaTitleArray;
}

-(NSMutableArray *)rootAreaTitleArray{
	if (!_rootAreaTitleArray) {
		_rootAreaTitleArray = [NSMutableArray array];
	}
	return  _rootAreaTitleArray;
}

- (NSMutableArray *)relatedAreaDataArray{
	if (!_relatedAreaDataArray) {
		_relatedAreaDataArray = [NSMutableArray array];
	}
	return _relatedAreaDataArray;
}

-(NSMutableArray *)defaultAreaDataArray{
	if (!_defaultAreaDataArray) {
		_defaultAreaDataArray = [NSMutableArray array];
	}
	return  _defaultAreaDataArray;
}

-(NSMutableArray *)selectedAreaArray{
	if (!_selectedAreaArray) {
		_selectedAreaArray = [NSMutableArray array];
	}
	return _selectedAreaArray;
}

- (NSMutableArray *)historyArray{
	if (!_historyArray){
		_historyArray = [NSMutableArray array];
	}
	return _historyArray;
}

-(BOOL)hasToursSearchParams{
	NSMutableDictionary *requestDic = [NSMutableDictionary dictionaryWithDictionary:[self.tourSearchParam toParameters]];
	return requestDic.allValues.count > 1;
}

-(BOOL)isOnlyhasDestinationParam{
	NSMutableDictionary *requestDic = [NSMutableDictionary dictionaryWithDictionary:[self.tourSearchParam toParameters]];
	if (requestDic.allValues.count == 2 && self.tourSearchParam.destinations) {
		return YES;
	}
	return NO;
}

- (CLPlacemark *)currentPlacemark {
	return [[PINCache sharedCache] objectForKey:[NSString stringWithFormat:@"%@-%@", NSStringFromClass(self.class), NSStringFromSelector(@selector(currentPlacemark))]];
}

- (void)setCurrentPlacemark:(CLPlacemark *)currentPlacemark {
	if (currentPlacemark) {
		[[PINCache sharedCache] setObject:currentPlacemark forKey:[NSString stringWithFormat:@"%@-%@", NSStringFromClass(self.class), NSStringFromSelector(@selector(currentPlacemark))]];
	}
}

- (void)setHistoryValues:(NSString *)values {
	if (![StringUtils isEmpty:values]){
		for (NSString *areaid in [values componentsSeparatedByString:@";"]) {
			[self.historyArray addObject:areaid];
		}
	}
}

- (HMSegmentedControl *)segmentedControl{
	if (!_segmentedControl) {
		_segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:self.rootAreaTitleArray];
		_segmentedControl.frame = CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 44);
		_segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
		_segmentedControl.selectionIndicatorHeight = 3;
		_segmentedControl.selectionIndicatorColor = [Vars defaultTintColor];
		_segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
		_segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
		_segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 12, 0, 12);
		_segmentedControl.selectionIndicatorEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 30);
		_segmentedControl.backgroundColor = [UIColor colorWithRed:247/255.0f green:247/255.0f blue:247/255.0f alpha:1.0f];
		@weakify(self)
		[_segmentedControl setIndexChangeBlock:^(NSInteger index) {
			@strongify(self)
			self.selectIndex = index;
			[self buildCellDataSource];
		}];
		[_segmentedControl setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
			NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] init];
			[attribute appendAttributedString:[[NSAttributedString alloc] im_initWithString:title attributes:@{NSForegroundColorAttributeName : selected ? [Vars defaultTintColor] : [UIColor blackColor], NSFontAttributeName :selected ? [UIFont boldSystemFontOfSize:14] : [UIFont systemFontOfSize:14]}]];
			return [[NSAttributedString alloc] initWithAttributedString:attribute];
		}];
	}
	return _segmentedControl;
}

- (CALayer *)animationlayer{
	if(!_animationlayer){
		_animationlayer = [CALayer layer];
		_animationlayer.contents =  (__bridge id)[DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome circleIconWithSize:20] fillColor:[UIColor orangeColor]].CGImage;
		_animationlayer.contentsGravity = kCAGravityResizeAspectFill;
		_animationlayer.bounds = CGRectMake(0, 0, 20, 20);
		[_animationlayer setCornerRadius:CGRectGetHeight([_animationlayer bounds])/2];
		_animationlayer.masksToBounds = YES;
		_animationlayer.position = CGPointMake(0, 0);
		[self.view.layer addSublayer:_animationlayer];
	}
	return _animationlayer;
}


- (NSArray *)getDataSourceForRowWithTableView:(UITableView *)tableView {
	if (self.isRelationState) {
		return @[self.searchCellDataArray];
	} else {
		return @[];
	}
}

@end
