//
//  SMTakeImageViewController.m
//  SkinMagnifier
//
//  Created by nana on 2020/11/17.
//

#import "SMTakeImageViewController.h"
#import "SMEditPositionNameView.h"
#import "SMReportViewController.h"
#import "DKWIFIVideoView.h"
#import "DKSocket.h"
#import "DKCmdTool.h"
#import "SMCheckOilBGView.h"
#import "SMLinkDeviceView.h"
#import "SMAIImageTool.h"
#import <SDImageCache.h>


@interface SMTakeImageViewController ()

@property(nonatomic, strong)UIView *dengBGView;
@property(nonatomic, strong)NSMutableArray *dengTypeBtnArray;
@property(nonatomic, weak)DKWIFIVideoView *videoView;
@property(nonatomic, strong)dispatch_source_t timer ;
//@property(nonatomic, strong)NSMutableArray *shuifenArray;
@property(nonatomic, strong)NSMutableDictionary *weiduDcit;
@property(nonatomic, weak)UIButton *takeImageBtn;
@property(nonatomic, weak)UIButton *dengBtn;
@end

static bool netWorkStatus;

@implementation SMTakeImageViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [SVProgressHUD dismiss];
    if (self.navigationController) {
        NSArray *childVC = self.navigationController.viewControllers;
        NSMutableArray *xinVC = [[NSMutableArray alloc] init];
        for (int i = 0 ; i < childVC.count; i++) {
            UIViewController *vc = childVC[i];
            if ([NSStringFromClass([vc class]) isEqualToString:@"SMCreateClientViewController"] ) {
            }else {
                [xinVC addObject:vc];
            }
        }
        self.navigationController.viewControllers = xinVC;
    }


    
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"shuifen" ofType: @"json"];
//    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
//    NSError * error;
//    NSDictionary *typeDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//    _shuifenArray = typeDict[@"category"];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"weidu" ofType: @"json"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    NSError * error;
    _weiduDcit = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    UIEdgeInsets e =  window.safeAreaInsets;
    

    DKWIFIVideoView *videoView = [[DKWIFIVideoView alloc ] init];

    CGAffineTransform translation = CGAffineTransformMakeTranslation(0,0);
    videoView.webView.transform = CGAffineTransformRotate(translation, M_PI_2);
    CGFloat vh = self.view.bounds.size.height+20;
    CGFloat w = 1920.0*(vh/1080.0);
    CGFloat h = vh;
    videoView.frame =  CGRectMake(self.view.bounds.size.width - w+((e.top+e.bottom) /2.0), 0,w,h);
    _videoView = videoView;
    [self.view addSubview:videoView];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [[DKSocket share] connectHost:@"192.168.168.1" port:8336];
        [DKSocket share].heartbeatData = dataWithCmd(JFDeviceSendCommandFirmwareVersion);
    });

    @weakify(self);
    [DKSocket share].checkNetWorkBlock = ^(BOOL xx) {
        @strongify(self);
        netWorkStatus = xx;
    };

    
    
    
    UIButton *dengBtn = [[UIButton alloc] init];
    _dengBtn = dengBtn;
    dengBtn.selected = YES;
    [dengBtn addTarget:self action:@selector(dengBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [dengBtn wb_setImageName:@"pz_icon_light"];
    [self.view addSubview:dengBtn];
    [dengBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(safaBottom(-45.5));
        make.left.mas_equalTo(35.5);
    }];
    
    
    
    
    
    
    UIButton *sfbtn  = [[UIButton alloc] init];
    [sfbtn addTarget:self action:@selector(sfbtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [sfbtn setAttributedTitle:createAttString(@"下限", 14, rgba(255, 0, 0, 1)) forState:UIControlStateNormal];
    [sfbtn setBackgroundImage:[UIImage wb_imageWithColor:rgba(0, 255, 0, 1) size:CGSizeMake(40, 40)] forState:UIControlStateNormal];
    [self.view addSubview:sfbtn];
    [sfbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(safaBottom(-36.5));
        make.right.mas_equalTo(-5);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    UIButton *sfhhhhhbtn  = [[UIButton alloc] init];
    [sfhhhhhbtn addTarget:self action:@selector(sfbtnhhhhClick:) forControlEvents:UIControlEventTouchUpInside];
    [sfhhhhhbtn setAttributedTitle:createAttString(@"上限", 14, rgba(255, 0, 0, 1)) forState:UIControlStateNormal];
    [sfhhhhhbtn setBackgroundImage:[UIImage wb_imageWithColor:rgba(0, 255, 0, 1) size:CGSizeMake(40, 40)] forState:UIControlStateNormal];
    [self.view addSubview:sfhhhhhbtn];
    [sfhhhhhbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(safaBottom(-36.5));
        make.right.mas_equalTo(-65);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    UIButton *sfhhbtn  = [[UIButton alloc] init];
    [sfhhbtn addTarget:self action:@selector(sfhhbtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [sfhhbtn setAttributedTitle:createAttString(@"水份", 14, rgba(255, 0, 0, 1)) forState:UIControlStateNormal];
    [sfhhbtn setBackgroundImage:[UIImage wb_imageWithColor:rgba(0, 255, 0, 1) size:CGSizeMake(40, 40)] forState:UIControlStateNormal];
    [self.view addSubview:sfhhbtn];
    [sfhhbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(safaBottom(-36.5));
        make.right.mas_equalTo(-125);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    
    
    UIButton *backBtn = [[UIButton alloc] init];
    backBtn.frame =CGRectMake(10, safaTop(20) , 38, 45);
    [backBtn wb_setImageName:@"nav_white_back"];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    UIButton *takeImageBtn = [[UIButton alloc] init];
    _takeImageBtn = takeImageBtn;
    [takeImageBtn addTarget:self action:@selector(takeImageClick:) forControlEvents:UIControlEventTouchUpInside];
    [takeImageBtn wb_setImageName:@"pz_button_xj"];
    [self.view addSubview:takeImageBtn];
    [takeImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(safaBottom(-36.5));
        make.centerX.mas_equalTo(0);
    }];
    
    self.dengBGView = [[UIView alloc] init];
    self.dengBGView.backgroundColor = rgba(51, 51, 51, 0.4);
    self.dengBGView.layer.cornerRadius =46/2;
    self.dengBGView.layer.masksToBounds = YES;
    [self.view addSubview:self.dengBGView];
    self.dengBGView.hidden = YES;
    [self.dengBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(dengBtn.mas_top).offset(-19);
        make.centerX.equalTo(dengBtn);
        make.size.mas_equalTo(CGSizeMake(46, 208));
    }];
//    self.dengBGView.frame = CGRectMake(36.5, self.view.bounds.size.height+(safaBottom(-110))-208, 46, 208);
    self.dengTypeBtnArray = [[NSMutableArray alloc] init];
    
    UIButton *riGBtn = [[UIButton alloc] init];
    riGBtn.tag = 1580;
    [riGBtn addTarget:self action:@selector(dengTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    [riGBtn wb_setImageName:@"pz_icon_rig"];
    [self.dengBGView addSubview:riGBtn];
    [riGBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(22);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];

    
    UIButton *wlBtn = [[UIButton alloc] init];
    [wlBtn wb_setImageName:@"pz_icon_wl"];
    wlBtn.tag = 1581;
    [wlBtn addTarget:self action:@selector(dengTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.dengBGView addSubview:wlBtn];
    [wlBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(riGBtn.mas_bottom).offset(17.5);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];

    UIButton *jhBtn = [[UIButton alloc] init];
    [jhBtn wb_setImageName:@"pz_icon_jh"];
    jhBtn.tag = 1582;
    [jhBtn addTarget:self action:@selector(dengTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.dengBGView addSubview:jhBtn];
    [jhBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wlBtn.mas_bottom).offset(17.5);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    UIButton *uvBtn = [[UIButton alloc] init];
    [uvBtn wb_setImageName:@"pz_icon_uv"];
    uvBtn.tag = 1583;
    [uvBtn addTarget:self action:@selector(dengTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.dengBGView addSubview:uvBtn];
    [uvBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(jhBtn.mas_bottom).offset(17.5);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    [self.dengTypeBtnArray addObjectsFromArray:@[riGBtn,wlBtn,jhBtn,uvBtn]];

    
    
    
    if (islinkDeviceWifi()) {
        [UIView showFromView:self.view text:@"请将放大镜对准拍摄位置，画面清晰即可拍照" afterDelay:2];
    }
    
    
}
- (void)sfbtnhhhhClick:(UIButton *)btn{
    NSData *sendDate= dataWithCmd(JFDeviceRecvCommandXiaoYanHeightWaterOil);
    @weakify(self);
    [[DKSocket share] sendData:sendDate completeBlock:^(NSData * _Nonnull response) {
        @strongify(self);
        if (!response) {
            [SVProgressHUD showInfoWithStatus:@"响应超时"];
            return;
        }
        JFDeviceSendCommand cmd;
        int outValue = 0;
        cmdWithData(response,&outValue, &cmd);
        if (outValue == 0) {
            [SVProgressHUD showInfoWithStatus:@"水分上限校验失败"];
        }else {
            [SVProgressHUD showInfoWithStatus:@"水分上限校验成功"];
        }
        
    }];
}
- (void)sfhhbtnClick:(UIButton *)btn {
    
    [btn setAttributedTitle:createAttString(@"水份", 14, rgba(255, 0, 0, 1)) forState:UIControlStateNormal];
    NSData *sendDate= dataWithCmd(JFDeviceRecvCommandCheckWaterOil);
//    @weakify(self);
    @weakify(btn);
    
    [[DKSocket share] sendData:sendDate completeBlock:^(NSData * _Nonnull response) {
        @strongify(btn);
//        @strongify(self);
        if (!response) {
            [SVProgressHUD showInfoWithStatus:@"响应超时"];
            return;
        }
        
        JFDeviceSendCommand cmd;
        int outValue = 0;
        cmdWithData(response,&outValue, &cmd);
        NSString *tipsString = [[NSString alloc] initWithFormat:@"%d",outValue];
        
        [btn setAttributedTitle:createAttString(tipsString, 14, rgba(255, 0, 0, 1)) forState:UIControlStateNormal];

    }];
    
}
- (void)backClick:(UIButton *)btn
{
    if (self.takeImageBtn.hidden == YES) {


      UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"正在检测中，确认退出吗？" message:@"" preferredStyle:UIAlertControllerStyleAlert];
      
      UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          [self backVC];
      }];
      
      UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      }];
      [alert addAction:cancleAction];
      [alert addAction:conform];
      
      [self presentViewController:alert animated:YES completion:nil];

    }else {
        [self backVC];
    }
    
  
}

- (void)backVC {
    NSArray *vcArray = self.navigationController.childViewControllers;
    for (int i = 0; i < vcArray.count; i++) {
        UIViewController  *sVC = vcArray[i];
        if ([NSStringFromClass([sVC class]) isEqualToString:@"SMCreateClientViewController"] ) {
            [self.navigationController popToViewController:vcArray[i-1] animated:YES];
            return;
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sfbtnClick:(UIButton *)btn {
    NSData *sendDate= dataWithCmd(JFDeviceRecvCommandXiaoYanWaterOil);
    @weakify(self);
    [[DKSocket share] sendData:sendDate completeBlock:^(NSData * _Nonnull response) {
        @strongify(self);
        if (!response) {
            [SVProgressHUD showInfoWithStatus:@"响应超时"];
            return;
        }    
        JFDeviceSendCommand cmd;
        int outValue = 0;
        cmdWithData(response,&outValue, &cmd);
        if (outValue == 0) {
            [SVProgressHUD showInfoWithStatus:@"水分下限校验失败"];
        }else {
            [SVProgressHUD showInfoWithStatus:@"水分下限校验成功"];
        }
        
    }];
    
    
}
- (void)setTask {
    
}
- (void)dengBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    self.dengBGView.hidden = btn.selected;
//    @weakify(self);
//    [[DKSocket share] sendData:dataWithCmd(JFDeviceRecvCommandCheckWaterOil) completeBlock:^(NSData * _Nonnull response) {
//        @strongify(self);
//
//        NSLog(@"%@",response);
//    }];
}





- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self lightUpOne];
//    if (islinkDeviceWifi()) {
//        NEHotspotConfiguration *hotspotConfig = [[NEHotspotConfiguration alloc]initWithSSID:WIFIName() passphrase:deviceWifiPWd() isWEP:NO];
//        hotspotConfig.joinOnce = YES;
//        [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
//            NSLog(@"wifi 连接成功");
//        }];
//    }
    

}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(lightUpOne) object:nil];
    
    [[DKSocket share] sendData:dataWithCmd(JFDeviceSendCommandLightsOFF) completeBlock:^(NSData * _Nonnull response) {

        
        
    }];
//    if (islinkDeviceWifi()) {
//        [[NEHotspotConfigurationManager sharedManager] removeConfigurationForSSID:WIFIName()];
//    }

}

-  (void)lightUpOne {
    @weakify(self);
    [[DKSocket share] sendData:dataWithCmd(JFDeviceSendCommandLightsRG) completeBlock:^(NSData * _Nonnull response) {
        @strongify(self);
        if (!response ) {
            [self performSelector:@selector(lightUpOne) withObject:nil afterDelay:5];
        }
        
    }];
}


- (void)dengTypeClick:(UIButton *)btn {
    @weakify(self);
    for (UIButton *xbtn in self.dengTypeBtnArray) {
        
        if ([xbtn isEqual:btn]) {
            xbtn.selected = YES;
            xbtn.userInteractionEnabled = NO;
            [[DKSocket share] sendData:dataWithCmd(btn.tag-1580) completeBlock:^(NSData * _Nonnull response) {
                @strongify(self);
            }];
            
        }else {
            xbtn.selected = NO;
            xbtn.userInteractionEnabled = YES;
        }

    }
}


- (void)takeImageClick:(UIButton *)btn {


    
    if (netWorkStatus == NO) {
        return;
    }

    
    self.dengBtn.hidden =YES;
    self.dengBGView.hidden = YES;
    
    btn.hidden = YES;
    NSArray *tipsTArray = [@"日光图,极化图,纹理图,UV图,日光图" componentsSeparatedByString:@","];
    @weakify(self);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLock *lock = [[NSLock alloc] init];
        NSMutableArray *imageArray = [[NSMutableArray alloc] init];
        for ( int i=0; i <5; i++) {

            [lock lock];
            if (i == 4) {
                [self checkOilAndArray:imageArray];
                [lock unlock];
                
                break;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *tipsT = [NSString stringWithFormat:@"%@拍摄中，请勿移动放大镜",tipsTArray[i]];
                [UIView showFromView:self.view text:tipsT afterDelay:3];
            });

            [[DKSocket share] sendData:dataWithCmd(i) completeBlock:^(NSData * _Nonnull response) {
                @strongify(self);

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.168.1:8888/?action=snapshot"]
                      cachePolicy:NSURLRequestUseProtocolCachePolicy
                      timeoutInterval:10.0];

                    [request setHTTPMethod:@"GET"];

                    NSURLSession *session = [NSURLSession sharedSession];
                    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if (!error) {
                                UIImage *xImage = [UIImage imageWithData:data];
                                if (!xImage) {
                                    [imageArray addObject:[self viewSnapshot:self.videoView withInRect:CGRectZero]];
                                }else {
                                    CGSize Iszie = xImage.size;
//
                                  UIImage *image3 = [xImage  sd_rotatedImageWithAngle:M_PI_2 fitSize:YES];
//
                                    [imageArray addObject:image3];
//                                    [imageArray addObject:[[self viewSnapshot:self.videoView withInRect:CGRectZero] sd_rotatedImageWithAngle:M_PI_2 fitSize:YES]];
//                                    [imageArray addObject:[self viewSnapshot:self.videoView withInRect:CGRectZero]];
                                }
                     
                            }else {
//                                [imageArray addObject:[self.videoView captureImage]];
                                [imageArray addObject:[self viewSnapshot:self.videoView withInRect:CGRectZero]];
                            }
                        });

                        [lock unlock];
                    }];
                    [dataTask resume];
                });
            }];
        }
    });

}
- (UIImage *)viewSnapshot:(UIView *)theView withInRect:(CGRect)rect;
{
    
    
        CGRect irect = CGRectZero;
        CGSize sSize = self.videoView.frame.size;
        if (sSize.width > sSize.height) {
//            CGFloat h = sSize.width/1280*720;
//            irect = CGRectMake(0, (self.videoView.frame.size.width-h)/2,  self.videoView.frame.size.width,  self.videoView.frame.size.height );
            irect = CGRectMake(0, 300, self.videoView.frame.size.height *1.35 , self.videoView.frame.size.width *1.5);
        }else {
             CGFloat w = self.videoView.frame.size.height/720*1280;
             irect = CGRectMake((w-self.videoView.frame.size.width)/2, 0,  self.videoView.frame.size.width,  self.videoView.frame.size.height);
        }
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.videoView.frame.size.height*1.35, self.videoView.frame.size.width*1.5), YES, 0);
      [[[UIApplication sharedApplication].keyWindow layer] renderInContext:UIGraphicsGetCurrentContext()];
      UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      CGImageRef imageRef = viewImage.CGImage;
      rect =irect;//这里可以设置想要截图的区域
      CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
      UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
