//
//  AboutViewController.m
//  VclustersGemini
//
//  Created by APPLE on 2020/2/24.
//  Copyright © 2020 APPLE. All rights reserved.
//

#import "AboutViewController.h"
#import "HaveNewVersionView.h"
#import "HWVersionModel.h"
#import "iPhone.h"
#import "CloudPhoneAPI.h"
#import <MJExtension.h>
#import "CustomerWebViewController.h"
#import "netWorkManager.h"
#import "SuperModel.h"
#import "allVersionView.h"

@interface AboutViewController ()
@property (nonatomic, strong) UIButton *checUpdatekBtn;
// gradient
@property (nonatomic, strong)CAGradientLayer *gl_checkVersonBut;
@property (nonatomic, strong) UIButton *ruleBtn;
@property (nonatomic, strong) UIButton *privateBtn;
@property (nonatomic, strong) HWVersionModel *versionModel;

@end

@implementation AboutViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self drawAnyView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}

- (void)drawAnyView
{
    [self.view setBackgroundColor:HWF5F7FAColor];
    self.navBarBGView.hidden = NO;
    [self.navigationBar setHidden:YES];
    [self.toolBar setHidden:YES];
    [self.titleLabel setText:NSLocalizedString(@"app_update_title",nil)];
    
    UIImageView *topImage = [[UIImageView alloc] init];
    [topImage setImage:[self getAppIcon]];
    topImage.userInteractionEnabled = YES;
    [self.view addSubview:topImage];
    [topImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(72.f);
        make.height.mas_equalTo(72.f);
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.navBarBGView.mas_bottom).offset(123.f);
    }];
    [topImage.layer setCornerRadius:15.f];
    topImage.clipsToBounds = YES;
    
    UITapGestureRecognizer *tap5 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap5NumFun)];
    tap5.numberOfTapsRequired = 5;
    [topImage addGestureRecognizer:tap5];
    
    /*app名*/
    UILabel *appName = [[UILabel alloc] init];
    [appName setBackgroundColor:[UIColor clearColor]];
    [appName setTextColor:HW333333Color];
    [appName setFont:[UIFont boldSystemFontOfSize:16.f]];
    [appName setTextAlignment:(NSTextAlignmentCenter)];
    [appName setText:[NSString stringWithFormat:@"%@",[iPhone appBundleName]]];
    //[appName setText:[NSString stringWithFormat:@"%@",@"Private- X"]];
    
    [self.view addSubview:appName];
    [appName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topImage.mas_bottom).offset(20.f);
        make.right.mas_equalTo(-27.f);
        make.left.mas_equalTo(27.f);
        make.height.mas_equalTo(22.f);
    }];
    
    /*版本号*/
    UILabel *versionLabel = [[UILabel alloc] init];
    [versionLabel setBackgroundColor:[UIColor clearColor]];
    [versionLabel setTextColor:HW333333Color];
    [versionLabel setFont:[UIFont systemFontOfSize:13.f]];
    [versionLabel setTextAlignment:(NSTextAlignmentCenter)];
    NSString *vers = [iPhone appVersion];
    [versionLabel setText:[NSString stringWithFormat:@"V%@",vers]];
    [self.view addSubview:versionLabel];
    [versionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(appName.mas_bottom).offset(10.f);
        make.right.mas_equalTo(-27.f);
        make.left.mas_equalTo(27.f);
        make.height.mas_equalTo(20.f);
    }];
    
    /*开始体验*/
    _checUpdatekBtn = [[UIButton alloc] init];
    _checUpdatekBtn.frame = CGRectMake(0, 0, 160.f, 48.f);

    // gradient
    _gl_checkVersonBut = [CAGradientLayer layer];
    _gl_checkVersonBut.frame = CGRectMake(0,0,160.f,48.f);
    _gl_checkVersonBut.startPoint = CGPointMake(0, 0.5);
    _gl_checkVersonBut.endPoint = CGPointMake(1, 0.5);
    _gl_checkVersonBut.colors = @[(__bridge id)HW0CDEFDColor.CGColor, (__bridge id)HW058DFBColor.CGColor];
    _gl_checkVersonBut.locations = @[@(0), @(1.0f)];
    
    [_checUpdatekBtn.layer addSublayer:_gl_checkVersonBut];
    [_checUpdatekBtn addTarget:self action:@selector(versionCheckBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
    [_checUpdatekBtn setTitle:NSLocalizedString(@"app_update_check",nil) forState:(UIControlStateNormal)];
    [_checUpdatekBtn setTitle:NSLocalizedString(@"app_update_last_version",nil) forState:(UIControlStateDisabled)];
    [_checUpdatekBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_checUpdatekBtn.titleLabel setFont:[UIFont systemFontOfSize:16.f]];
    [_checUpdatekBtn.layer setCornerRadius:8.f];
    _checUpdatekBtn.clipsToBounds = YES;
    [self.view addSubview:_checUpdatekBtn];
    [_checUpdatekBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(160.f);
        make.top.equalTo(versionLabel.mas_bottom).offset(25.f);
        make.height.mas_equalTo(48.f);
    }];
    
    UIButton *privateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.privateBtn = privateBtn;
    privateBtn.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [privateBtn setTitle:NSLocalizedString(@"app_update_private",nil) forState:UIControlStateNormal];
    [privateBtn setTitleColor:HW13B2EBColor forState:UIControlStateNormal];
    [privateBtn setBackgroundColor:[UIColor clearColor]];
    [privateBtn addTarget:self action:@selector(privateBtnClick) forControlEvents:UIControlEventTouchUpInside];
    privateBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.view addSubview:privateBtn];
    [privateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-80-AdaptTabHeight);
        //make.width.mas_equalTo(55);
        make.width.mas_equalTo(130);
        make.height.mas_equalTo(38);
        make.left.equalTo(self.view.mas_centerX).offset(6);
    }];
    
    UIButton *ruleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.ruleBtn = ruleBtn;
    ruleBtn.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [ruleBtn setTitle:NSLocalizedString(@"app_update_use_deal",nil) forState:UIControlStateNormal];
    [ruleBtn setTitleColor:HW13B2EBColor forState:UIControlStateNormal];
    [ruleBtn setBackgroundColor:[UIColor clearColor]];
    [ruleBtn addTarget:self action:@selector(ruleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    ruleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.view addSubview:ruleBtn];
    [ruleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-80-AdaptTabHeight);
        //make.width.mas_equalTo(55);
        make.width.mas_equalTo(130);
        make.height.mas_equalTo(38);
        make.right.equalTo(self.view.mas_centerX).offset(-6);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    [lineView setBackgroundColor:HW999999Color];
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(14);
        make.centerY.equalTo(ruleBtn.mas_centerY);
    }];
}

