//
//  PlayerViewController+otherDelegate.m
//  隐私保护
//
//  Created by xd h on 2023/10/13.
//

#import "PlayerViewController+otherDelegate.h"
#import "RCCommandHelp.h"
#import "couldPhoneBaseInfoModel.h"
#import "cachesFileManager.h"
#import "couldphoneSysInfoModel.h"
#import "TvStatusModel.h"
#import "HWVersionModel.h"
#import <MJExtension.h>
#import "HaveNewVersionView.h"
#import "connectDeviceManager.h"
#import "PlayerViewController+downloadFile.h"
#import "downloadManager.h"
#import "uploadFileManager.h"
#import "cloudPhoneExtraFileListModel.h"
#import "AppDelegate.h"
#import "cachesFileManager.h"
#import "extraMediaEventModel.h"
#import "USBInsertPopView.h"
#import "commandSendCheckModel.h"

@implementation PlayerViewController (otherDelegate)

#pragma mark   ComontAlretViewControllerDelegate
- (void)CommonAlertokBtnClickPressed{
    //HLog("11111");
    
    if(self->logoutAlertVC){
        self->logoutAlertVC = nil;
    }
    
    self.isLoginAgainType = YES;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:lockBypwdNotification object:nil];
}
- (void)CommonAlertCancelBtnClickPressed{
    HLog("强制退出app");
    
    exit(0);/*强制退出app*/
}

- (void)checkVersionFun
{
    [self getVersion];
}

#pragma mark- 网络请求
- (void)getVersion {
    
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    [paraDict setValue:@"ios" forKey:@"type"];
    [paraDict setValue:@"skyworth" forKey:@"source"];
    
    [[netWorkManager shareInstance] CommonGetWithCallBackCode:upgradeNewVersion Parameters:paraDict success:^(id  _Nonnull responseObject) {
        //HLog(@"%@", responseObject);

      SuperModel *model = [[SuperModel alloc] initWithDictionary:responseObject error:nil];

       if (model.status == 0) {

           HWVersionModel *model = [HWVersionModel mj_objectWithKeyValues:responseObject[@"data"]];
           [self checkVersion:model];
       }
       else
       {
           //[[iToast makeText:model.msg] show];
       }

    } failure:^(NSError * _Nonnull error) {
      HLog(@"%@", error);
    }];
}

- (void)checkVersion:(HWVersionModel*)versionModel {
//  NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *newVersion = [versionModel.versionNumber stringByReplacingOccurrencesOfString:@"v" withString:@""];  //去掉v
//    HLog(@"%@---%@", newVersion, currentVersion);
    if ([currentVersion compare:newVersion options:NSNumericSearch] == NSOrderedSame) { // 本地版本号 == 服务器版本号
    }else if ([currentVersion compare:newVersion options:NSNumericSearch] == NSOrderedDescending) { // 本地版本号 > 服务器版本号 （异常情况）
        [HWDataManager setBoolWithKey:Const_haveVersion value:NO];
    }else { // 本地版本号 < 服务器版本号 (有新版本)
        [self showNewVersion:versionModel];
        [HWDataManager setBoolWithKey:Const_haveVersion value:YES];
    };
}

#pragma mark 需要强制重启
- (void)updateForceStartFun{
    
    
    NSString* curSn = [connectDeviceManager shareInstance].DeviceThirdIdMod.data.sn;
    
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    [paraDict setValue:curSn forKey:@"sn"];
    [paraDict setValue:[NSNumber numberWithBool:YES] forKey:@"isForceStart"];
    
    [[netWorkManager shareInstance] CommonPostCallBackCode:updateForceStart Parameters:paraDict success:^(id  _Nonnull responseObject) {
        
      SuperModel *model = [[SuperModel alloc] initWithDictionary:responseObject error:nil];

       if (model.status == 0) {
          
       }
       else
       {
           
       }

    } failure:^(NSError * _Nonnull error) {
       HLog(@"%@", error);
    }];
}

- (void)showNewVersion:(HWVersionModel*)versionModel {
    
    HaveNewVersionView *haveNewVersionView = [HaveNewVersionView shardInstance];
    if (haveNewVersionView.isShow) {
        return;
    }
    haveNewVersionView.versionModel = versionModel;
    haveNewVersionView.isContinueCheckAlert = NO; // 是否继续走下一步弹窗检测流程
    [haveNewVersionView setBackgroundColor:RGBACOLOR(0, 0, 0, 0.5)];
    [[iTools getKeyWindow] addSubview:haveNewVersionView];
    haveNewVersionView.isShow = YES;
    
    if(!versionModel.necessary){
        haveNewVersionView.deleteBtn.hidden = NO;
    }
    
    [haveNewVersionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    haveNewVersionView.alpha = 0.0;

    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^ {
                haveNewVersionView.alpha = 1.0;
                KyoLog(@"in animate start");
            } completion:^(BOOL finished) {
                KyoLog(@"in animate completion");
    }];
}


