//
//  DeliveryTrackingViewController.m
//  Palmwms
//
//  Created by 曹云霄 on 16/8/25.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "DeliveryTrackingViewController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import "CustomBMKAnnotationView.h"
#import "UserPaopaoView.h"
#import "UIImage+Rotate.h"
#import "OrderDetailsViewController.h"
#import "OrderListViewController.h"

#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
#define USERLOCATIONID @"userlocation"
#define PAGESIZE 100

@interface RouteAnnotation : BMKPointAnnotation
{
    int _type; ///<0:起点 1：终点 2：公交 3：已送达途经点 4:驾乘 5:为送达途经点
    int _degree;//方向
}

@property (nonatomic,assign) int type;
@property (nonatomic,assign) int degree;
@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;
@end


@interface DeliveryTrackingViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKRouteSearchDelegate,BMKGeoCodeSearchDelegate>


@property (nonatomic,strong) BMKRouteSearch *routesearch;
@property (strong, nonatomic) BMKLocationService *locService;
@property (strong, nonatomic) BMKMapView* mapView;
@property (nonatomic,strong) BMKLocationViewDisplayParam *displayLocation;
@property (nonatomic,strong) BMKGeoCodeSearch *geographicSearch;//用于反地理编码

/**
 *  保存用户大头针对象
 */
@property (nonatomic,strong) BMKPointAnnotation *userPointAnnotation;

/**
 *  发货单
 */
@property (weak, nonatomic) IBOutlet UIView *invoiceView;

/**
 *  发货单信息
 */
@property (weak, nonatomic) IBOutlet UILabel *invoiceInformationlabel;

/**
 *  发货单详情
 */
@property (nonatomic,strong) UIView *invoiceDetailsView;

/**
 *  发货单列表
 */
@property (nonatomic,strong) UIView *orderListView;

/**
 *  已送达店铺
 */
@property (nonatomic,strong) NSMutableArray *arriveStoreArray;

/**
 *  订单列表
 */
@property (nonatomic,strong) NSMutableArray *orderListArray;

/**
 *  当前选中的发货单
 */
@property (nonatomic,strong) Busbill *selecteOrderBill;

/**
 *  当前选中的发货单indexPath
 */
@property (nonatomic,strong) NSIndexPath *selectIndexPath;

/**
 *  排序后的发货单详情
 */
@property (nonatomic,strong) NSArray *sortingArray;



@end

@implementation DeliveryTrackingViewController

- (NSString*)getMyBundlePath1:(NSString *)filename
{
    NSBundle * libBundle = MYBUNDLE ;
    if ( libBundle && filename ){
        NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
        return s;
    }
    return nil ;
}

#pragma mark - lazy
- (NSMutableArray *)arriveStoreArray
{
    if (!_arriveStoreArray) {
        _arriveStoreArray = [NSMutableArray array];
    }
    return _arriveStoreArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    _routesearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _geographicSearch.delegate = self;
    [self queryOrderBillDatasAndDepotInforMation];
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
    _routesearch.delegate = nil; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _geographicSearch.delegate = nil;
}

#pragma mark - UI
- (void)uiConfigAction
{
   [self.invoiceView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(invoiceViewClickAction:)]];
    //初始化
    _geographicSearch = [[BMKGeoCodeSearch alloc]init];
    _routesearch = [[BMKRouteSearch alloc]init];
    self.locService = [[BMKLocationService alloc]init];
    [self.locService startUserLocationService];
    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.mj_w, self.view.mj_h-44-64)];
    [self.view insertSubview:_mapView atIndex:0];
    self.mapView.zoomLevel = 16;
    self.locService.pausesLocationUpdatesAutomatically = NO;
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    double latitude = userLocation.location.coordinate.latitude;
    double longitude = userLocation.location.coordinate.longitude;
    [UserInforMation manager].latitude = latitude;
    [UserInforMation manager].longitude = longitude;//记录用户经纬度
    CLLocationCoordinate2D location = CLLocationCoordinate2DMake(latitude, longitude);
    //地址解析
    BMKReverseGeoCodeOption *CodeOption = [[BMKReverseGeoCodeOption alloc]init];
    CodeOption.reverseGeoPoint = location;
    [self.geographicSearch reverseGeoCode:CodeOption];
    [self displayAnnotationWithLatitude:latitude andLongitude:longitude title:USERLOCATIONID];
}