- (UIImage *)getAppIcon{

    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];

    //获取app中所有icon名字数组

    NSArray *iconsArr = infoDict[@"CFBundleIcons"][@"CFBundlePrimaryIcon"][@"CFBundleIconFiles"];

    //取最后一个icon的名字

    NSString *iconLastName = [iconsArr lastObject];

    //打印icon名字

    NSLog(@"iconsArr: %@", iconsArr);

    NSLog(@"iconLastName: %@", iconLastName);

    return [UIImage imageNamed:iconLastName];

}

#pragma mark- 网络请求
- (void)getVersion {
    
    [self showNewIndicatorHaveStrWithCanBack:YES canTouch:NO showText:NSLocalizedString(@"app_update_checking",nil)];

    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);
      [self removeNewIndicatorHaveStr];

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

       if (model.status == 0) {

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

    } failure:^(NSError * _Nonnull error) {
      HLog(@"%@", error);
        [[iToast makeText:NSLocalizedString(@"player_link_fail_tip",nil)] show];
      [self removeNewIndicatorHaveStr];
    }];
}

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

- (void)checkVersion {
//  NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *newVersion = [self.versionModel.versionNumber stringByReplacingOccurrencesOfString:@"v" withString:@""];  //去掉v
//    HLog(@"%@---%@", newVersion, currentVersion);
    if ([currentVersion compare:newVersion options:NSNumericSearch] == NSOrderedSame) { // 本地版本号 == 服务器版本号
//        [self showNoNewVersion];
          //[self showNewVersion];
        [[iToast makeText:NSLocalizedString(@"app_update_last_version",nil)] show];
        
        [HWDataManager setBoolWithKey:Const_haveVersion value:NO];
        
//        _checUpdatekBtn.enabled = NO;
//        _checUpdatekBtn.backgroundColor = [UIColor hwColor:@"#959799" alpha:1.0];
//        [_gl_checkVersonBut removeFromSuperlayer];
    }else if ([currentVersion compare:newVersion options:NSNumericSearch] == NSOrderedDescending) { // 本地版本号 > 服务器版本号 （异常情况）
        [self showNoNewVersion];
        [HWDataManager setBoolWithKey:Const_haveVersion value:NO];
        
//        _checUpdatekBtn.enabled = NO;
//        _checUpdatekBtn.backgroundColor = [UIColor hwColor:@"#959799" alpha:1.0];
//        [_gl_checkVersonBut removeFromSuperlayer];
    }else { // 本地版本号 < 服务器版本号 (有新版本)
        self.versionModel.versionNumber = newVersion;
        [self showNewVersion];
        [HWDataManager setBoolWithKey:Const_haveVersion value:YES];
    };
}