//      UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存图片到照片库
    
    
    
    
    
    
    
    
//    UIGraphicsBeginImageContextWithOptions(CGSizeMake(theView.bounds.size.width, theView.bounds.size.height * 0.8), YES, [UIScreen mainScreen].scale);
//      CGContextRef context = UIGraphicsGetCurrentContext();
//      UIImage *img;
//
//    CGRect irect = CGRectZero;
//    CGSize sSize = self.videoView.frame.size;
//    if (sSize.width > sSize.height) {
//        CGFloat h = sSize.width/1280*720;
//        irect = CGRectMake(600, (self.videoView.frame.size.width-h)/2,  self.videoView.frame.size.width,  self.videoView.frame.size.height );
//    }else {
//         CGFloat w = self.videoView.frame.size.height/720*1280;
//         irect = CGRectMake((w-self.videoView.frame.size.width)/2, 0,  self.videoView.frame.size.width,  self.videoView.frame.size.height);
//    }
//
//      if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){
//        for(UIView *subview in theView.subviews){
//          [subview drawViewHierarchyInRect:irect afterScreenUpdates:YES];
//        }
//        img = UIGraphicsGetImageFromCurrentImageContext();
//      }else{
//        CGContextSaveGState(context);
//        [theView.layer renderInContext:context];
//        img = UIGraphicsGetImageFromCurrentImageContext();
//      }
//      UIGraphicsEndImageContext();
      return sendImage;
}



