//
// TourSeachBoxViewController.m
// IvyMedia
//
// Created by haibara on 8/26/14.
//
//

#import "TourSearchBoxViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "CalendarViewController.h"
#import "DrawUtils.h"
#import "NavigationItemSheet.h"
#import "MultipleSelectionView.h"
#import "AutoCompleteViewController.h"
#import "ComboBoxViewController.h"
#import "TourComboBoxViewController.h"
#import "TourSearchBoxCell.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/A2DynamicDelegate.h>
#import <BlocksKit/NSObject+A2DynamicDelegate.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "AppTracker.h"
#import "Destination.h"
#import "TourSearchListViewController.h"
#import "Vars.h"

@interface TourSearchBoxParam () <NSCopying>
@property (nonatomic, assign) BOOL hideComingSoonProduct;
@end

@implementation TourSearchBoxParam

- (instancetype)init {
	self = [super init];
	if (self) {
		self.hideComingSoonProduct = YES;
	}
	return self;
}

- (BOOL)isEqual:(id)object {
	if (self == object) {
		return YES;
	}
	if (![object isKindOfClass:self.class]) {
		return NO;
	}
    return [[BeanUtils describe:self] isEqualToDictionary:[BeanUtils describe:object]];
}

- (id)copyWithZone:(NSZone *)zone {
	return [BeanUtils copyWithZone:zone origin:self];
}

#pragma mark - Public

- (NSDictionary *)toParameters {
	NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[CocoaUtils nonEmptyDictionary:[BeanUtils describeAccessibleSimple:self]]];
	if (dict[@"keywords"] && [Vars is_cn_website]) {
		dict[@"keywords"] = [dict[@"keywords"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
	}
	if (self.destinations.count > 0) {
		dict[@"destinations"] = [self.destinations componentsJoinedByString:@";"];
	}
	return [NSDictionary dictionaryWithDictionary:dict];
}

@end

@interface TourSearchBoxViewController ()<UIGestureRecognizerDelegate,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) TourSearchBoxParam *tourSearchParam;
@property (nonatomic, strong) NSDictionary *tourSearchData;
@property (nonatomic, strong) NSDictionary *allAreaSearchData;
@property (nonatomic, copy) TourSearchBoxParam *tmpTourSearchParam;
@property (nonatomic, strong) NSMutableArray *origionDataDurations;
@property (nonatomic, strong) NSDictionary *tmpTourSearchData;
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong, readonly) NSString *destinationsText;
@property (nonatomic, strong, readonly) NSString *departureText;
@property (nonatomic, strong, readonly) NSString *durationText;
@property (nonatomic, strong, readonly) NSString *startDatesText;
@property (nonatomic, strong, readonly) NSString *keywordsText;
@property (nonatomic, strong, readonly) NSString *totalText;
@property (nonatomic, strong) MultipleSelectionView *selectDurationView;
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) NSMutableArray *tmpDataDurations;
@property (nonatomic, strong) NSArray *cellDataArray;

@end

@implementation TourSearchBoxViewController

- (instancetype)init {
	self = [super init];
	if (self) {
		self.title = IMLocalizedString(@"Find Tours & Vacations");
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	[[AppTracker sharedInstance] sendView:[self class]];
	[[Vars appDelegate] applyDefaultConfigurationForViewController:self];

	self.tourSearchData = [NSDictionary dictionary];
	self.tmpTourSearchData = [NSDictionary dictionary];

	self.tourSearchParam = [[TourSearchBoxParam alloc] init];
	self.tmpTourSearchParam = [[TourSearchBoxParam alloc] init];
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TourSearchBoxCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([TourSearchBoxCell class])];

	if (YES) {
		UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight] + 15 * 2)];
		UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
		button.tag = NSStringFromClass([UIButton class]).hash;
		button.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]);
		button.backgroundColor = [Vars defaultTintColor];
		button.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
		[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[button setTitle:IMLocalizedString(@"Show Tours") forState:UIControlStateNormal];
		[button addTarget:self action:@selector(showTours) forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:button];
		[footerView addSubview:button];
		self.tableView.tableFooterView = footerView;
	}
	[self buildCellDataSource];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	[[Vars appDelegate] getSearchDataSource:@"Tour"];
}

#pragma mark - Network

