//
//  TruckSearchViewController.m
//  QMapKitDemo
//
//  Created by Keith Cao on 2023/10/19.
//  Copyright © 2023 tencent. All rights reserved.
//

#import "TruckSearchViewController.h"
#import <QMapKit/QMSSearchKit.h>
#import "QSearchTools.h"

@interface TruckSearchViewController () <QMSSearchDelegate>

@property (nonatomic, strong) QMSSearcher *searcher;

@end

@implementation TruckSearchViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	[self searchTruckRoutePlan];
}

- (void)searchTruckRoutePlan
{
	self.searcher = [[QMSSearcher alloc] initWithDelegate:self];
	
	QMSTruckingRouteSearchOption *truckOption = [[QMSTruckingRouteSearchOption alloc] init];
	truckOption.from = @"39.960521,116.318928";
	truckOption.to = @"39.806965,116.421292";
	truckOption.width = 2.5;
	truckOption.length = 4;
	truckOption.weight = 2.3;
	truckOption.get_speed = 1;
	truckOption.get_mp = 1;
	
	truckOption.added_fields = @"cities,toll_distance";
	
	// 发起检索
	[self.searcher searchWithTruckingRouteSearchOption:truckOption];
}

- (void)drawRouteLineWithResult:(QMSTruckingRouteSearchResult *)result
{
	[self.mapView removeOverlays:self.mapView.overlays];
	
	QMSTruckingRoutePlan *plan = result.routes.firstObject;
	
	// 创建线
	NSUInteger count = plan.polyline.count;
	CLLocationCoordinate2D coordinateArray[count];
	for (int i = 0; i < count; ++i)
	{
		coordinateArray[i] = [QSearchTools decodeCoordinateValue:[plan.polyline objectAtIndex:i]];
	}
	QPolyline *polyline = [[QPolyline alloc] initWithCoordinates:coordinateArray count:count];
	
	// 根据路况信息创建路线分段颜色
	NSArray *routeStyle = [QSearchTools getSegmentColorsFromRouteCondition:plan.speed];
	polyline.userData = routeStyle;
	
	[self.mapView addOverlay:polyline];
	
	// 调整视野
	[self.mapView setVisibleMapRect:polyline.boundingMapRect edgePadding:UIEdgeInsetsMake(50, 30, 30, 50) animated:YES];
}

#pragma mark -- MapDelegate
- (QOverlayView *)mapView:(QMapView *)mapView viewForOverlay:(id<QOverlay>)overlay
{
	if ([overlay isKindOfClass:[QPolyline class]])
	{
		QPolyline *polyline = (QPolyline*)overlay;
		QTexturePolylineView *polylineRender = [[QTexturePolylineView alloc] initWithPolyline:polyline];
		polylineRender.drawType = QTextureLineDrawType_ColorLine;
		// 分段颜色赋值
		polylineRender.segmentColor = polyline.userData;
		polylineRender.lineWidth = 8;
		return polylineRender;
	}
	return nil;
}

#pragma mark -- SearchDelegate

- (void)searchWithSearchOption:(QMSSearchOption *)searchOption didFailWithError:(NSError *)error
{
	NSLog(@"error:%@", error);
}

- (void)searchWithTruckingRouteSearchOption:(QMSTruckingRouteSearchOption *)truckingRouteSearchOption didRecevieResult:(QMSTruckingRouteSearchResult *)truckingRouteSearchResult
{
	[self drawRouteLineWithResult:truckingRouteSearchResult];
}

@end