- (UIImage *)captureImage {
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGRect irect = CGRectZero;
    CGSize sSize = self.view.frame.size;
    if (sSize.width > sSize.height) {
        CGFloat h = sSize.width/1280*720;
        irect = CGRectMake(0, (self.view.frame.size.width-h)/2,  self.view.frame.size.width,  self.view.frame.size.height);
    }else {
         CGFloat w = self.view.frame.size.height/720*1280;
         irect = CGRectMake((w-self.view.frame.size.width)/2, 0,  self.view.frame.size.width,  self.view.frame.size.height);
    }
    return [self imageByCropToRect:irect image:snap];
}
- (UIImage *)imageByCropToRect:(CGRect)rect image:(UIImage *)image {
    rect.origin.x *= image.scale;
    rect.origin.y *= image.scale;
    rect.size.width *= image.scale;
    rect.size.height *= image.scale;
    if (rect.size.width <= 0 || rect.size.height <= 0) return nil;
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    UIImage *rimage = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];
    CGImageRelease(imageRef);
    return rimage;
}
- (void)checkOilAndArray:(NSArray *)imageArray {

    @weakify(self);
        dispatch_async(dispatch_get_main_queue(), ^{
            SMCheckOilBGView *oview = [[SMCheckOilBGView alloc] init];
            @weakify(oview);
            oview.BtnSendBlock = ^(bool send) {
                @strongify(oview);
                @strongify(self);
                if (send) {
                    [self checkOilAndArray:imageArray];
                }else {
                    [self editPostionWithArray:imageArray outValue:0];
                }
                [oview wb_disBTlLMiss];
            };
            oview.frame= self.view.bounds;
            [oview wb_showlTBFromSuperView: self.view];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [oview wb_disBTlLMiss];
//            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                [[DKSocket share] sendData:dataWithCmd(JFDeviceRecvCommandCheckWaterOil) completeBlock:^(NSData * _Nonnull response) {
                    @strongify(self);
                    JFDeviceSendCommand cmd;
                    int outValue = 0;
                    cmdWithData(response,&outValue, &cmd);
                    if (outValue > 85) {
                        outValue = 85;
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (outValue ==0) {
                            [oview faildViewHidden:NO];
                        }else {
                            [oview wb_disBTlLMiss];
                            [self editPostionWithArray:imageArray outValue:outValue];
                        }

                    });
  
                    
                }];
                
            });
            
        });
  


}
- (void)editPostionWithArray:(NSArray *)imageArray  outValue:(int )outValue{
    
    
    [[DKSocket share] sendData:dataWithCmd(0) completeBlock:^(NSData * _Nonnull response) {
    }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.takeImageBtn.hidden = NO;
        self.dengBtn.hidden = NO;
        self.dengBtn.selected = NO;
        self.dengBGView.hidden = NO;
        SMEditPositionNameView *nameView = [[SMEditPositionNameView alloc] init];
        [nameView wb_showFromSuperView:self.view];
        @weakify(self);
        nameView.saveBlock = ^(NSString * _Nonnull str) {
            @strongify(self);
            [self reportViewWithName:str imgeArray:imageArray fen:outValue];

        };
        
    });
    
}