- (void)getCouldPhoneBaseInfoResponseFun:(NSDictionary *)dataDict
{
    couldPhoneBaseInfoModel *model = [[couldPhoneBaseInfoModel alloc] initWithDictionary:dataDict error:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:getCouldPhoneBaseInfoNotification object:model];
}

- (void)getCouldPhoneSysInfoResponseFun:(NSDictionary *)dataDict{
    couldphoneSysInfoModel *model = [[couldphoneSysInfoModel alloc] initWithDictionary:dataDict error:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:getCouldPhoneSysInfoNotification object:model];
    
    NSString * predatestr = [HWDataManager getObjectWithKey:Const_did_show_image_version_date];
    
    NSString *datestr = [iTools getNowDateString];
    
    if(predatestr && [predatestr isEqualToString:datestr]){
        return;
    }
    
    NSString *hostImgVer = model.data.data.hostImgVer;
    
    if (!hostImgVer || hostImgVer.length < 3) {
        //[self showImageViewRenewTipViewFun];
        return;
    }
    
    NSArray *versionArr = [hostImgVer componentsSeparatedByString:@"."];
    
    if(versionArr.count >= 2)
    {
        NSString * oneStr = versionArr[0];
        NSString * twoStr = versionArr[1];
        
        if(oneStr.integerValue >=1 && twoStr.integerValue >=2){
            return;
        }
    }
    
    
    [self showImageViewRenewTipViewFun];
}

- (void)getCouldPhoneTvStatusResponseFun:(NSDictionary *)dataDict
{
    TvStatusModel *model = [[TvStatusModel alloc] initWithDictionary:dataDict error:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:getCouldPhoneTvStatusNotification object:model];
    
    if(![model.msg containsString:@"PushStreamBActivity"])
    {
        return;
    }
    
    UIViewController*topVc = self.navigationController.viewControllers.lastObject;
    if([topVc isKindOfClass:[PlayerViewController class]]){
        [[iToast makeText:NSLocalizedString(@"tv_p2p_ing",nil)] show];
    }
}

