//
//  VectorHeatViewController.m
//  QMapKitDemo
//
//  Created by Keith Cao on 2020/4/21.
//  Copyright © 2020 tencent. All rights reserved.
//

#import "VectorHeatViewController.h"

#import <QMapVisualPlugin/QMapPluginKit.h>

#import "StyleView.h"

#define GlobalNavAndStatusHight (self.navigationController.navigationBar.frame.size.height + [[UIApplication sharedApplication] statusBarFrame].size.height)

static const NSInteger GlobalStyleTitleArrayCount = 13;

static NSString *const GlobalStyleTitleArray[GlobalStyleTitleArrayCount] =
{
	@"展示层级和颜色",
	@"半径",
	@"级别+类型",
	@"透明度",
	@"可见性",
	@"3D",
	@"热力区间",
	@"高度",
	@"zIndex",
	@"配色一",
	@"配色二",
	@"配色三",
	@"配色四"
};


@interface VectorHeatViewController ()

@property (nonatomic, strong) QVectorHeatOverlay *heatTileOverlay;

@property (nonatomic, strong) QVectorHeatOverlay *heat2;

@property (nonatomic, strong) StyleView *styleView;

@end

@implementation VectorHeatViewController

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	[self.navigationController setToolbarHidden:NO animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	
	[self.navigationController setToolbarHidden:YES animated:animated];
}


#pragma mark - Action