/**
 *返回反地理编码搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果
 *@param error 错误号，@see BMKSearchErrorCode
 */
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"反地理编码成功----%p",[UserInforMation manager]);
    BMKAddressComponent *content = result.addressDetail;
    [UserInforMation manager].city = content.city;
    [UserInforMation manager].address = result.address;
    [self downLoadLocationCityMaps];
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
//    [self SHOWPrompttext:@"定位失败"];
}

#pragma mark -自定义用户大头针
- (void)displayAnnotationWithLatitude: (CGFloat)latitude andLongitude: (CGFloat)longitude title:(NSString *)title
{
    [self.mapView removeAnnotation:self.userPointAnnotation];
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(latitude,longitude) animated:YES];
     BMKPointAnnotation  *pointAnnotation = [[BMKPointAnnotation alloc]init];
    self.userPointAnnotation = pointAnnotation;
    pointAnnotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
    pointAnnotation.title = title;
    [self.mapView addAnnotation:pointAnnotation];
}

/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //标注物
    if ([annotation isKindOfClass:[RouteAnnotation class]]) {
        return [self getRouteAnnotationView:mapView viewForAnnotation:(RouteAnnotation*)annotation];
    }
    //用户位置
    CustomBMKAnnotationView *annottionView = (CustomBMKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:USERLOCATIONID];
    if (!annottionView) {
        annottionView = [[CustomBMKAnnotationView alloc]carSignInitialize:annotation reuseIdentifier:USERLOCATIONID];
    }
    UserPaopaoView *paopaoView = [[UserPaopaoView alloc] signUserInitialize:[UIView new] withCoord:annotation.coordinate];
    paopaoView.frame = CGRectMake(0, 0, 200, 70);
    annottionView.paopaoView = paopaoView;
    return annottionView;
}


#pragma mark -路径规划
- (void)startDrawWayPointRoutepointArray:(NSArray *)arrays
{
    //删除无坐标的门店
    NSMutableArray *locationArray = [NSMutableArray array];
    for (BusbillDtl *model in arrays) {
        if ([model.customerLng length] && [model.customerLat length]) {
            [locationArray addObject:model];
        }
    }
    UserInforMation *user = [UserInforMation manager];
    //起点
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    start.name = user.address;
    start.cityName =  user.city;
    start.pt = CLLocationCoordinate2DMake(user.depotLatitude, user.depotLongitude);
    //途径点
    NSMutableArray *array = [NSMutableArray array];
    [locationArray enumerateObjectsUsingBlock:^(id  _Nonnull object, NSUInteger index, BOOL * _Nonnull stop) {
        
        BusbillDtl *model = (BusbillDtl  *)object;
        BMKPlanNode* wayPointItem = [[BMKPlanNode alloc]init];
        wayPointItem.name =  model.customerName;
        wayPointItem.cityName = user.city;
        CLLocationCoordinate2D pt = CLLocationCoordinate2DMake([model.customerLat doubleValue], [model.customerLng doubleValue]);
        wayPointItem.pt = pt;
        [array addObject:wayPointItem];
    }];
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = start;
    drivingRouteSearchOption.to = start;
    drivingRouteSearchOption.wayPointsArray = array;
    BOOL flag = [_routesearch drivingSearch:drivingRouteSearchOption];
    if(flag)
    {
        [self CreateMBProgressHUDLoding:@"路径规划中"];
    }
    else
    {
        [self SHOWPrompttext:@"路径规划错误"];
    }
}