- (void)showImageViewRenewTipViewFun
{
    imageVersionRenewTipView * RenewTipView = [[imageVersionRenewTipView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
    [self.view addSubview:RenewTipView];
    [self.view bringSubviewToFront:RenewTipView];
}

- (void)createFolderBeginNotFun:(NSNotification *)notification
{
    NSString *folderName = [notification object];
    
    if(folderName && folderName.length >0){
        NSString * commandStr = [RCCommandHelp applyForCreateFolderwithFolderName:folderName];
        [self.commandChannelManager rc_sendData:commandStr];
    }
}

- (void)createFolderResponseFun:(NSDictionary *)dataDict
{
    couldPhoneCommonModel *model = [[couldPhoneCommonModel alloc] initWithDictionary:dataDict error:nil];
    
    if(model){
        NSNumber *curNum = [NSNumber numberWithInteger:model.status];
        [[NSNotificationCenter defaultCenter] postNotificationName:createFolderDoneNotification object:curNum];/*发送通知*/
    }
}

- (void)getFolderListBeginNotFun:(NSNotification *)notification
{
    NSString * commandStr = [RCCommandHelp getCreateFolderList];
    [self.commandChannelManager rc_sendData:commandStr];
}

- (void)getFolderListResponseFun:(NSDictionary *)dataDict
{
    [[NSNotificationCenter defaultCenter] postNotificationName:getFolderListDoneNotification object:dataDict];/*发送通知*/
}


- (void)searchFileListBeginFun:(NSNotification *)notification
{
    NSMutableDictionary *objectDict = [notification object];
    NSNumber *curNum = @1;
    
    if ([[objectDict allKeys] containsObject:@"type"]) {
        curNum = [objectDict objectForKey:@"type"];
    }
    
    NSString *pathStr = @"";
    
    if ([[objectDict allKeys] containsObject:@"path"]) {
        pathStr = [objectDict objectForKey:@"path"];
    }
    
    NSString *fileType = @"video";
    
    if(curNum.boolValue)
    {
        fileType = @"jpg";
    }
    
    NSString * commandStr = [RCCommandHelp searchCouldPhoneFilewithType:fileType withPath:pathStr];
    [self.commandChannelManager rc_sendData:commandStr];
}
- (void)searchFileListResponseFun:(NSDictionary *)dataDict
{
    [[NSNotificationCenter defaultCenter] postNotificationName:searchFileListDoneNotification object:dataDict];/*发送通知*/
}


// NSData转int
- (int)data2Int:(NSData *)data{
    Byte *byte = (Byte *)[data bytes];
    // 有大小端模式问题？
     return (byte[0] << 24) + (byte[1] << 16) + (byte[2] << 8) + (byte[3]);
}


- (void)handleDownloadResponseFunBy:(id)message
{
    NSData *curData = (NSData *)message;
    
//    if(curData.length < 20){
//        return;
//    }
    
    //head
    NSData *headData = [curData subdataWithRange:NSMakeRange(0, 1)];
    char head = 0;//104;
    [headData getBytes:&head length:sizeof(head)];
    //HLog(@"head: %d",head);
    
    //msgType  0x11(17)
    NSData *msgTypeData = [curData subdataWithRange:NSMakeRange(1, 1)];
    char msgType = 0;
    [msgTypeData getBytes:&msgType length:sizeof(msgType)];
    //HLog(@"msgType: %d",msgType);
    
    //taskId  6位字符串
    NSData *taskIdData = [curData subdataWithRange:NSMakeRange(2, 6)];
    NSString* taskIdStr = [[NSString alloc] initWithData:taskIdData encoding:NSUTF8StringEncoding];;
    HLog(@"taskId: %@",taskIdStr);
    
    if(curData.length <= 15){
        HLog(@"消息长度不对不处理");
        return;
    }
    
    //datalen
    NSData *datalenData = [curData subdataWithRange:NSMakeRange(8, 4)];
    int datalen = [self data2Int:datalenData];
    //HLog(@"datalen: %d",datalen);

    //curNum
    NSData *curNumData = [curData subdataWithRange:NSMakeRange(12, 4)];
    int curNum = [self data2Int:curNumData];;
    //HLog(@"curNum: %d",curNum);
    
    //totalNum
    NSData *totalNumData = [curData subdataWithRange:NSMakeRange(16, 4)];
    int totalNum = [self data2Int:totalNumData];
    //HLog(@"totalNum: %d",totalNum);
    
    BOOL isDownloadDone = curNum == totalNum ? YES : NO;
    
    HLog(@"taskUid:%@ curNum:%d totalNum: %d datalen:%d isDownloadDone:%d",taskIdStr,curNum,totalNum,datalen -8,isDownloadDone);
    
    if(curData.length <= 23){
        //data 的位置 装 成功或者失败
        NSData *failTypeData = [curData subdataWithRange:NSMakeRange(20, 1)];
        //0xcc (204)失败 0xcd (205)文件不存在 0xdd (221)完成  0xbb 187 完成
        __block Byte failType;
        [failTypeData getBytes:&failType length:sizeof(failType)];
        
        if(taskIdStr && [taskIdStr isEqualToString:self.downloadFileTaskUid]){
            
            if(failType == 0xcc || failType == 0xcf){
                [[downloadManager shareInstance] DownloadFileFailOneFileFun];
            }
            else if(failType == 0xcd ){
                [[downloadManager shareInstance] suspendDownloadFileFun:YES];
                NSString *tipStr = NSLocalizedString(@"disk_not_find_tip",nil);
                mainBlock(^{
                    [[iToast makeText:tipStr] show];
                });
            }
            else if(failType == 0xdd || failType == 0xbb){
                [self downloadFileFunServiceResponseFun:[NSData new] with:YES];
            }
            else{
                HLog(@"下载数据未知错误");
                [[downloadManager shareInstance] DownloadFileFailOneFileFun];
            }
        }
        
        return;
    }
    
    if(curData.length <= (20 + datalen - 8)){
        HLog(@"下载数据解析出错了");
        return;
    }
    
    NSData *fileData = [curData subdataWithRange:NSMakeRange(20, datalen-8)];

    if([taskIdStr isEqualToString:self.downloadFileTaskUid]){
        [self downloadFileFunServiceResponseFun:fileData with:NO];
    }
    
}

- (void)checkAllTaskFun
{
    //处理相册备份
    [[backupsFileManager shareInstance] checkReBackupsFileFun];
    
    [[uploadFileManager shareInstance] checkReUploadFileFun];
    [[downloadManager shareInstance] checkReDownloadFileFun];
    
    [self checkCommandSendTaskFun];
}

-(void)addCommandSendTaskFunWithType:(NSString*)type WithCommandStr:(NSString*)commandStr
{
    if(!commandSendCheckArr){
        commandSendCheckArr = [NSMutableArray new];
    }
    
    BOOL didAddType = NO;
        
    for (commandSendCheckModel *model in commandSendCheckArr) {
        if([model.type isEqualToString:type]){
            didAddType = YES;
            model.reSendNum = 0;
            model.sendTimerStamp = [iTools getNowTimeStamp];
            break;
        }
    }
        
    if(!didAddType){
        commandSendCheckModel *model = [commandSendCheckModel new];
        model.commandStr = commandStr;
        model.type = type;
        model.reSendNum = 0;
        model.sendTimerStamp = [iTools getNowTimeStamp];
        [commandSendCheckArr addObject:model];
    }
    
}

-(void)checkCommandSendTaskFun
{
    if(commandSendCheckArr && commandSendCheckArr.count >0){
        for (commandSendCheckModel *model in commandSendCheckArr) {
            if(model.reSendNum < 5){
                model.reSendNum ++;
                if(model.commandStr){
                    [self send_data:model.commandStr];
                    
                    HLog(@"\n\n\n任务重发 重发次数:%ld 指令:%@\n\n\n",model.reSendNum,model.commandStr);
                }
                
                if([model.type isEqualToString:@"offline_notification"]){
                    model.reSendNum = 1;//只要不收到
                }
            }
        }
    }
}

-(void)deleteCommandSendTaskFunWith:(NSString*)type
{
    if(commandSendCheckArr && commandSendCheckArr.count >0){
        
        NSArray *taskArr = [NSArray arrayWithArray:commandSendCheckArr];
        
        for (commandSendCheckModel *model in taskArr) {
            if([type isEqualToString:model.type]){
                [commandSendCheckArr removeObject:model];
            }
        }
    }
}

- (void)getExtraFilesResponseFun:(NSDictionary *)dataDict
{
    cloudPhoneExtraFileListModel *model = [[cloudPhoneExtraFileListModel alloc] initWithDictionary:dataDict error:nil];
    ksharedAppDelegate.cloudPhoneExtraFileListMod = model;
}

- (void)saveLastImageFun
{
    UIImage *image = [UIImage imageWithCIImage:saveCIImage];
    if(image){   //执行返回最后一帧
        //[mPlayerView.showImageView setImage:image];
        
        NSString *filePath = kSHPath_cloudPhone_last_image;
        NSString *folderPath = [kSHPath_cloudPhone_last_image stringByDeletingLastPathComponent];
        [[NSFileManager defaultManager] removeItemAtPath:folderPath error:nil];
        [cachesFileManager getCreateFilePath:folderPath];
        NSData*imageData = UIImagePNGRepresentation(image);
        
        BOOL ret = [imageData writeToFile:filePath atomically:NO];
        
        if (ret) {
        }
    }
}

- (void)readLastImageFun
{
    NSString *filePath = kSHPath_cloudPhone_last_image;
    UIImage *image = [UIImage imageWithContentsOfFile:filePath];
    if(image && !saveCIImage){
        [mPlayerView.showImageView setImage:image];
    }
}

- (void)getExtraMediaEventResponseFun:(NSDictionary *)dataDict
{
    extraMediaEventModel *model = [[extraMediaEventModel alloc] initWithDictionary:dataDict error:nil];
    
    NSString *tip = nil;
    if(model.data.event == 0){
        tip = NSLocalizedString(@"disk_insertion_tip",nil);
        [self showInsertPopViewFun:model.data.name];
    }
    else if(model.data.event == 1){
        tip = NSLocalizedString(@"disk_extract_tip",nil);
    }
    else if(model.data.event == 2){
        tip = NSLocalizedString(@"disk_save_extract_tip",nil);
    }
    
    NSString *totalTips = [[NSString alloc] initWithFormat:@"%@%@",model.data.name,tip];
    
    mainBlock(^{
        [[iToast makeText:totalTips] show];
    });
}

#pragma mark 显示插入UI弹框
- (void)showInsertPopViewFun:(NSString*)name
{
    if(self->curUSBInsertPopV){
        [self->curUSBInsertPopV removeFromSuperview];
        self->curUSBInsertPopV = nil;
    }
    
    self->curUSBInsertPopV = [[USBInsertPopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) withName:name];
    
    UIViewController*lastVC =  self.navigationController.viewControllers.lastObject;
    //[[iTools getKeyWindow] addSubview:self->curUSBInsertPopV];
    [lastVC.view addSubview:self->curUSBInsertPopV];
}

@end