- (void)showNewVersion {
    
    HaveNewVersionView *haveNewVersionView = [HaveNewVersionView shardInstance];
    if (haveNewVersionView.isShow) {
        return;
    }
    haveNewVersionView.versionModel = self.versionModel;
    haveNewVersionView.isContinueCheckAlert = NO; // 是否继续走下一步弹窗检测流程
    [haveNewVersionView setBackgroundColor:RGBACOLOR(0, 0, 0, 0.5)];
    [[[UIApplication sharedApplication] keyWindow] addSubview:haveNewVersionView];
    haveNewVersionView.isShow = YES;
    
    if(!self.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)showNoNewVersion {
    [[iToast makeText:NSLocalizedString(@"app_update_last_version",nil)] show];
}

- (void)ruleBtnClick {
//https://cliys.armclouding.com/h5/protocol/protocol.html?agreementCoding=YSZYHXY2002&type=1
//    [self gotoProtocolWKWebVCByPush:YES];
    CustomerWebViewController *vc = [[CustomerWebViewController alloc] init];
    vc.titleStr = NSLocalizedString(@"app_update_use_deal",nil);
    NSString *url = @"https://cliys.armclouding.com/h5/protocol/protocol.html?agreementCoding=YSZYHXY2003&type=1";//[NSString stringWithFormat:@"%@/h5/protocol/protocol.html?agreementCoding=YSZYHXY2002&type=1", CloudService];
    vc.webUrl = url;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)privateBtnClick {
    
//    [self gotoPrivateProtocolWKWebVCByPush:YES];
    CustomerWebViewController *vc = [[CustomerWebViewController alloc] init];
    vc.titleStr = NSLocalizedString(@"app_update_private",nil);
    NSString *url = @"https://cliys.armclouding.com/h5/protocol/protocol.html?agreementCoding=YSZYSXY2002&type=1";//[NSString stringWithFormat:@"%@/h5/protocol/protocol.html?agreementCoding=YSZYSXY2001&type=1", CloudService];
    vc.webUrl = url;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didTap5NumFun
{
    allVersionView *view = [[allVersionView alloc] init];
    UIWindow *keyWindow = [iTools getKeyWindow];
    [keyWindow addSubview:view];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    if(_getSysInfo){
        _getSysInfo();
    }
}
@end
