//
//   DDMATrackManager.m
//   DDMAMapKit_Private
//   Created by DDIsFriend on 2023/3/5.
    

#import "DDMATrackManager.h"
#import <DDLogKit_Private/DDOCLog.h>

@interface DDMATrackManager ()<AMapTrackManagerDelegate>
@property (nonatomic, strong)AMapTrackManager *trackManager;

@end

@implementation DDMATrackManager
// MARK: <Class Initialize>
+ (void)startWithAppKey:(nullable NSString *)appKey{
    [[AMapServices sharedServices] setEnableHTTPS:YES];
    [AMapServices sharedServices].apiKey = appKey;
}

+ (instancetype)shareManager{
    static DDMATrackManager *_Nullable _manager = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        _manager = [[self alloc] initWithSuper];
    });
    return _manager;
}

- (instancetype)initWithSuper{
    self = [super init];
    if (self == nil) return nil;
    
    return self;
}

- (instancetype)init{
    @throw [[NSException alloc] initWithName:NSGenericException reason:@"'init' is unavailable,please use 'shareManager' instead." userInfo:nil];
}

// MARK: <Start Service>
- (void)initTraceService{
    NSAssert(self.serviceID != nil, @"猎鹰serviceID = nil");
    NSAssert(self.fullAccuracyPurpose != nil, @"请设置fullAccuracyPurpose的值");
    if (self.serviceID == nil) {
        return;
    }
    if (self.fullAccuracyPurpose == nil) {
        return;
    }
    
    AMapTrackManagerOptions *option = [[AMapTrackManagerOptions alloc] init];
    option.serviceID = self.serviceID; //Service ID 需要根据需要进行修改
        
    //初始化AMapTrackManager
     self.trackManager = [[AMapTrackManager alloc] initWithOptions:option];
     self.trackManager.delegate = self;
    [self.trackManager setPausesLocationUpdatesAutomatically:NO];
}

//查询终端是否存在
- (void)queryTerminal:(NSString *)terminalName{
    AMapTrackQueryTerminalRequest *request = [[AMapTrackQueryTerminalRequest alloc] init];
    request.serviceID = self.serviceID;
    request.terminalName = terminalName;
    [self.trackManager AMapTrackQueryTerminal:request];
}

//查询终端结果
- (void)onQueryTerminalDone:(AMapTrackQueryTerminalRequest *)request response:(AMapTrackQueryTerminalResponse *)response
{
    //查询成功
    if ([[response terminals] count] > 0) {
        //查询到结果，使用 Terminal ID
        NSString *terminalID = [[[response terminals] firstObject] tid];
        
        DDLog(@"--------------------------------LBS查询终端成功,terminalID = %@--------------------------------\n--------------------------------准备启动服务--------------------------------",terminalID);

        //启动上报服务(service id)，参考下一步
        self.terminalID = terminalID;
        [self startService];
    }
    else {
        DDLog(@"--------------------------------LBS查询终端为空--------------------------------\n--------------------------------准备创建终端--------------------------------");
        //查询结果为空，创建新的terminal
        [self addTerminal:request.terminalName];
    }
}

// 创建终端
- (void)addTerminal:(NSString *)terminalName{
    AMapTrackAddTerminalRequest *addRequest = [[AMapTrackAddTerminalRequest alloc] init];
    addRequest.serviceID = self.trackManager.serviceID;
    addRequest.terminalName = terminalName;
    [self.trackManager AMapTrackAddTerminal:addRequest];
}

//创建终端结果
- (void)onAddTerminalDone:(AMapTrackAddTerminalRequest *)request response:(AMapTrackAddTerminalResponse *)response {
    DDLog(@"--------------------------------LBS创建终端成功--------------------------------\n--------------------------------准备开启服务--------------------------------");
    //创建terminal成功
    NSString *terminalID = [response terminalID];
    
    //启动上报服务(service id)，参考下一步
    self.terminalID = terminalID;
    [self startService];
}

//错误回调
- (void)didFailWithError:(NSError *)error associatedRequest:(id)request {
    if ([request isKindOfClass:[AMapTrackQueryTerminalRequest class]]) {
        //查询参数错误
        DDLog(@"--------------------------------LBS查询终端失败--------------------------------");
    }
    
    if ([request isKindOfClass:[AMapTrackAddTerminalRequest class]]) {
        //创建terminal失败
        DDLog(@"--------------------------------LBS创建终端失败--------------------------------");
    }
    
    if ([request isKindOfClass:[AMapTrackAddTrackRequest class]]) {
        //创建轨迹失败
        DDLog(@"--------------------------------LBS创建轨迹失败--------------------------------");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryLastPointRequest class]]) {
        //查询失败
        DDLog(@"--------------------------------LBS查询最后位置失败--------------------------------");
    }
    
    if ([request isKindOfClass:[AMapTrackQueryTrackDistanceRequest class]]) {
        //查询失败
        DDLog(@"--------------------------------LBS查询距离失败--------------------------------");
    }
    
    if (self.queryFailWithErrorOnDone) {
        self.queryFailWithErrorOnDone(error, request);
    }
}

//创建轨迹
- (void)addTrackID{
   AMapTrackAddTrackRequest *request = [[AMapTrackAddTrackRequest alloc] init];
   request.serviceID = self.trackManager.serviceID;
   request.terminalID = self.trackManager.terminalID;
   [self.trackManager AMapTrackAddTrack:request];
}

- (void)onAddTrackDone:(AMapTrackAddTrackRequest *)request response:(AMapTrackAddTrackResponse *)response
{
    //创建轨迹成功，开始采集
    self.trackID = response.trackID;
    
    DDLog(@"---------------------------------创建轨迹成功----------------------------------")
    
    if (self.addTrackOnDone != nil) {
        self.addTrackOnDone(request, response);
    }
}

