//
// ScheduleDetailsViewController.m
// GotoBus
//
// Created by vae on 2018/1/11.
//

#import "ScheduleDetailsViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "DZNEmptyDataSetDefault.h"
#import <FontAwesomeKit/FontAwesomeKit.h>
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "Product.h"
#import "Schedule.h"
#import "BookingReportDetailResponseJsonMapper.h"
#import "CheckoutViewController.h"
#import "Vars.h"

@interface ScheduleDetailsViewController () <DZNEmptyDataSetDefault>
@property (nonatomic, strong) NSArray<NSMutableArray *> *cellDataArrays;
@property (nonatomic, strong) NSArray<NSArray *> *accordionCellDataArrays;
@property (nonatomic, strong) NSArray<BookingReportSummaryBean *> *bookingReportSummaryList;
@end

@implementation ScheduleDetailsViewController

- (instancetype)init {
	if (self = [super init]) {
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	self.title = self.service_date;
	
	self.tableView.emptyDataSetSource = self;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	if (!self.bookingReportSummaryList) {
		[self performRequestForBookingReportDetail];
	}
}

#pragma mark - Network

- (void)performRequestForBookingReportDetail {
	BookingReportDetail *bookingReportDetail = [[BookingReportDetail alloc] init];
	bookingReportDetail.departureDate = self.service_date;
	bookingReportDetail.scheduleId = self.schedule.id;

	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:bookingReportDetail];
	self.tableView.emptyDataSetSource = nil;
	[Utility performRESTRequestWithMethod:@"POST" url:bookingReportDetail.address parameters:requestDict success:^(id jsonObject) {
		//NSLog(@"%@", jsonObject);
		BookingReportDetailResponseJsonMapper *mapper = [[BookingReportDetailResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]) {
			BookingReportDetailResponse *response = mapper.response;
			if (response.errorCode > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.errorMessage];
			} else {
				self.bookingReportSummaryList = response.bookingReportSummaryList;
				[self buildCellDataSource];
				 self.tableView.emptyDataSetSource = self;
				[self.tableView reloadData];
				[self judgeLocation];
			}
		}
	}];
}

#pragma mark - Segue

- (void)performSegueForCashTicketWithObject:(BookingReportDetailBean *)bookingReportDetail {
	CheckoutViewController *viewController = [[CheckoutViewController alloc] init];
	viewController.service_date = self.service_date;
	viewController.bookingReportDetail = bookingReportDetail;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (void)buildCellDataSource {
	@weakify(self)
	if (YES) {
		NSMutableArray *arrays = [NSMutableArray array];
		for (BookingReportSummaryBean *bookingReportSummary in self.bookingReportSummaryList) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome locationArrowIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			data.text = bookingReportSummary.defaultBookingReportDetail.departureScheduleStop.city.show_name;
			data.detailText = bookingReportSummary.defaultBookingReportDetail.departureScheduleStop.busstation.name;
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
			data.stronglyAssociatedObject = @NO;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self changeExpandAction: ![data.stronglyAssociatedObject boolValue] onTableView:tableView atIndexPath: indexPath];
			}];
			[arrays addObject:[NSMutableArray arrayWithObject:data]];
		}
		self.cellDataArrays = [NSArray arrayWithArray:arrays];
	}
	if (YES) {
		NSMutableArray *arrays = [NSMutableArray array];
		for (BookingReportSummaryBean *bookingReportSummary in self.bookingReportSummaryList) {
			NSMutableArray *array = [NSMutableArray array];
			for (BookingReportDetailBean *bookingReportDetail in bookingReportSummary.bookingReportDetailList) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
				data.style = UITableViewCellStyleSubtitle;
				data.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:24] fillColor:[UIColor lightGrayColor]];
				data.text = bookingReportDetail.arrivalScheduleStop.city.show_name;
				data.detailText = bookingReportDetail.arrivalScheduleStop.busstation.name;
				[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
					return [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome moneyIconWithSize:24] fillColor:[Vars defaultTintColor]]];
				}];
				[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
					@strongify(self)
					[self performSegueForCashTicketWithObject: bookingReportDetail];
				}];
				[array addObject:data];
			}
			[arrays addObject:[NSArray arrayWithArray:array]];
		}
		self.accordionCellDataArrays = [NSArray arrayWithArray:arrays];
	}
}

- (void)changeExpandAction:(BOOL)isExpand onTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
	for (int section = 0; section < self.cellDataArrays.count; section++) {
		NSMutableArray *arrary = self.cellDataArrays[section];
		TableViewCellData *data = arrary.firstObject;
		if ([data.stronglyAssociatedObject boolValue] == YES) {
			data.stronglyAssociatedObject = @NO;
			[CocoaUtils removeObjectsInArray:self.cellDataArrays[section] fromIndex:1];
			[indexSet addIndex:section];
		}
	}
	if (isExpand == YES) {
		NSMutableArray *array = self.cellDataArrays[indexPath.section];
		TableViewCellData *data = array.firstObject;
		data.stronglyAssociatedObject = @(YES);
		[array addObjectsFromArray:self.accordionCellDataArrays[indexPath.section]];
		[indexSet addIndex:indexPath.section];
	}
	[tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
	if (![tableView.indexPathsForVisibleRows containsObject:indexPath]) {
		[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
	}
}

- (void)judgeLocation {
	[Utility requestLocationWithCompletion:^(BOOL granted, CLLocation *location, NSError *error) {
		NSMutableArray *distanceArray = [NSMutableArray array];
		for (int i = 0; i < self.bookingReportSummaryList.count; i++) {
			BusStation *station = self.bookingReportSummaryList[i].defaultBookingReportDetail.departureScheduleStop.busstation;
			CLLocation *busStationLocation = [[CLLocation alloc] initWithLatitude:station.latitude longitude:station.longitude];
			CLLocationDistance distance = [location distanceFromLocation:busStationLocation];
			[distanceArray addObject:@(distance)];
		}
		CLLocationDistance minDistance = [[distanceArray valueForKeyPath:@"@min.doubleValue"] doubleValue];
		if (minDistance < 1000) {
			NSInteger index = [distanceArray indexOfObject:@(minDistance)];
			[self changeExpandAction:YES onTableView:self.tableView atIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]];
		}
	}];
}

#pragma mark - Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return self.cellDataArrays.count;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

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

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

@end