- (void)fetchTourSearchData:(UIViewController *)viewController commit:(void (^)(void))commit {
	if ([self isTourSearchBoxEmptyByParam:self.tmpTourSearchParam]) {
		if (commit) {
			commit();
		}
		return;
	}
	NSString *urlString = [[Vars javaSearchEndpoint] stringByAppendingString:@"/ajax.do"];

	NSMutableDictionary *requestDict = [NSMutableDictionary dictionaryWithDictionary:[self.tmpTourSearchParam toParameters]];
	NSString *durstr = requestDict[@"duration"];
	if ([durstr containsString:@"All"] || [StringUtils isEmpty:durstr]) {
		requestDict[@"duration"] = @"";
	}

	[Utility getJSONFromRequestWithMethod:@"GET" url:urlString parameters:requestDict beforeSend:^{
		if ([viewController isKindOfClass:[TourComboBoxViewController class]] || [viewController isKindOfClass:[AutoCompleteViewController class]]) {
			viewController.navigationItem.leftBarButtonItem.enabled = NO;
			viewController.navigationItem.rightBarButtonItem.enabled = NO;
		}
		[CocoaUtils showBusyIndicator:viewController.view];
	} success:^(id jsonObject) {
		// NSLog(@"%@", jsonObject);
		NSArray *jsonArray = jsonObject;
		self.origionDataDurations = [NSMutableArray arrayWithArray:jsonArray];
		if (jsonArray.count > 0) {
			self.tmpTourSearchData = jsonArray.firstObject;
		}
		if (commit) {
			commit();
		}
	} complete:^{
		if ([viewController isKindOfClass:[AutoCompleteViewController class]]) {
			viewController.navigationItem.leftBarButtonItem.enabled = YES;
			viewController.navigationItem.rightBarButtonItem.enabled = YES;
		}
		[CocoaUtils hideBusyIndicator:viewController.view];
	}];
}

#pragma mark - Segue