- (void)reportViewWithName:(NSString *)name imgeArray:(NSArray *)imgArray fen:(int)fen{
    if (imgArray.count < 4) {
        [SVProgressHUD showErrorWithStatus:@"拍摄失败,重新拍摄"];
        return;
    }
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        
        NSMutableArray *imgeArray = [[NSMutableArray alloc] init];
        NSArray *tipsTArray = [@"日光图,极化图,纹理图,UV图,日光图" componentsSeparatedByString:@","];
        NSString *tID = nowTimeTimestamp();
        for (int i = 0; i < 4; i++) {
            UIImage *iconImg = imgArray[i];
            NSString *keyString = [NSString stringWithFormat:@"Pictures/%@/%@/%@/%d.jpg",[SMGlobalModel share].mid ,self.clinetModel.ID,tID,i];
            [[MMLocalDataBManager sharedManager] addWithObjectKey:keyString updateData:UIImageJPEGRepresentation(iconImg, 1)];
            NSString *iconUrl = [NSString stringWithFormat:@"%@/%@",[[MMAutoUploadTool sharedManager] domain],keyString];
            [[SDImageCache sharedImageCache] storeImage:iconImg forKey: iconUrl completion:^{

            }];
            SMLocalReportImageModel *model = [[SMLocalReportImageModel alloc] init];
            model.iType = [NSString stringWithFormat:@"%d",i];
            model.iURL = iconUrl;
            model.iname = tipsTArray[i];
            [imgeArray addObject:model];

        }

        SMLocalReportModel *model = [[SMLocalReportModel alloc] init];
        model.cid = self.clinetModel.ID;
        model.iposition = name;
        model.createTime = tID;
        model.cgid = tID;
        model.imageArray = imgeArray;
        model.mid = [SMGlobalModel share].mid;
        
        
        
        ///敏感
        NSDictionary *minganDict = [SMAIImageTool minGanWithJihuaImg:imgArray[1]];
        NSDictionary *zhouwenDict = [SMAIImageTool zhouwenWithWenLiImg:imgArray[2]];
        NSDictionary *maokongcudaDict = [SMAIImageTool haoKongCuDaWithJihuaImg:imgArray[1]];
        NSDictionary *sechenDict = [SMAIImageTool seChenWithJihuaImg:imgArray[1]];
        NSDictionary *pizhiDict = [SMAIImageTool piZhiDuSheWithRiGuangImg:imgArray[0]];
        NSDictionary *maokongduseDict = [SMAIImageTool haoKongDuSheWithUVImg:imgArray[3]];
        
        SMLocalReportAIModel *shuifenModel = [[SMLocalReportAIModel alloc] init];
        shuifenModel.tagFlag = @"magn_water";
        shuifenModel.tagValue = [NSString stringWithFormat:@"%d",fen];
        shuifenModel.aiImageUrl = @"";
        shuifenModel.dermalogicatext = @"";
        shuifenModel.tagname = @"水份";
        shuifenModel.tagNum = [NSString stringWithFormat:@"%d",fen];
        if (fen <= 45) {
            shuifenModel.dermalogicatext = (self.weiduDcit[@"magn_water"])[@"one"];
        }else if (fen <= 55) {
            shuifenModel.dermalogicatext = (self.weiduDcit[@"magn_water"])[@"two"];
        }else {
            shuifenModel.dermalogicatext = (self.weiduDcit[@"magn_water"])[@"three"];
        }
        
        SMLocalReportAIModel *minganModel = [[SMLocalReportAIModel alloc] init];
        minganModel.tagFlag = @"magn_sensity";
        minganModel.tagValue =[NSString stringWithFormat:@"%@",minganDict[@"ratio"]];
        minganModel.aiImageUrl = [self saveLocalImage:minganDict[@"image"] typeString:@"magn_sensity" tID:tID];
        minganModel.tagname = @"敏感";
        minganModel.tagNum = minganDict[@"ratio"];
        
        int minganFen = [minganDict[@"ratio"]doubleValue];
        if (minganFen == 0 ) {
            minganModel.dermalogicatext  =  (self.weiduDcit[@"magn_sensity"])[@"one"];
        }else if (minganFen <= 10 ) {
            minganModel.dermalogicatext  =  (self.weiduDcit[@"magn_sensity"])[@"two"];
        }else if (minganFen <=20 ) {
            minganModel.dermalogicatext  =  (self.weiduDcit[@"magn_sensity"])[@"three"];
        }else {
            minganModel.dermalogicatext  =  (self.weiduDcit[@"magn_sensity"])[@"four"];
        }
        

        
        SMLocalReportAIModel *zhouwenModel = [[SMLocalReportAIModel alloc] init];
        zhouwenModel.tagFlag = @"magn_wrinkle";
        zhouwenModel.tagValue =[NSString stringWithFormat:@"%@",zhouwenDict[@"wrinkleCount"]];
        zhouwenModel.aiImageUrl = [self saveLocalImage:zhouwenDict[@"image"] typeString:@"magn_wrinkle" tID:tID];
        zhouwenModel.tagname = @"皱纹";

        int zhouwenFen = [zhouwenDict[@"wrinkleCount"]intValue];
        zhouwenModel.tagNum =zhouwenDict[@"wrinkleCount"];
        if (zhouwenFen == 0 ) {
            zhouwenModel.dermalogicatext  =  (self.weiduDcit[@"magn_wrinkle"])[@"one"];
        }else if (zhouwenFen <= 25 ) {
            zhouwenModel.dermalogicatext  =  (self.weiduDcit[@"magn_wrinkle"])[@"two"];
        }else if (zhouwenFen <=40 ) {
            zhouwenModel.dermalogicatext  =  (self.weiduDcit[@"magn_wrinkle"])[@"three"];
        }else {
            zhouwenModel.dermalogicatext  =  (self.weiduDcit[@"magn_wrinkle"])[@"four"];
        }
        
        
        SMLocalReportAIModel *maokongcudaModel = [[SMLocalReportAIModel alloc] init];
        maokongcudaModel.tagFlag = @"magn_pore_large";
        maokongcudaModel.tagValue =[NSString stringWithFormat:@"%@",maokongcudaDict[@"roughPoreCount"]];
        maokongcudaModel.aiImageUrl = [self saveLocalImage:maokongcudaDict[@"image"] typeString:@"magn_pore_large" tID:tID];
        maokongcudaModel.tagname = @"毛孔粗大";
        maokongcudaModel.dermalogicatext  = @"毛孔粗大的护理方法";
        int maokongcudaFen = [maokongcudaDict[@"roughArea"]intValue];
        maokongcudaModel.tagNum  = maokongcudaDict[@"roughArea"];
        if (maokongcudaFen == 0 ) {
            maokongcudaModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_large"])[@"one"];
        }else if (maokongcudaFen <=50000 ) {
            maokongcudaModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_large"])[@"two"];
        }else if (maokongcudaFen <=120000 ) {
            maokongcudaModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_large"])[@"three"];
        }else {
            maokongcudaModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_large"])[@"four"];
        }
        
        
        SMLocalReportAIModel *maokongduseModel = [[SMLocalReportAIModel alloc] init];
        maokongduseModel.tagFlag = @"magn_pore_clogging";
        maokongduseModel.tagValue =[NSString stringWithFormat:@"%@",maokongduseDict[@"blockedCount"]];
        maokongduseModel.aiImageUrl = [self saveLocalImage:maokongduseDict[@"image"] typeString:@"magn_pore_clogging" tID:tID];
        maokongduseModel.tagname = @"毛孔堵塞";
        
        int maokongduseFen = [maokongduseDict[@"blockedArea"]intValue];
        maokongduseModel.tagNum  = maokongduseDict[@"blockedArea"];
        if (maokongduseFen == 0 ) {
            maokongduseModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_clogging"])[@"one"];
        }else if (maokongduseFen <=50000 ) {
            maokongduseModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_clogging"])[@"two"];
        }else if (maokongduseFen <=120000 ) {
            maokongduseModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_clogging"])[@"three"];
        }else {
            maokongduseModel.dermalogicatext  =  (self.weiduDcit[@"magn_pore_clogging"])[@"four"];
        }
        
        
        SMLocalReportAIModel *sechenModel = [[SMLocalReportAIModel alloc] init];
        sechenModel.tagFlag = @"magn_pigmentation";
        sechenModel.tagValue =[NSString stringWithFormat:@"%@",sechenDict[@"ratio"]];
        sechenModel.aiImageUrl = [self saveLocalImage:sechenDict[@"image"] typeString:@"magn_pigmentation" tID:tID];
        sechenModel.tagname = @"色沉";
        sechenModel.tagNum  = sechenDict[@"ratio"];

        int secenFen = [sechenDict[@"ratio"]intValue];
        if (secenFen == 0 ) {
            sechenModel.dermalogicatext  =  (self.weiduDcit[@"magn_pigmentation"])[@"one"];
  
        }else if (secenFen <=7 ) {
            sechenModel.dermalogicatext  =  (self.weiduDcit[@"magn_pigmentation"])[@"two"];

        }else if (secenFen <=15 ) {
            sechenModel.dermalogicatext  =  (self.weiduDcit[@"magn_pigmentation"])[@"three"];

        }else {
            sechenModel.dermalogicatext  =  (self.weiduDcit[@"magn_pigmentation"])[@"four"];

        }
        
        
    
        
        SMLocalReportAIModel *pizhiModel = [[SMLocalReportAIModel alloc] init];
        pizhiModel.tagFlag = @"magn_sebum";
        pizhiModel.tagValue =[NSString stringWithFormat:@"%@",pizhiDict[@"ratio"]];
        pizhiModel.aiImageUrl = [self saveLocalImage:pizhiDict[@"image"] typeString:@"magn_sebum" tID:tID];
        pizhiModel.tagname = @"皮脂";
        pizhiModel.dermalogicatext  = @"皮脂的护理方法";
        pizhiModel.tagNum  = pizhiDict[@"ratio"];
        int pizhiFen = [pizhiDict[@"ratio"]intValue];
        if (pizhiFen <= 1 ) {
            pizhiModel.dermalogicatext  =  (self.weiduDcit[@"magn_sebum"])[@"one"];
        }else if (pizhiFen <=9 ) {
            pizhiModel.dermalogicatext  =  (self.weiduDcit[@"magn_sebum"])[@"two"];
        }else {
            pizhiModel.dermalogicatext  =  (self.weiduDcit[@"magn_sebum"])[@"three"];
        }
        NSLog(@"shuifen = %d, minganFen = %d, pizhiFen = %d, secenFen = %d, zhouwenFen = %d, maokongcudaFen = %d",fen,minganFen,pizhiFen,secenFen,zhouwenFen,maokongcudaFen);
        
       model.AISymptomArray = @[shuifenModel,minganModel,zhouwenModel,maokongcudaModel,maokongduseModel,sechenModel,pizhiModel].mutableCopy;
        [[SMLocalReportBManager sharedManager] addWithModel:model];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            SMReportViewController *vc = [[SMReportViewController alloc] init];
            vc.clinetModel = self.clinetModel;
            vc.lrModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        });
    });
}

- (NSString *)saveLocalImage:(UIImage *)image typeString:(NSString *)typeString tID:(NSString *)tID{
    
    NSString *mingankeyString = [NSString stringWithFormat:@"Pictures/%@/%@/%@/%@.jpg",[SMGlobalModel share].mid ,self.clinetModel.ID,tID,typeString];
    [[MMLocalDataBManager sharedManager] addWithObjectKey:mingankeyString updateData:UIImageJPEGRepresentation(image, 1)];
    NSString *iconUrl = [NSString stringWithFormat:@"%@/%@",[[MMAutoUploadTool sharedManager] domain],mingankeyString];
    [[SDImageCache sharedImageCache] storeImage:image forKey: iconUrl completion:^{

    }];
    return iconUrl;
}
@end