#pragma mark - 获取发货单列表和仓库信息
- (void)queryOrderBillDatasAndDepotInforMation
{
    WS(weakSelf);
    dispatch_group_t group = dispatch_group_create();
    [self CreateMBProgressHUDLoding:@"加载中"];
    //任务一，获取仓库信息
    dispatch_group_enter(group);
    NSString *URL = [NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(QUERYDEPOT),@"depot"];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:URL WithRequestType:NetworkRequestWithGET WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        dispatch_group_leave(group);
        [UserInforMation manager].depotLatitude = [returnValue[@"data"][@"lat"] doubleValue];
        [UserInforMation manager].depotLongitude = [returnValue[@"data"][@"lng"] doubleValue];
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        dispatch_group_leave(group);
        [weakSelf SHOWPrompttext:NETWORK];
        
    } WithFailureBlock:^(NSError *error) {
        dispatch_group_leave(group);
        [weakSelf SHOWPrompttext:error.localizedDescription];
    }];
    //任务二，获取发货单列表信息
    dispatch_group_enter(group);
    BusbillQueryDefintion *query = [[BusbillQueryDefintion alloc]init];
    query.driverCode = [UserInforMation manager].userCode;
    QueryOrder *sorting = [[QueryOrder alloc]init];
    sorting.field = @"pickingDate";
    sorting.direction = QUERYORDERDIRECTION_DESC;
    query.orders = (NSArray<QueryOrder> *)@[sorting];
    query.date = [NSString stringWithFormat:@"%@ 00:00:00",[[NSDate date] yearMonthDayString]];
    query.pageSize = PAGESIZE;
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(QUERYORDERBILL) WithRequestType:NetworkRequestWithPOST WithParameter:query WithReturnValueBlock:^(id returnValue) {
        
        dispatch_group_leave(group);
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            BusbillQueryResult *result = [[BusbillQueryResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.orderListArray = [NSMutableArray arrayWithArray:result.records];
        }else
        {
            [weakSelf SHOWPrompttext:returnValue[@"message"]];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        dispatch_group_leave(group);
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf SHOWPrompttext:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        dispatch_group_leave(group);
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf SHOWPrompttext:error.localizedDescription];
    }];
    //完成后回调
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [weakSelf RemoveMBProgressHUDLoding];
        NSLog(@"完成请求");
    });
}

- (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(RouteAnnotation*)routeAnnotation
{
    BMKAnnotationView* view = nil;
    switch (routeAnnotation.type) {
        case 0://起点
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"];
                view.image = LOADIMAGENAME(@"warehouse");
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 1://终点
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"];
                view.image = LOADIMAGENAME(@"warehouse");
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 3://已送达途径点
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            UIImage* image = [UIImage imageNamed:@"finishstore"];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
            
        }
            break;
        case 4:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
            
        }
            break;
        case 5://未送达途经点
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"waypoint_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            UIImage* image = LOADIMAGENAME(@"store");
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
        }
            break;
        default:
            break;
    }
    return view;
}


- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 5.0f;
        return polylineView;
    }
    return nil;
}

/**
 *返回驾乘搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果，类型为BMKDrivingRouteResult
 *@param error 错误号，@see BMKSearchErrorCode
 */
- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    [self RemoveMBProgressHUDLoding];
    NSMutableArray* array = [NSMutableArray arrayWithArray:_mapView.annotations];
    [array removeObject:self.userPointAnnotation];
    [_mapView removeAnnotations:array];
    array = [NSMutableArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        
        [self SuccessMBProgressView:@"路径规划成功" timeDelay:1 finish:nil];
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"仓库";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"仓库";
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加终点标注
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (int i=0; i<plan.wayPoints.count; i++) {
                BMKPlanNode* tempNode = plan.wayPoints[i];
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                //判断已送达、未送达情况
                BusbillDtl *model = self.sortingArray[i];
                item.type = [model.state isEqualToString:@"已完成"]?3:5;
                item.title = tempNode.name;
                [_mapView addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
    }else
    {
        [self ErrorMBProgressView:@"路径规划失败"];
    }
}

//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_mapView setVisibleMapRect:rect];
    _mapView.zoomLevel = _mapView.zoomLevel - 0.3;
}