- (void)startService{
    if (self.isServing == false) {
        // 当开启服务时，设置允许后台定位
        [self.trackManager setAllowsBackgroundLocationUpdates:YES];
        AMapTrackManagerServiceOption *serviceOption = [[AMapTrackManagerServiceOption alloc] init];
        serviceOption.terminalID = self.terminalID;//Terminal ID 需要根据需要进行修改
        [self.trackManager startServiceWithOptions:serviceOption];
    }
}

- (void)stopService{
    if (self.isServing == true) {
        [self.trackManager stopService];
    }
}

- (void)startGatherAndPack{
    if (self.trackID != nil) {
        self.trackManager.trackID = self.trackID;
        NSLog(@"轨迹id---------------%@",self.trackID);
        DDLog(@"---------------------------------设置轨迹成功----------------------------------")
    }
    [self.trackManager startGatherAndPack];
}

- (void)stopGatherAndPack{
    [self.trackManager stopGaterAndPack];
}

//service 开启结果回调
- (void)onStartService:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        DDLog("--------------------------------开启猎鹰服务成功--------------------------------\n--------------------------------准备采集--------------------------------");
        // 已开启服务成功
        self.isServing = YES;
       
    } else {
        //开始服务失败
        DDLog("--------------------------------开启猎鹰服务失败--%ld",errorCode);
    }
    if (self.startServiceOnDone) {
        self.startServiceOnDone(errorCode);
    }
}

// 关闭猎鹰服务
- (void)onStopService:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        //关闭猎鹰服务成功
        self.isServing = false;
        
        DDLog(@"--------------------------------关闭猎鹰服务成功--------------------------------");
    } else {
        //关闭猎鹰服务失败
        DDLog(@"--------------------------------关闭猎鹰服务失败--------------------------------");
    }
    
    if (self.stopServiceOnDone) {
        self.stopServiceOnDone(errorCode);
    }
}

//gather 开启结果回调
- (void)onStartGatherAndPack:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        //开始采集成功
        self.isGathering = YES;
        DDLog(@"--------------------------------开始猎鹰采集成功--------------------------------");
    } else {
        //开始采集失败
        DDLog(@"--------------------------------开始猎鹰采集失败--------------------------------");
    }
    
    if (self.startGatherAndPackOnDone) {
        self.startGatherAndPackOnDone(errorCode);
    }
}

// 关闭采集
- (void)onStopGatherAndPack:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        //关闭采集成功
        self.isGathering = NO;
        DDLog(@"--------------------------------关闭猎鹰采集成功--------------------------------");
    } else {
        //关闭采集失败
        DDLog(@"--------------------------------关闭猎鹰采集失败--------------------------------");
    }
    
    if (self.stopGatherAndPackOnDone) {
        self.stopGatherAndPackOnDone(errorCode);
    }
}

// 查询最后的位置
- (void)queryLastPointWith:(nullable NSString *)trackID{
    AMapTrackQueryLastPointRequest *request = [[AMapTrackQueryLastPointRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = self.trackManager.terminalID;
    if (trackID != nil) {
        request.trackID = trackID;
    }
    [self.trackManager AMapTrackQueryLastPoint:request];
}

// 查询最后的位置结果
- (void)onQueryLastPointDone:(AMapTrackQueryLastPointRequest *)request response:(AMapTrackQueryLastPointResponse *)response
{
    if (self.queryLastPointOnDone != nil) {
        self.queryLastPointOnDone(request,response);
    }
}

- (void)queryTrackDistanceWith:(long long)startTime endTime:(long long)endTime trackID:(nullable NSString *)trackID{
    AMapTrackQueryTrackDistanceRequest *request = [[AMapTrackQueryTrackDistanceRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = self.trackManager.terminalID;
    request.startTime = startTime;
    request.endTime = endTime;
    request.correctionMode = @"driving";
    if (trackID != nil) {
        request.trackID = self.trackManager.trackID;
    }
    DDLog(@"--------------------------------当前猎鹰查询distance:\n起始时间:%lld\n结束时间:%lld--------------------------------",startTime,endTime);
    [self.trackManager AMapTrackQueryTrackDistance:request];
}

- (void)onQueryTrackDistanceDone:(AMapTrackQueryTrackDistanceRequest *)request response:(AMapTrackQueryTrackDistanceResponse *)response
{
    //查询成功
    NSLog(@"--------------------------------onQueryTrackDistanceDone%@--------------------------------", response.formattedDescription);
    if (self.queryTrackDistanceOnDone != nil) {
        DDLog(@"--------------------------------当前猎鹰查询distance:%lu--------------------------------",(unsigned long)response.distance);
        self.queryTrackDistanceOnDone(request, response);
    }
}

- (void)changeGatherAndPackTimeInterval:(NSInteger)gatherTimeInterval packTimeInterval:(NSInteger)packTimeInterval{
    [self.trackManager changeGatherAndPackTimeInterval:gatherTimeInterval packTimeInterval:packTimeInterval];
}

- (BOOL)setLocalCacheMaxSize:(NSInteger)cacheMaxSize{
    return [self.trackManager setLocalCacheMaxSize:50];
}

// 获取精准定位
- (void)amapTrackManager:(nonnull AMapTrackManager *)manager doRequireTemporaryFullAccuracyAuth:(nonnull CLLocationManager *)locationManager completion:(nonnull void (^)(NSError * _Nonnull))completion API_AVAILABLE(ios(14.0)){
    [locationManager requestTemporaryFullAccuracyAuthorizationWithPurposeKey:self.fullAccuracyPurpose completion:^(NSError *error){
         if(completion){
            completion(error);
         }
    }];
}
@end