- (void)performSegueForDestinationOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	TourComboBoxViewController *viewController = [[TourComboBoxViewController alloc] init];
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.isDestinations = YES;
	viewController.allowsLocation = YES;
	viewController.isMultipleSelection = YES;
	viewController.navigationItem.leftBarButtonItem = nil;
	viewController.navigationItem.hidesBackButton = YES;
	if (self.origionDataDurations.count != 0){
		viewController.currentSearchObjectArray = [NSMutableArray arrayWithArray:[self.origionDataDurations copy]];
	}
	viewController.tourSearchParam = self.tourSearchParam;
	[viewController setSelectionChangedBlock:^(TourComboBoxViewController *viewController, NSArray *items, NSDictionary *allAreaDic) {
		self.tmpTourSearchData = self.tourSearchData;
		self.tmpTourSearchParam = self.tourSearchParam;
		self.origionDataDurations = viewController.currentSearchObjectArray;
		if (!self.allAreaSearchData){
			self.allAreaSearchData = allAreaDic;
		}
		self.tmpTourSearchParam.destinations = items;
		[self fetchTourSearchData:viewController commit:^{
			if (![self.tourSearchParam isEqual:self.tmpTourSearchParam]) {
				self.tourSearchParam = self.tmpTourSearchParam;
				self.tourSearchData = self.tmpTourSearchData;
				[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
				[self reloadTourSearchData];
			}
			[self.navigationController popViewControllerAnimated:YES];
			
		}];
	}];
	[viewController setGeocodeBlock:^(TourComboBoxViewController *viewController) {
		[Utility requestLocationWithCompletion:^(BOOL granted, CLLocation *location, NSError *error) {
			if (!granted || !location) {
				[viewController updatePlacemark:nil];
			} else {
				[Utility reverseGeocodeLocation:location completionHandler:^(CLPlacemark *placemark, NSError *error) {
					[viewController updatePlacemark:placemark];
				}];
			}
		}];
	}];
	[viewController setPlacemarkFormattingBlock:^NSString *(CLPlacemark *placemark) {
		return placemark.locality;
	}];
	[viewController setPlacemarkTransformationBlock:^id (CLPlacemark *placemark) {
		return [Destination localityTransformation:[self getTourSearchDestinationsByParam:self.tourSearchParam fromData:self.tourSearchData] objectForPlacemark:placemark];
	}];
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForDepartureOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	TourComboBoxViewController *viewController = [[TourComboBoxViewController alloc] init];
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.isDestinations = NO;
	viewController.allowsLocation = YES;
	viewController.isMultipleSelection = NO;
	viewController.navigationItem.leftBarButtonItem = nil;
	viewController.navigationItem.hidesBackButton = YES;
	if (self.origionDataDurations.count != 0){
		viewController.currentSearchObjectArray = [NSMutableArray arrayWithArray:[self.origionDataDurations copy]];
	}
	viewController.tourSearchParam = self.tourSearchParam;
	[viewController setSelectionChangedBlock:^(TourComboBoxViewController *viewController, NSArray *items, NSDictionary *allAreaDic) {
		self.tmpTourSearchData = self.tourSearchData;
		if (!self.allAreaSearchData){
			self.allAreaSearchData = allAreaDic;
		}
		self.tmpTourSearchParam = self.tourSearchParam;
		if (items.count == 0){
			return ;
		}
		self.tmpTourSearchParam.dep_ids = items[0];
		self.origionDataDurations = viewController.currentSearchObjectArray;
		[self fetchTourSearchData:viewController commit:^{
			if (![self.tourSearchParam isEqual:self.tmpTourSearchParam]) {
				self.tourSearchParam = self.tmpTourSearchParam;
				self.tourSearchData = self.tmpTourSearchData;
				[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
				[self reloadTourSearchData];
			}
			[self.navigationController popViewControllerAnimated:YES];
			
		}];
	}];
	[viewController setGeocodeBlock:^(TourComboBoxViewController *viewController) {
		[Utility requestLocationWithCompletion:^(BOOL granted, CLLocation *location, NSError *error) {
			if (!granted || !location) {
				[viewController updatePlacemark:nil];
			} else {
				[Utility reverseGeocodeLocation:location completionHandler:^(CLPlacemark *placemark, NSError *error) {
					[viewController updatePlacemark:placemark];
				}];
			}
		}];
	}];
	[viewController setPlacemarkFormattingBlock:^NSString *(CLPlacemark *placemark) {
		return placemark.locality;
	}];
	[viewController setPlacemarkTransformationBlock:^id (CLPlacemark *placemark) {
		return [Destination localityTransformation:[self getTourSearchDestinationsByParam:self.tourSearchParam fromData:self.tourSearchData] objectForPlacemark:placemark];
	}];
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForDurationOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	NSMutableArray *optionValues = [NSMutableArray array];
	[optionValues addObject:@""];
	if (YES) {
		[optionValues addObjectsFromArray:@[@"1",@"2-3", @"3-4", @"4-5", @"5-6", @"6-7", @"8-"]];
	}
	if (YES) {
		self.selectDurationView.contextViewdataArray = @[@"1",@"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10",@"11+",@"All"];
		self.coverView.hidden = NO;
	}
}

- (void)performSegueForStartDateOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	CalendarViewController *viewController = [[CalendarViewController alloc] init];
	viewController.title = IMLocalizedString(@"Start Date");
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.allowsToday = NO;
	viewController.allowsMultipleSelection = YES;
	viewController.calendarManager.minimumDate = [NSDate date];
	viewController.calendarManager.maximumDate = [DateUtils addYears:[NSDate date] amount:1];
	[viewController setDidDoneMultipleBlock:^(NSArray<NSDate *> *dates) {
		[self changeStartDates:dates onTableView:tableView atIndexPath:indexPath];
	}];
	if (![StringUtils isEmpty:self.tourSearchParam.start_dates]) {
		[viewController selectDate:[[DateFormatUtils ISO_DATE_FORMAT] parse:self.tourSearchParam.start_dates]];
		NSArray *array = [self.tourSearchParam.start_dates componentsSeparatedByString:@";"];
		NSMutableArray *dates = [NSMutableArray array];
		for (NSString *date in array) {
			[dates addObject:[[DateFormatUtils ISO_DATE_FORMAT] parse:date]];
		}
		[viewController selectDates:[dates copy]];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForKeywordOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	AutoCompleteViewController *viewController = [[AutoCompleteViewController alloc] init];
	viewController.title = IMLocalizedString(@"Keywords or tour code");
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	[viewController setItemsWithArray:[Vars appDelegate].coreData.tourSearchDataSource[@"keywords"]];
	if (![StringUtils isEmpty:self.tourSearchParam.keywords]) {
		[viewController searchString:self.tourSearchParam.keywords];
	}
	[viewController setDidSelectStringBlock:^(NSString *string) {
		[self.navigationController popViewControllerAnimated:YES];
		self.tmpTourSearchParam = self.tourSearchParam;
		self.tmpTourSearchParam.keywords = string;
		if (![self.tourSearchParam isEqual:self.tmpTourSearchParam]) {
			[self fetchTourSearchData:self commit:^{
				self.tourSearchParam = self.tmpTourSearchParam;
				self.tourSearchData = self.tmpTourSearchData;
				[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
				[self reloadTourSearchData];
			}];
		}
	}];
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Action
- (void)changeStartDates:(NSArray *)dates onTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	NSMutableArray *start_dates = [NSMutableArray array];
	for (NSData *date in dates) {
		[start_dates addObject:(date ? [[DateFormatUtils ISO_DATE_FORMAT] format:date] : @"")];
	}
	[self.navigationController popViewControllerAnimated:YES];
	self.tmpTourSearchParam = self.tourSearchParam;
	self.tmpTourSearchParam.start_dates = [[start_dates copy] componentsJoinedByString:@";"];
	if (![self.tourSearchParam isEqual:self.tmpTourSearchParam]) {
		[self fetchTourSearchData:self commit:^{
			self.tourSearchParam = self.tmpTourSearchParam;
			self.tourSearchData = self.tmpTourSearchData;
			[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
			[self reloadTourSearchData];
		}];
	}
}

- (void)showTours {
	if (self.tourSearchParam.destinations.count == 0 && [StringUtils isEmpty:self.tourSearchParam.dep_ids] && [StringUtils isEmpty:self.tourSearchParam.keywords]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter at least one destination or departure city or keywords (tour code)")];
		return;
	}
	TourSearchListViewController *viewController = [[TourSearchListViewController alloc] init];
	TourSearchPaginationParam *tourSearchParam = [[TourSearchPaginationParam alloc] init];
	if (self.tourSearchParam.destinations.count > 0) {
		tourSearchParam.destinations = self.tourSearchParam.destinations;
	}
	if (![StringUtils isEmpty:self.tourSearchParam.dep_ids]) {
		tourSearchParam.departures = @[self.tourSearchParam.dep_ids];
	}
	if (![StringUtils isEmpty:self.tourSearchParam.duration]) {
		tourSearchParam.duration = @[self.tourSearchParam.duration];
	} else {
		if ([self.durationText isEqualToString:IMLocalizedString(@"1 day")]) {
			tourSearchParam.duration = @[@"1"];
		} else if ([StringUtils isEmpty:self.durationText]) {
		} else {
			tourSearchParam.duration = @[@"2-"];
		}
	}
	if (![StringUtils isEmpty:self.tourSearchParam.start_dates]) {
		tourSearchParam.startDates = @[self.tourSearchParam.start_dates];
	}
	if (![StringUtils isEmpty:self.tourSearchParam.keywords]) {
		tourSearchParam.keyWords = self.tourSearchParam.keywords;
	}
	viewController.tourSearchParam = tourSearchParam;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)hiddenCoverView {
	self.coverView.hidden = YES;
}
#pragma mark - Property

- (NSString *)destinationsText {
	return [[self.tourSearchParam.destinations bk_map:^id (id obj) {
		Area *area = self.allAreaSearchData[obj];
		return area.label;
	}] componentsJoinedByString:@" / "];
}

- (NSString *)departureText {
	NSDictionary *dict = [self getTourSearchDeparturesByParam:self.tourSearchParam fromData:self.tourSearchData];
	if (![StringUtils isEmpty:self.tourSearchParam.dep_ids]){
		return dict[self.tourSearchParam.dep_ids];
	} else {
		return @"";
	}
	
}

- (NSString *)startDatesText {
	if ([self.tourSearchParam.start_dates containsString:@";"]){
		NSArray *array = [self.tourSearchParam.start_dates componentsSeparatedByString:@";"];
		NSMutableArray *start_dates = [NSMutableArray array];
		for (NSString *date in array) {
			[start_dates addObject:[Utility localizedStringWithStandardDateString:date]];
		}
		return [[start_dates copy] componentsJoinedByString:@"/"];
	} else {
		return self.tourSearchParam.start_dates ;
	}
	
}

- (NSString *)durationText {
	return [self transformDuration:self.tourSearchParam.duration];
}

- (NSString *)keywordsText {
	return self.tourSearchParam.keywords;
}

- (NSString *)totalText {
	if (![self isTourSearchBoxEmptyByParam:self.tourSearchParam]) {
		NSDictionary *otherDatas = self.tourSearchData[@"otherDatas"];
		if (otherDatas && otherDatas[@"total"]) {
			return [NSString stringWithFormat:[Vars is_cn_website] ? IMLocalizedString(@"%@ Tour(s) Matched") : @"%@ Matched", [otherDatas[@"total"] intValue] >= 1000 ? @"999+" : otherDatas[@"total"]];
		}
	}
	return nil;
}

- (MultipleSelectionView *)selectDurationView {
	if (!_selectDurationView){
		_selectDurationView = [MultipleSelectionView viewFromNib];
		_selectDurationView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 270 + 2 * ([CocoaUtils isIPhoneX] ? 5 : 0));
		[_selectDurationView.contentView addSubview:self.collectView];
		[self.coverView addSubview:_selectDurationView];
		@weakify(self)
		_selectDurationView.backSelectDurationArray = ^(NSArray *selectArray) {
			@strongify(self)
			self.tmpTourSearchParam = self.tourSearchParam;
			if (!(selectArray.count==0)){
				self.tmpTourSearchParam.duration = [selectArray componentsJoinedByString:@","];
			} else {
				self.tmpTourSearchParam.duration = @"";
				[self.tmpDataDurations removeAllObjects];
				[self.collectView reloadData];
			}
			
			if (![self.tourSearchParam isEqual:self.tmpTourSearchParam]) {
				[self fetchTourSearchData:self commit:^{
					self.tourSearchParam = self.tmpTourSearchParam;
					self.tourSearchData = self.tmpTourSearchData;
					[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
					[self buildCellDataSource];
					[self reloadTourSearchData];
				}];
			}
			[self hiddenCoverView];
		};
		_selectDurationView.reloadContentView = ^(NSArray *selectArray) {
			@strongify(self)
			if (selectArray.count == 0){
				[self.tmpDataDurations removeAllObjects];
				[self.collectView reloadData];
			}
			
			
		};
		[_selectDurationView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
		[_selectDurationView autoPinEdgeToSuperviewEdge:ALEdgeBottom];
		[_selectDurationView autoSetDimension:ALDimensionHeight toSize:270 + 2 * ([CocoaUtils isIPhoneX] ? 5 : 0)];
		[_selectDurationView autoSetDimension:ALDimensionWidth toSize:CGRectGetWidth(self.view.frame)];
		[DrawUtils addRoundedBorderToRect:_selectDurationView byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadius:10];
		
	}
	return _selectDurationView;
}
- (UIView *)coverView {
	if (!_coverView) {
		_coverView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
		[_coverView setBackgroundColor:[UIColor colorWithWhite:0.f alpha:0.3]];
		UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenCoverView)];
		tap.delegate = self;
		[_coverView addGestureRecognizer:tap];
	
		_coverView.hidden = YES;
		[self.tabBarController.view addSubview:_coverView];
	}
	return _coverView;
}

-(UICollectionView *)collectView {
	if(!_collectView){
		CGFloat spacing = 17;
		CGFloat cols = 30;
		UICollectionViewFlowLayout *collectionViewLayout = [[UICollectionViewFlowLayout alloc] init];
		collectionViewLayout.itemSize = CGSizeMake(43, 43);
		collectionViewLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
		collectionViewLayout.minimumInteritemSpacing = spacing;
		collectionViewLayout.minimumLineSpacing = cols;

		_collectView = [[UICollectionView alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds) - 32, 115) collectionViewLayout:collectionViewLayout];
		_collectView.backgroundColor = [UIColor whiteColor];
		[_collectView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
		_collectView.dataSource = self;
		_collectView.delegate = self;
		_collectView.scrollEnabled = NO;
	}
	return _collectView;
}
-(NSMutableArray *)tmpDataDurations {
	if (!_tmpDataDurations){
		_tmpDataDurations = [NSMutableArray array];
	}
	return _tmpDataDurations;
}

-(NSMutableArray *)origionDataDurations {
	if (!_origionDataDurations){
		_origionDataDurations = [NSMutableArray array];
	}
	return _origionDataDurations;
}
#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([TourSearchBoxCell class]);
		data.isCustomRegistered = YES;
		data.reuseHeight = [UIConstants defaultTableViewRowHeight] + 5 * 2;
		[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, TourSearchBoxCell *cell) {
			@strongify(self)
			cell.labeltitle.hidden = NO;
			cell.labelcontent.hidden = NO;
			cell.textFiledContent.hidden = YES;
			cell.labeltitle.text =  IMLocalizedString(@"Destination(s) / Attraction(s)");
			cell.labelcontent.text = [StringUtils isEmpty:self.destinationsText] ? IMLocalizedString(@"Anywhere") : self.destinationsText;
			cell.imagetitle.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:28] fillColor:[UIColor lightGrayColor]];
			[cell.labelcontent setTextColor:([StringUtils isEmpty:self.destinationsText] ? [UIColor lightGrayColor] : [Vars defaultTintColor])];
			cell.buttonDelegate.hidden = [StringUtils isEmpty:self.destinationsText];
			[cell.buttonDelegate bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
			[cell.buttonDelegate bk_addEventHandler:^(id sender) {
				self.tmpTourSearchParam = self.tourSearchParam;
				self.tmpTourSearchParam.destinations = @[];
				self.tourSearchParam = self.tmpTourSearchParam;
				[self fetchTourSearchData:self commit:^{
					self.tourSearchData = self.tmpTourSearchData;
					[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
					[self reloadTourSearchData];
				}];
			} forControlEvents:UIControlEventTouchUpInside];
			cell.separatorInset = UIEdgeInsetsMake(0, 50, 0, 16);
		}];
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForDestinationOnTableView: tableView atIndexPath: indexPath];
		}];
		[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
			@strongify(self)
			return [NSString stringWithFormat:@"%u", self.destinationsText.length];
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([TourSearchBoxCell class]);
		data.isCustomRegistered = YES;
		data.reuseHeight = [UIConstants defaultTableViewRowHeight] + 5 * 2;
		[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, TourSearchBoxCell *cell) {
			@strongify(self)
			cell.labeltitle.text =  IMLocalizedString(@"Departure city");
			cell.labelcontent.text = [StringUtils isEmpty:self.departureText] ? IMLocalizedString(@"Anywhere") : self.departureText;
			cell.labeltitle.hidden = NO;
			cell.labelcontent.hidden = NO;
			cell.textFiledContent.hidden = YES;
			cell.imagetitle.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:28] fillColor:[UIColor lightGrayColor]];
			[cell.labelcontent setTextColor:([StringUtils isEmpty:self.departureText] ? [UIColor lightGrayColor] : [Vars defaultTintColor])];
			cell.buttonDelegate.hidden = [StringUtils isEmpty:self.departureText];
			[cell.buttonDelegate bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
			[cell.buttonDelegate bk_addEventHandler:^(id sender) {
				self.tmpTourSearchParam = self.tourSearchParam;
				self.tmpTourSearchParam.dep_ids = @"";
				self.tourSearchParam = self.tmpTourSearchParam;
				[self fetchTourSearchData:self commit:^{
					self.tourSearchData = self.tmpTourSearchData;
					[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
					[self reloadTourSearchData];
				}];
			} forControlEvents:UIControlEventTouchUpInside];
			cell.separatorInset = UIEdgeInsetsMake(0, 50, 0, 16);
		}];
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForDepartureOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([TourSearchBoxCell class]);
		data.isCustomRegistered = YES;
		data.reuseHeight = [UIConstants defaultTableViewRowHeight] + 5 * 2;
		[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, TourSearchBoxCell *cell) {
			@strongify(self)
			cell.labeltitle.text = IMLocalizedString(@"Duration");
			cell.labelcontent.text = [StringUtils isEmpty:self.durationText] ? IMLocalizedString(@"Any length") : self.durationText;
			cell.labeltitle.hidden = NO;
			cell.labelcontent.hidden = NO;
			cell.textFiledContent.hidden = YES;
			cell.imagetitle.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome clockOIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			[cell.labelcontent setTextColor:([StringUtils isEmpty:self.durationText] ? [UIColor lightGrayColor] : [Vars defaultTintColor])];
			cell.buttonDelegate.hidden = [StringUtils isEmpty:self.durationText];
			[cell.buttonDelegate bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
			[cell.buttonDelegate bk_addEventHandler:^(id sender) {
				self.tmpTourSearchParam = self.tourSearchParam;
				self.tmpTourSearchParam.duration = @"";
				[self.tmpDataDurations  removeAllObjects];
				[self.collectView reloadData];
				self.tourSearchParam = self.tmpTourSearchParam;
				[self fetchTourSearchData:self commit:^{
					self.tourSearchData = self.tmpTourSearchData;
					[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
					[self reloadTourSearchData];
				}];
			} forControlEvents:UIControlEventTouchUpInside];
			cell.separatorInset = UIEdgeInsetsMake(0, 50, 0, 16);
		}];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForDurationOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([TourSearchBoxCell class]);
		data.isCustomRegistered = YES;
		data.reuseHeight = [UIConstants defaultTableViewRowHeight] + 5 * 2;
		[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, TourSearchBoxCell *cell) {
			@strongify(self)
			cell.labeltitle.hidden = NO;
			cell.labelcontent.hidden = NO;
			cell.textFiledContent.hidden = YES;
			cell.labeltitle.text = IMLocalizedString(@"Start Date");
			cell.labelcontent.text = [StringUtils isEmpty:self.startDatesText] ? IMLocalizedString(@"Any day") : self.startDatesText;
			cell.imagetitle.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome calendarIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			[cell.labelcontent setTextColor:([StringUtils isEmpty:self.startDatesText] ? [UIColor lightGrayColor] : [Vars defaultTintColor])];
			cell.buttonDelegate.hidden = [StringUtils isEmpty:self.startDatesText];
			[cell.buttonDelegate bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
			[cell.buttonDelegate bk_addEventHandler:^(id sender) {
				@strongify(self)
				self.tmpTourSearchParam = self.tourSearchParam;
				self.tmpTourSearchParam.start_dates = @"";
				self.tourSearchParam = self.tmpTourSearchParam;
				[self fetchTourSearchData:self commit:^{
					self.tourSearchData = self.tmpTourSearchData;
					[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
					[self reloadTourSearchData];
				}];
			} forControlEvents:UIControlEventTouchUpInside];
			cell.separatorInset = UIEdgeInsetsMake(0, 50, 0, 16);
		}];

		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForStartDateOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([TourSearchBoxCell class]);
		data.isCustomRegistered = YES;
		data.reuseHeight = [UIConstants defaultTableViewRowHeight] + 5 * 2;
		[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, TourSearchBoxCell *cell) {
			@strongify(self)
			cell.labeltitle.hidden = YES;
			cell.labelcontent.hidden = YES;
			cell.textFiledContent.hidden = NO;
			cell.imagetitle.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome commentingOIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			cell.textFiledContent.placeholder = IMLocalizedString(@"Keywords or tour code");
			cell.textFiledContent.text = [StringUtils isEmpty:self.keywordsText] ?  @"" :self.keywordsText;
			[cell.textFiledContent setTextColor:[Vars defaultTintColor]];
			[cell.buttonDelegate setImageEdgeInsets:UIEdgeInsetsMake(-16, 16, 0, 0)];
			cell.buttonDelegate.hidden = [StringUtils isEmpty:self.keywordsText];
			cell.textFiledContent.bk_shouldEndEditingBlock = ^BOOL(UITextField * _Nonnull textField) {
				if ([StringUtils isEmpty:textField.text]){
					return YES;
				}
				self.tmpTourSearchParam = self.tourSearchParam;
				self.tmpTourSearchParam.keywords = textField.text;
				[self fetchTourSearchData:self commit:^{
					self.tourSearchParam = self.tmpTourSearchParam;
					self.tourSearchData = self.tmpTourSearchData;
					[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
					[self reloadTourSearchData];
				}];
				return YES;
			};
			[cell.buttonDelegate bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
			[cell.buttonDelegate bk_addEventHandler:^(id sender) {
				@strongify(self)
				self.tmpTourSearchParam = self.tourSearchParam;
				self.tmpTourSearchParam.keywords = @"";
				self.tourSearchParam = self.tmpTourSearchParam;
				[self fetchTourSearchData:self commit:^{
					self.tourSearchData = self.tmpTourSearchData;
					[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
					[self reloadTourSearchData];
				}];
			} forControlEvents:UIControlEventTouchUpInside];
			cell.separatorInset = UIEdgeInsetsMake(0, 50, 0, 16);
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.accessoryType = UITableViewCellAccessoryNone;
		[data setTextBlock:^NSString *{
			@strongify(self)
			return self.totalText;
		}];
		data.textAlignment = NSTextAlignmentCenter;
		data.textColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

- (void)reloadTourSearchData {
	[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:5 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
	UIButton *button = [self.tableView.tableFooterView viewWithTag:NSStringFromClass([UIButton class]).hash];
	button.enabled = YES;
	button.backgroundColor = [Vars defaultTintColor];
	if (![self isTourSearchBoxEmptyByParam:self.tourSearchParam]) {
		NSDictionary *otherDatas = self.tourSearchData[@"otherDatas"];
		if (otherDatas && otherDatas[@"total"]) {
			if ([otherDatas[@"total"] intValue] == 0) {
				button.enabled = NO;
				button.backgroundColor = [UIColor lightGrayColor];
			}
		}
	}
}

- (BOOL)isTourSearchBoxEmptyByParam:(TourSearchBoxParam *)param {
	if (param.destinations.count > 0) {
		return NO;
	}
	if (![StringUtils isEmpty:param.dep_ids]) {
		return NO;
	}
	if (![StringUtils isEmpty:param.start_dates]) {
		return NO;
	}
	if (![StringUtils isEmpty:param.keywords]) {
		return NO;
	}
	if (![StringUtils isEmpty:param.duration]) {
		return NO;
	}
	return YES;
}

- (NSDictionary *)getTourSearchDestinationsByParam:(TourSearchBoxParam *)param fromData:(NSDictionary *)data {
	NSDictionary *dataSource = nil;
	if ([self isTourSearchBoxEmptyByParam:param]) {
		dataSource = [Vars appDelegate].coreData.tourSearchDataSource[@"destinations"];
	} else {
		NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
		[dictionary addEntriesFromDictionary:[CocoaUtils nonNullDictionary:data[@"destinations"]]];
		if ([Vars is_cn_website]) {
			[dictionary addEntriesFromDictionary:[CocoaUtils nonNullDictionary:data[@"regions"]]];
		} else {
			[dictionary addEntriesFromDictionary:[[CocoaUtils nonNullDictionary:data[@"regions"]] bk_map:^id (id key, id obj) {
				return [Destination cityName:obj];
			}]];
		}
		[dictionary addEntriesFromDictionary:[CocoaUtils nonNullDictionary:data[@"attractions"]]];
		dataSource = [NSDictionary dictionaryWithDictionary:dictionary];
	}
	return dataSource;
}

- (NSDictionary *)getTourSearchDeparturesByParam:(TourSearchBoxParam *)param fromData:(NSDictionary *)data {
	NSDictionary *dataSource = nil;
	if ([self isTourSearchBoxEmptyByParam:param]) {
		dataSource = [Vars appDelegate].coreData.tourSearchDataSource[@"departures"];
	} else {
		dataSource = [CocoaUtils nonNullDictionary:data[@"departure"]];
	}
	return dataSource;
}

- (NSString *)transformDuration:(NSString *)duration {
	if ([StringUtils isEmpty:duration]) {
		return duration;
	} else if ([duration isEqualToString:@"1"]) {
		return [NSString stringWithFormat:IMLocalizedString(@"%@ day"), duration];
	} else if ([duration isEqualToString:@"8-"]) {
		return [NSString stringWithFormat:IMLocalizedString(@"%@ days"), @"8+"];
	} else {
		return [NSString stringWithFormat:IMLocalizedString(@"%@ days"), duration];
	}
}

#pragma mark - Table view data source

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[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.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.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

#pragma mark -gesturedelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
	if ([[touch.view superview] isDescendantOfView:self.coverView]) {
		return NO;
	}
	return YES;
}

#pragma mark - Collection view methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
	return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.selectDurationView.contextViewdataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";
	UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
	UIButton *button = [cell.contentView viewWithTag:NSStringFromClass([UIButton class]).hash];
	if (!button) {
		button = [[UIButton alloc] init];
		button.tag = NSStringFromClass([UIButton class]).hash;
		[cell.contentView addSubview:button];
	}
	button.userInteractionEnabled = NO;
	NSString *duration = self.selectDurationView.contextViewdataArray[indexPath.row];
	UICollectionViewFlowLayout *layout = collectionView.collectionViewLayout;
	button.frame = CGRectZeroMakeSize(layout.itemSize);
	[button setTitle:duration forState:UIControlStateNormal];
	if ([self.tmpDataDurations containsObject:duration]) {
		[button setBackgroundImage:[UIImage imageNamed:@"duration_button_background_selected"] forState:UIControlStateNormal];
		[button setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
	} else {
		[button setBackgroundImage:[UIImage imageNamed:@"duration_button_background_null"] forState:UIControlStateNormal];
		[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	}
	return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
	[collectionView deselectItemAtIndexPath:indexPath animated:YES];
	NSString *duration = self.selectDurationView.contextViewdataArray[indexPath.row];
	if ([self.tmpDataDurations containsObject:duration]) {
		[self.tmpDataDurations removeObject:duration];
		if ([self.tmpDataDurations containsObject:self.selectDurationView.contextViewdataArray.lastObject]){
			[self.tmpDataDurations removeObject:self.selectDurationView.contextViewdataArray.lastObject];
			[self.selectDurationView.tmpDataArray removeObject:self.selectDurationView.contextViewdataArray.lastObject];
			[collectionView reloadData];
		} else {
			[collectionView reloadItemsAtIndexPaths:@[indexPath]];
		}
		
	} else {
		if ([duration isEqualToString:self.selectDurationView.contextViewdataArray.lastObject]) {
			[self.tmpDataDurations removeAllObjects];
			self.tmpDataDurations = [self.selectDurationView.contextViewdataArray mutableCopy];
			[collectionView reloadData];
		} else {
			[self.tmpDataDurations addObject:duration];
			[collectionView reloadItemsAtIndexPaths:@[indexPath]];
		}
		
	}
	_selectDurationView.tmpDataArray = self.tmpDataDurations;
	
}

@end