#pragma mark - 发货单详情
- (void)invoiceViewClickAction:(UITapGestureRecognizer *)sender
{
    if (!self.selecteOrderBill) {
        [self SHOWPrompttext:@"请先选择送货单"];
    }else{
        //发货单详情
        OrderDetailsViewController *orderDetails = [self.storyboard instantiateViewControllerWithIdentifier:@"OrderDetailsViewController"];
        orderDetails.orderDetails = self.sortingArray;
        orderDetails.billNumber = self.selecteOrderBill.billNumber;
        WS(weakSelf);
        [orderDetails setReturnoffButtonClickBlock:^{
            [weakSelf turnoffButtonClickAction];
        }];
        [orderDetails setRefreshListDatasBlock:^{
            [weakSelf queryOrderBillDatasAndDepotInforMation];
        }];
        [orderDetails setRefreshPinStateBlock:^(NSArray *pinArray) {
            [weakSelf startDrawWayPointRoutepointArray:pinArray];
        }];
        self.invoiceDetailsView = orderDetails.view;
        self.invoiceDetailsView.frame = CGRectMake(0, self.view.mj_h, ScreenSize.width, orderDetails.view.mj_h);
        [self addChildViewController:orderDetails];
        [self.view addSubview:self.invoiceDetailsView];
        [UIView animateWithDuration:0.3 animations:^{
            self.invoiceDetailsView.frame = CGRectMake(0, 0, ScreenSize.width, self.view.mj_h);
        }];
    }
}

#pragma mark - 关闭发货单详情
- (void)turnoffButtonClickAction
{
    [UIView animateWithDuration:0.3 animations:^{
       CGRect frame = self.invoiceDetailsView.frame;
        frame.origin.y = self.view.mj_h;
        self.invoiceDetailsView.frame = frame;
    }completion:^(BOOL finished) {
        [self.invoiceDetailsView removeFromSuperview];
    }];
}

#pragma mark - 发货单列表
- (IBAction)orderListButtonClickAction:(UIButton *)sender {
   
    if (!self.orderListArray.count) {
        [self SHOWPrompttext:@"暂无送货单"];
    }else
    {
        //发货单列表
        OrderListViewController *orderList = [self.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
        orderList.datasArray = self.orderListArray;
        orderList.indexPath = self.selectIndexPath;
        WS(weakSelf);
        [orderList setReturnoffButtonClickBlock:^{
            [weakSelf turnoffListButtonClickAction];
        }];
        [orderList setSelectOrderClickBlock:^(Busbill *order,NSIndexPath *indexPath) {
            
            weakSelf.selectIndexPath = indexPath;
            weakSelf.selecteOrderBill = order;
            [weakSelf turnoffListButtonClickAction];
            weakSelf.invoiceInformationlabel.text = [NSString stringWithFormat:@"%@(单号:%@)",order.busInfo,order.billNumber];
            [weakSelf sortingCoordinates:order.billNumber];
        }];
        self.orderListView = orderList.view;
        self.orderListView.frame = CGRectMake(0, self.view.mj_h, ScreenSize.width, orderList.view.mj_h);
        [self addChildViewController:orderList];
        [self.view addSubview:self.orderListView];
        [UIView animateWithDuration:0.3 animations:^{
            self.orderListView.frame = CGRectMake(0, 0, ScreenSize.width, self.view.mj_h);
        }];
    }
}

#pragma mark - 关闭发货单详情
- (void)turnoffListButtonClickAction
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.orderListView.frame;
        frame.origin.y = self.view.mj_h;
        self.orderListView.frame = frame;
    }completion:^(BOOL finished) {
        [self.orderListView removeFromSuperview];
    }];
}


#pragma mark - 绘点排序
- (void)sortingCoordinates:(NSString *)orderBillNumber
{
    WS(weakSelf);
    [self CreateMBProgressHUDLoding:@"计算路径中"];
    NSString *urlString = [NSString stringWithFormat:SERVERREQUESTURL(ORDERSORTING),orderBillNumber,@"depot"];
    NSString *utf8String = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:utf8String WithRequestType:NetworkRequestWithGET WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            NSMutableArray *sortingArray = [NSMutableArray array];
            [returnValue[@"data"] enumerateObjectsUsingBlock:^(id  _Nonnull dict, NSUInteger idx, BOOL * _Nonnull stop) {
                BusbillDtl *details = [[BusbillDtl alloc]initWithDictionary:dict error:nil];
                [sortingArray addObject:details];
            }];
            weakSelf.sortingArray = sortingArray;
            [weakSelf startDrawWayPointRoutepointArray:sortingArray];
        }else
        {
            [weakSelf SHOWPrompttext:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf SHOWPrompttext:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf SHOWPrompttext:error.description];
    }];
}



@end