- (void)handleSwitchAction
{
	UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择需要切换的样式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
	
	[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
	
	for (int i = 0; i < GlobalStyleTitleArrayCount; i++)
	{
		[alertController addAction:[UIAlertAction actionWithTitle:GlobalStyleTitleArray[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
			[self handleChangeAction:i];
		}]];
	}
	
	[self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark -- changeAction

- (void)handleChangeAction:(NSInteger)actNum
{
	switch (actNum) {
		case 0:
			
			[self changeColorAndDisplayLevel];
			
			break;
		case 1:
			[self changeSize];
			
			break;
			
		case 2:
			[self changeZoomAndType];
			
			break;
		case 3:
			[self changeOpacity];
			break;
			
		case 4:
			[self changeVisible];
			break;
		case 5:
			[self change3D];
			break;
		case 6:
			[self changeIntensity];
			break;
		case 7:
			[self changeHeight];
			break;
		case 8:
			[self changeZIndex];
			break;
		case 9:
			[self changeColorStyle];
			break;
		case 10:
			[self changeColorStyleTwo];
			break;
		case 11:
			[self changeColorStyleThree];
			break;
		case 12:
			[self changeColorStyleFour];
			break;
		default:
			break;
	}
}

// 颜色+展示层级
- (void)changeColorAndDisplayLevel
{
	NSArray<UIColor *> *colorDB = @[
		[UIColor purpleColor],
		[UIColor cyanColor],
		[UIColor greenColor]
	];
	
	[self.heatTileOverlay setColors:colorDB startPoints:@[@0.0f,@0.5f, @1.f]];
	QVectorHeatOverlayView *hv = (QVectorHeatOverlayView *) [self.mapView viewForOverlay:self.heatTileOverlay];
	
	hv.displayLevel = QOverlayLevelAboveLabels;
	// 刷新样式需调用此接口，否则新样式不生效
	[self.heatTileOverlay setNeedsDisplay];
	
	
}

// 1 半径
- (void)changeSize
{
	int size = arc4random() % 500 + 2000;
	
	size = size / 10 * self.mapView.zoomLevel;
	
	self.heatTileOverlay.size = size;
	self.heatTileOverlay.gap = size / (arc4random() %4 + 1);
	// 刷新样式需调用此接口，否则新样式不生效
	[self.heatTileOverlay setNeedsDisplay];
	
}

// 2 type 和 最大最小
- (void)changeZoomAndType
{
	[self.heatTileOverlay setMinZoomLevel:10 maxZoomLevel:17];
	
	if (self.heatTileOverlay.type == QVectorHeatTypeHoneyComb)
	{
		self.heatTileOverlay.type = QVectorHeatTypeSquare;
	}
	else
	{
		self.heatTileOverlay.type = QVectorHeatTypeHoneyComb;
	}
	// 刷新样式需调用此接口，否则新样式不生效
	[self.heatTileOverlay setNeedsDisplay];
}

// 3 透明
- (void)changeOpacity
{
	self.heatTileOverlay.opacity = self.heatTileOverlay.opacity == 1 ? 0.5 : 1;
	
}

// 4 可见性
- (void)changeVisible
{
	self.heatTileOverlay.visible = !self.heatTileOverlay.visible;
}

//5 3d
- (void)change3D
{
	self.heatTileOverlay.enable3D = !self.heatTileOverlay.enable3D;
	// 刷新样式需调用此接口，否则新样式不生效
	[self.heatTileOverlay setNeedsDisplay];
}

// 6 热力区间
- (void)changeIntensity
{
	[self.heatTileOverlay setMinIntensity:100 maxIntensity:1000];
	// 刷新样式需调用此接口，否则新样式不生效
	[self.heatTileOverlay setNeedsDisplay];
	
	
}

// 7 高度
- (void)changeHeight
{
	[self.heatTileOverlay setMinHeight:300 maxHeight:600];
	// 刷新样式需调用此接口，否则新样式不生效
	[self.heatTileOverlay setNeedsDisplay];
}

// 8 zindex
- (void)changeZIndex
{
	QVectorHeatOverlayView *hv = (QVectorHeatOverlayView *)[self.mapView viewForOverlay:self.heatTileOverlay];
	QVectorHeatOverlayView *hv2 = (QVectorHeatOverlayView *)[self.mapView viewForOverlay:self.heat2];
	
	hv.zIndex = 100;
	hv.zIndex = 50;
	
}

// 9 配色1
- (void)changeColorStyle
{
	self.mapView.mapType = QMapTypeDark;
	self.mapView.overlooking = 40;
	
	if (self.heatTileOverlay)
	{
		NSArray *styleColors =  @[
			[UIColor colorWithRed:0x3B / 255.0 green:0x12 / 255.0 blue:0x30 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x90 / 255.0 green:0x09 / 255.0 blue:0x3B / 255.0 alpha:1.0],
			[UIColor colorWithRed:0xCB / 255.0 green:0x01 / 255.0 blue:0x34 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0xF4 / 255.0 green:0x6A / 255.0 blue:0x25 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0xFF / 255.0 green:0xAA / 255.0 blue:0x00 / 255.0 alpha:1.0]
		];
		
		NSArray *startPoints = @[@0.f, @0.1f, @0.15f, @0.3f, @0.5f
		];
		
		[self.heatTileOverlay setColors:styleColors startPoints:startPoints];
		// 刷新样式需调用此接口，否则新样式不生效
		[self.heatTileOverlay setNeedsDisplay];
	}
}

// 9 配色2
- (void)changeColorStyleTwo
{
	self.mapView.mapType = QMapTypeDark;
	self.mapView.overlooking = 40;
	
	if (self.heatTileOverlay)
	{
		NSArray *styleColors =  @[
			[UIColor colorWithRed:0x1f / 255.0 green:0x2c / 255.0 blue:0x47 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x28 / 255.0 green:0x48 / 255.0 blue:0x8a / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x26 / 255.0 green:0x61 / 255.0 blue:0xd9 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x5a / 255.0 green:0x8c / 255.0 blue:0xf2 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x99 / 255.0 green:0xbb / 255.0 blue:0xff / 255.0 alpha:1.0]
		];
		
		NSArray *startPoints = @[@0.f, @0.1f, @0.15f, @0.3f, @0.5f
		];
		
		[self.heatTileOverlay setColors:styleColors startPoints:startPoints];
		// 刷新样式需调用此接口，否则新样式不生效
		[self.heatTileOverlay setNeedsDisplay];
	}
}

// 9 配色3
- (void)changeColorStyleThree
{
	self.mapView.mapType = QMapTypeDark;
	self.mapView.overlooking = 40;
	
	if (self.heatTileOverlay)
	{
		NSArray *styleColors =  @[
			[UIColor colorWithRed:0x47 / 255.0 green:0x30 / 255.0 blue:0x1f / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x8a / 255.0 green:0x51 / 255.0 blue:0x28 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0xd9 / 255.0 green:0x71 / 255.0 blue:0x26 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0xf2 / 255.0 green:0x99 / 255.0 blue:0x5a / 255.0 alpha:1.0],
			[UIColor colorWithRed:0xff / 255.0 green:0xc4 / 255.0 blue:0x99 / 255.0 alpha:1.0]
		];
		
		NSArray *startPoints = @[@0.f, @0.1f, @0.15f, @0.3f, @0.5f
		];
		
		[self.heatTileOverlay setColors:styleColors startPoints:startPoints];
		// 刷新样式需调用此接口，否则新样式不生效
		[self.heatTileOverlay setNeedsDisplay];
	}
}

// 9 配色4
- (void)changeColorStyleFour
{
	self.mapView.mapType = QMapTypeDark;
	self.mapView.overlooking = 40;
	
	if (self.heatTileOverlay)
	{
		NSArray *styleColors =  @[
			[UIColor colorWithRed:0x01 / 255.0 green:0x2C / 255.0 blue:0x4B / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x17 / 255.0 green:0x3E / 255.0 blue:0x59 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x3A / 255.0 green:0x73 / 255.0 blue:0x78 / 255.0 alpha:1.0],
			[UIColor colorWithRed:0x98 / 255.0 green:0xCD / 255.0 blue:0x9A / 255.0 alpha:1.0],
			[UIColor colorWithRed:0xF6 / 255.0 green:0xFB / 255.0 blue:0xB6 / 255.0 alpha:1.0]
		];
		
		NSArray *startPoints = @[@0.f, @0.1f, @0.15f, @0.3f, @0.5f
		];
		
		[self.heatTileOverlay setColors:styleColors startPoints:startPoints];
		
		// 刷新样式需调用此接口，否则新样式不生效
		[self.heatTileOverlay setNeedsDisplay];
	}
}

#pragma mark - Setup

- (void)setupSelf
{
	self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (void)setupNavigation
{
	self.navigationController.navigationBar.translucent = YES;
	
	UIBarButtonItem *switchButton = [[UIBarButtonItem alloc] initWithTitle:@"切换样式" style:UIBarButtonItemStyleDone target:self action:@selector(handleSwitchAction)];
	
	self.navigationItem.rightBarButtonItem = switchButton;
}

- (void)setupStyleView
{
	self.styleView = [[StyleView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 100, self.view.bounds.size.width, 100)];
	self.styleView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
	
	[self.view addSubview:self.styleView];
}


- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	
	[self setupSelf];
	[self setupNavigation];
	[self setupStyleView];
	
	[self setupToolbar];
	self.mapView.delegate = self;
	self.mapView.showsScale = YES;
	[self.mapView setScaleViewOffset:CGPointMake(200, -300)];
	
	self.mapView.overlooking = 45;
	self.mapView.zoomLevel = 10;
	self.mapView.centerCoordinate = CLLocationCoordinate2DMake(39.91718071931067,116.4151898097858);
	
	self.mapView.mapType = QMapTypeDark;
	
}

- (void)setupToolbar
{
	UIBarButtonItem *flexble = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
	
	UIBarButtonItem *add    = [[UIBarButtonItem alloc] initWithTitle:@"添加"  style:UIBarButtonItemStyleDone  target:self action:@selector(handleAddAction)];
	UIBarButtonItem *remove = [[UIBarButtonItem alloc] initWithTitle:@"删除"  style:UIBarButtonItemStyleDone  target:self action:@selector(handleRemoveAction)];
	UIBarButtonItem *reload = [[UIBarButtonItem alloc] initWithTitle:@"再加一个"  style:UIBarButtonItemStyleDone  target:self action:@selector(handleReloadAction)];
	
	self.toolbarItems = @[flexble, add, flexble, remove, flexble, reload, flexble, flexble];
}

#pragma mark - MapViewDelegate

- (QOverlayView *)mapView:(QMapView *)mapView viewForOverlay:(id<QOverlay>)overlay
{
	if ([overlay isKindOfClass:[QVectorHeatOverlay class]])
	{
		QVectorHeatOverlayView *heatView = [[QVectorHeatOverlayView alloc] initWithHeatOverlay:overlay];
		heatView.displayLevel = QOverlayLevelAboveLabels;
		return heatView;
	}
	return nil;
}

- (void)mapView:(QMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate
{
	QVectorHeatAggregationUnit *unit = [self.heatTileOverlay getAggregationUnit:coordinate];
	if (unit)
	{
		NSLog(@"count=%ld. intensity=%f. || center=(%f,%f). pt=(%f,%f)", unit.nodeIndices.count, unit.intensity, unit.center.latitude, unit.center.longitude, QMapPointForCoordinate(unit.center).x, QMapPointForCoordinate(unit.center).y);
	}
}

- (void)mapView:(QMapView *)mapView didTapPoi:(QPoiInfo *)poi
{
	NSLog(@"tapPoi:%@", poi.name);
}

- (void)mapView:(QMapView *)mapView regionDidChangeAnimated:(BOOL)animated gesture:(BOOL)bGesture
{
	NSLog(@"z:%f, coord:%f,%f", mapView.zoomLevel, mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude);
}

#pragma mark -

// 添加
- (void)handleAddAction
{
	if (self.heatTileOverlay != nil) return;
	
	self.heatTileOverlay = [self constructVectorHeatTileOverlay];
	
	[self.mapView addOverlay:self.heatTileOverlay];
}


// 删除
- (void)handleRemoveAction
{
	if (self.heatTileOverlay == nil) return;
	
	[self.mapView removeOverlay:self.heatTileOverlay];
	
	self.heatTileOverlay = nil;
}

// 再加一个
- (void)handleReloadAction
{
	self.heat2 = [self constructVectorHeatTileOverlay];
	
	[self.heat2.option setColors:@[[UIColor orangeColor],[UIColor greenColor], [UIColor blueColor]] startPoints:self.heat2.option.startPoints];
	[self.mapView addOverlay:_heat2];
	
}
- (QVectorHeatOverlay *)constructVectorHeatTileOverlay
{
	NSMutableArray <QHeatNode *> *nodes = [NSMutableArray array];
	{
		NSString *filePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"weightdot.data" ofType:nil];
		
		NSString* fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
		
		NSArray* allLinedStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
		
		[allLinedStrings enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
			
			NSArray *ar = [obj componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
			if (ar.count == 3)
			{
				// 纬度.
				double lat = [ar[1] doubleValue];
				// 经度.
				double lon = [ar[0] doubleValue];
				// 权值.
				double val = [ar[2] doubleValue];
				
				QHeatNode *node = [[QHeatNode alloc] init];
				node.coordinate = CLLocationCoordinate2DMake(lat, lon);
				node.value      = val;
				
				
				[nodes addObject:node];
			}
		}];
	}
	
	// 通用动画类
	QAnimation *ani = [[QAnimation alloc] init];
	ani.duration = 3;
	
	// 蜂窝热力图属性配置项，如不设置，则使用默认配置
	QVectorHeatOverlayOption *option = [[QVectorHeatOverlayOption alloc] init];
	option.size = 1500 / 10 * self.mapView.zoomLevel;
	
	option.gap = option.size / 4 ;
	
	option.maxHeight = 500;
	option.minHeight = 0;
	option.enable3D = YES;
	option.animation = ani;
	
	QVectorHeatOverlay *heat = [[QVectorHeatOverlay alloc] initWithHeatNodes:nodes option:option];
	
	return heat;
}

@end
