//
//  KMVerificationMessageViewController.m
//  PDF Reader Pro Edition
//
//  Created by 王帅 on 2018/5/9.
//

#import "KMVerificationMessageViewController.h"
#import <PDF_Reader_Pro-Swift.h>
#import "VerificationManager.h"
#import "AIInfoManager.h"
#import "KMVerificationWindowController.h"
#import "KMPurchaseCompareWindowController.h"
#import "KMUnlockAlertViewController.h"
//#import "FMTrackEventManager.h"
//#import "SKInspectPublicTool.h"
//#import "KMToolCompareWindowController.h"

#define kbottomGap 0
@interface KMVerificationMessageViewController ()<
NSPopoverDelegate>

@property (nonatomic, assign) IBOutlet NSTextField *label;
@property (nonatomic, assign) IBOutlet NSButton *button;
@property (nonatomic, assign) IBOutlet NSButton *secondTrialBtn;
@property (assign) IBOutlet NSView *labelContentView;
@property (assign) IBOutlet NSImageView *bgImg;

@property (assign) IBOutlet NSView *aiContendView;
@property (assign) IBOutlet NSImageView *aiIconImg;
@property (assign) IBOutlet NSTextField *aiLabel;

@property (nonatomic, retain) NSTrackingArea *trackingArea;

@property (nonatomic, retain) NSPopover *popover;

@property (nonatomic, assign) BOOL isPopoverShow;

@property (nonatomic, assign) BOOL checkValue;

@property (nonatomic, assign) BOOL stopPopOverHide;

@property (nonatomic, retain) KMUnlockAlertViewController *testVC;


@end

@implementation KMVerificationMessageViewController

#pragma mark Init Methods

- (instancetype)init {
    if (self = [super initWithNibName:@"KMVerificationMessageViewController" bundle:nil]) {
#if VERSION_DMG
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(deviceActivateStatusChangeNotification:)
                                                     name:kDeviceActivateStatusChangeNotification
                                                   object:nil];
#else
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IAPResultReceived:) name:KMIAPSubscriptionLoadedNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IAPPurchaseSuccess:) name:KMIAPProductPurchasedNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(IAPRestoreFinish:) name:KMIAPProductRestoreFinishedNotification object:nil];
        
#endif
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (self.trackingArea) {
        [self.button removeTrackingArea:self.trackingArea];
    }
    
}

#pragma mark Setter Methods

- (void)loadView {
    [super loadView];
    
    // Do view setup here.
    self.button.wantsLayer = YES;
    self.button.layer.masksToBounds = YES;
    self.button.layer.cornerRadius = 4.0;
    self.button.font = [NSFont SFProTextSemiboldFont:11];
    self.button.layer.backgroundColor = [NSColor colorWithDeviceRed:121.0/255.0 green:196.0/255.0 blue:66.0/255.0 alpha:1.0].CGColor;
    [self.button setAlignment:NSTextAlignmentCenter];
    
    self.secondTrialBtn.wantsLayer = YES;
    self.secondTrialBtn.layer.masksToBounds = YES;
    self.secondTrialBtn.layer.cornerRadius = 4.0;
    self.secondTrialBtn.font = [NSFont SFProTextSemiboldFont:11];
    self.secondTrialBtn.layer.backgroundColor = [NSColor colorWithDeviceRed:121.0/255.0 green:196.0/255.0 blue:66.0/255.0 alpha:1.0].CGColor;
    [self.secondTrialBtn setAlignment:NSTextAlignmentCenter];
    
    NSString *tTips = NSLocalizedString(@"Upgrade to Pro", nil);
#if VERSION_DMG
    tTips = [NSString stringWithFormat:@"%@\n%@", NSLocalizedString(@"Upgrade to Permanent License with one time purchase", nil), NSLocalizedString(@"Complete the purchase in your web browser to get a license", nil)];
#else
    tTips = [NSString stringWithFormat:@"%@\n%@", NSLocalizedString(@"Subscribe to All Access Pack to enjoy more expanded features.", nil), NSLocalizedString(@"Choose your favorite payment and enjoy flexible upgrades.", nil)];
#endif

    self.button.toolTip = tTips;
    self.button.title = [NSString stringWithFormat:@" %@  ",NSLocalizedString(@"Upgrade", nil)];
    [self.button setTitleColor:[NSColor whiteColor]];
    [self.button setAlignment:NSTextAlignmentCenter];
    
    self.secondTrialBtn.toolTip = tTips;
    self.secondTrialBtn.title = [NSString stringWithFormat:@" %@  ",NSLocalizedString(@"Free Trial", nil)];
    [self.secondTrialBtn setTitleColor:[NSColor whiteColor]];
    [self.secondTrialBtn setAlignment:NSTextAlignmentCenter];
    self.secondTrialBtn.hidden = YES;
    
    self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = YES;
    
    self.bgImg.wantsLayer = YES;
    self.bgImg.image = [NSImage imageNamed:@"Upgarde_bg_icon"];
    self.bgImg.layer.masksToBounds = YES;
    self.bgImg.layer.cornerRadius = 4.;
    self.bgImg.hidden = YES;
    
    self.aiLabel.font = [NSFont SFProTextSemiboldFont:11];
    self.aiLabel.textColor = [NSColor whiteColor];
    
    [self reloadData];
}

- (void)reloadData {
    self.label.textColor = [NSColor blackColor];
    self.label.hidden = NO;
    BOOL isFree = NO;
    self.secondTrialBtn.hidden = YES;
    self.bgImg.hidden = YES;
#if VERSION_DMG
    
    if (self.trackingArea) {
        [self.button removeTrackingArea:self.trackingArea];
    }
    
    self.label.stringValue = @"";
    if (ActivityStatusNone == [VerificationManager manager].status || isFree) {
        self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
        self.label.stringValue = @"";
        self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"Free Trial", nil)];
        if (isFree) {
            self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"Upgrade to Pro", nil)];
            self.button.title = [NSString stringWithFormat:@" %@            ",NSLocalizedString(@"Upgrade", nil)];
            [self.button setAlignment:NSTextAlignmentCenter];
            if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
                self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = YES;
            } else {
                self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
            }
        }
        self.button.layer.backgroundColor = [NSColor colorWithRed:0.0/255.0 green:207.0/255.0 blue:133.0/255.0 alpha:1].CGColor;
        [self.button setTitleColor:[NSColor whiteColor]];
    } else if (ActivityStatusTrial == [VerificationManager manager].status) {
        NSDate *date = [NSDate date];
        NSDate *expireDate = [VerificationManager manager].detailInfo.expireDate;
        NSTimeInterval time = [expireDate timeIntervalSinceDate:date];
        int leftDays = ((int)time)/(3600*24);
        self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
        NSString * needShowString = [NSString stringWithFormat:NSLocalizedString(@"%d days left", nil),leftDays];
        if (@available(macOS 10.14, *)) {
            self.label.attributedStringValue = [self numberConvertColor:[NSColor redColor] String:needShowString];
            self.label.textColor = [NSColor colorWithRed:255.0/255.0 green:94.0/255.0 blue:44.0/255.0 alpha:1];
        } else {
            self.label.stringValue = needShowString;
            self.label.textColor = [NSColor colorWithRed:255.0/255.0 green:94.0/255.0 blue:44.0/255.0 alpha:1];
        }
        
        
        self.label.wantsLayer = YES;
        self.label.layer.backgroundColor = [NSColor clearColor].CGColor;
        self.button.layer.backgroundColor = [NSColor colorWithRed:255.0/255.0 green:94.0/255.0 blue:44.0/255.0 alpha:1].CGColor;
        self.button.title = [NSString stringWithFormat:@" %@            ",NSLocalizedString(@"Upgrade", nil)];
        [self.button setTitleColor:[KMAppearance KMColor_Layout_W0]];
        [self.button setAlignment:NSTextAlignmentCenter];
        
        if (!self.trackingArea) {
            self.trackingArea = [[NSTrackingArea alloc] initWithRect:self.button.bounds options:NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect | NSTrackingActiveAlways  owner:self userInfo:nil];
        }
        [self.button addTrackingArea:self.trackingArea];
    } else if (ActivityStatusTrialExpire == [VerificationManager manager].status) {
        self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
        
        self.label.wantsLayer = YES;
        self.label.layer.backgroundColor = [NSColor clearColor].CGColor;
        self.label.stringValue = NSLocalizedString(@"Trial expired", nil);
        if (@available(macOS 10.14, *)) {
            self.label.textColor = [NSColor whiteColor];
        } else {
            self.label.textColor = [NSColor redColor];
        }
        self.label.stringValue = @"";
        
//        self.button.layer.backgroundColor = [NSColor colorWithRed:221/255.0 green:44/255.0 blue:0/255.0 alpha:1].CGColor;
//        self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"Unlock Full Version", nil)];
        self.button.title = [NSString stringWithFormat:@" %@            ",NSLocalizedString(@"Upgrade", nil)];
        [self.button setAlignment:NSTextAlignmentCenter];
        self.bgImg.hidden = NO;
        self.button.layer.backgroundColor = [NSColor clearColor].CGColor;
        [self.button setTitleColor:[NSColor whiteColor]];
        
        if (!self.trackingArea) {
            self.trackingArea = [[NSTrackingArea alloc] initWithRect:self.button.bounds options:NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect | NSTrackingActiveAlways  owner:self userInfo:nil];
        }
        [self.button addTrackingArea:self.trackingArea];
        
        if ([VerificationManager manager].secondTrialEnabled) {
            
            self.label.stringValue = NSLocalizedString(@"Trial expired", nil);
            self.label.hidden = YES;
            self.secondTrialBtn.hidden = NO;
            self.secondTrialBtn.layer.backgroundColor = [NSColor colorWithRed:0.0/255.0 green:207.0/255.0 blue:133.0/255.0 alpha:1].CGColor;
            [self.secondTrialBtn setTitleColor:[NSColor whiteColor]];
            [self.secondTrialBtn setAlignment:NSTextAlignmentCenter];
            
            self.button.title = [NSString stringWithFormat:@" %@            ",NSLocalizedString(@"Upgrade", nil)];
            [self.button setTitleColor:[NSColor whiteColor]];
            self.bgImg.hidden = NO;
            self.button.layer.backgroundColor = [NSColor clearColor].CGColor;
            [self.button setAlignment:NSTextAlignmentCenter];
//            [self.view removeTrackingArea:self.trackingArea];
        }
    } else if (ActivityStatusVerifExpire == [VerificationManager manager].status) {
        self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
        self.label.stringValue = @"";
//        self.button.layer.backgroundColor = [NSColor colorWithRed:221/255.0 green:44/255.0 blue:0/255.0 alpha:1].CGColor;
        self.button.title = [NSString stringWithFormat:@" %@            ",NSLocalizedString(@"Upgrade", nil)];
        [self.button setTitleColor:[NSColor whiteColor]];
        self.bgImg.hidden = NO;
        self.button.layer.backgroundColor = [NSColor clearColor].CGColor;
        [self.button setAlignment:NSTextAlignmentCenter];
    } else if (ActivityStatusVerification == [VerificationManager manager].status) {
        if ([VerificationManager manager].needUpgradeLicense == NO) {
            self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = YES;
        } else {
            self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
            self.label.stringValue = @"";
            self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"PDF to Office Pack", nil)];
            [self.button setTitleColor:[KMAppearance KMColor_Interactive_A0]];
            self.button.layer.backgroundColor = [NSColor colorWithRed:229/255. green:233/255. blue:248/255. alpha:1].CGColor;
            [self.button setAlignment:NSTextAlignmentCenter];
        }
    } else {
        self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = YES;
        if ([VerificationManager manager].needUpgradeLicense) {
            self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
            self.label.stringValue = @"";
            
            self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"PDF to Office Pack", nil)];
            [self.button setTitleColor:[KMAppearance KMColor_Interactive_A0]];
            self.button.layer.backgroundColor = [NSColor colorWithRed:229/255. green:233/255. blue:248/255. alpha:1].CGColor;
            [self.button setAlignment:NSTextAlignmentCenter];
        }
    }
#else
    isFree = YES;
    if (isFree) {
        self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
        self.button.layer.backgroundColor = [NSColor clearColor].CGColor;
        self.label.stringValue = @"";
        self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"Free Trial", nil)];
        if (isFree) {
            self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"Upgrade to Pro", nil)];
            [self.button setTitleColor:[NSColor whiteColor]];
            if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
                self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = YES;
            } else {
                self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
            }
            self.bgImg.hidden = self.button.hidden;
#if !VERSION_FREE
            self.bgImg.hidden = YES;
            self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = NO;
            self.button.title = [NSString stringWithFormat:@" %@ ",NSLocalizedString(@"PDF to Office Pack", nil)];
            if ([IAPProductsManager defaultManager].isAvailableAdvancedPDFToOffice) {
                self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = YES;
            }
            [self.button setTitleColor:[KMAppearance KMColor_Interactive_A0]];
            self.button.layer.backgroundColor = [NSColor colorWithRed:229/255. green:233/255. blue:248/255. alpha:1].CGColor;
#endif
        }
    } else {
        self.labelContentView.hidden = self.bgImg.hidden = self.button.hidden = YES;
    }
#endif

    [self.button sizeToFit];
    [self.button setAlignment:NSTextAlignmentCenter];
    [self.secondTrialBtn sizeToFit];
    [self.secondTrialBtn setAlignment:NSTextAlignmentCenter];
    
    [self.label sizeToFit];
    if (self.label.stringValue.length == 0) {
        self.labelContentView.frame = CGRectZero;
    } else {
        self.labelContentView.frame = CGRectMake(0, kbottomGap, self.label.frame.size.width + self.view.frame.size.height , self.view.frame.size.height -2 *kbottomGap);
        
        if ([VerificationManager manager].secondTrialEnabled) {
            self.labelContentView.frame = CGRectMake(0, kbottomGap, self.button.frame.size.width + self.secondTrialBtn.frame.size.width - 16, self.view.frame.size.height -2 *kbottomGap);
        }
        self.labelContentView.wantsLayer = YES;
        self.labelContentView.layer.cornerRadius = 4.;
        [self.labelContentView.layer masksToBounds];
        
        self.labelContentView.layer.backgroundColor = [NSColor colorWithRed:255.0/255.0 green:94.0/255.0 blue:44.0/255.0 alpha:0.15].CGColor;
        if ([VerificationManager manager].secondTrialEnabled) {
            self.labelContentView.layer.backgroundColor = [NSColor clearColor].CGColor;
        }
        self.label.frame = CGRectMake(self.labelContentView.frame.size.height/2, (self.labelContentView.frame.size.height - self.label.frame.size.height)/2, self.label.frame.size.width, self.label.frame.size.height);
    }
    
    CGFloat totalWidth = CGRectGetMaxX(self.labelContentView.frame) + 8;
    
    self.aiLabel.stringValue = NSLocalizedString(@"My AI Credit", nil);
    [self.aiLabel sizeToFit];
    CGFloat aiWidth = self.aiLabel.frame.size.width;
    aiWidth += 4;
    aiWidth += 16;
    aiWidth += 16;
    self.aiContendView.frame = CGRectMake(totalWidth, 0, aiWidth, self.view.frame.size.height);
    self.aiIconImg.frame = CGRectMake(8, CGRectGetHeight(self.view.frame)/2.-8, 16, 16);
    CGRect ailabelRect = self.aiLabel.frame;
    ailabelRect.origin.x = CGRectGetMaxX(self.aiIconImg.frame) + 4;
    self.aiLabel.frame = ailabelRect;
    
    totalWidth += aiWidth;
    totalWidth += 8;
    
    if (self.button.hidden == NO) {
        CGFloat buttonWidth = CGRectGetMaxX(self.button.frame);
        NSRect btnRect = [self.button.attributedTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, CGRectGetHeight(self.button.frame)) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading];
        if (fabs(buttonWidth-btnRect.size.width)>50) {
            buttonWidth = btnRect.size.width + 10;
        }
        self.button.frame = CGRectMake(totalWidth, kbottomGap, buttonWidth, self.view.frame.size.height -2 *kbottomGap);
        totalWidth += buttonWidth;
        totalWidth += 8;
    }
    
    if (!self.secondTrialBtn.hidden) {
        self.secondTrialBtn.frame = CGRectMake(MAX(CGRectGetMaxX(self.labelContentView.frame) - self.button.frame.size.width, 0), kbottomGap, self.button.frame.size.width, self.view.frame.size.height -2 *kbottomGap);
    }
    if (self.view.superview) {
        self.view.frame = CGRectMake(MAX(0, CGRectGetWidth(self.view.superview.frame)-totalWidth - 8), (CGRectGetHeight(self.view.superview.frame)-CGRectGetHeight(self.view.frame))/2., totalWidth, self.view.frame.size.height);
    } else {
        if (self.button.hidden) {
            self.view.frame = CGRectMake(0,0, CGRectGetMaxX(self.aiLabel.frame) + 20 ,self.view.frame.size.height);
        } else {
            self.view.frame = CGRectMake(0,0, CGRectGetMaxX(self.button.frame) ,self.view.frame.size.height);
        }
    }
    
    if (self.frameUpdateHandle) {
        self.frameUpdateHandle(self.view.frame);
    }

    CGRect rect = self.button.frame;
    self.bgImg.frame = rect;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popoverShowNoti:) name:@"KMVerificationMessagePopShowNoti" object:nil];
}

#pragma mark - Button Actions

- (IBAction)secondTrialAction:(NSButton *)sender {
    if ([VerificationManager manager].secondTrialEnabled) {
        KMVerificationWindowController *vc = [KMVerificationWindowController verificationWithType:KMVerificationTypeRepeatTrialGuide];
        [vc showWindow:nil];
    } else {
        [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
    }
}

- (IBAction)buttonAction:(id)sender {
    BOOL isFree = NO;

#if VERSION_DMG
    if (ActivityStatusNone == [VerificationManager manager].status) {
        //弹出 试用弹窗UI优化-新用户试用路径 新UI 情况一 右上角按钮
        KMPurchaseFirstTrialWindowController *firstTrialWC = [KMPurchaseFirstTrialWindowController currentFirstTrialWC];
        firstTrialWC.buttonActionBlock = ^(KMPurchaseFirstTrialWindowController * _Nonnull ftWC, KMButton * _Nonnull btn, NSString * _Nonnull email, NSString * _Nonnull name) {
            if (btn.tag == 10001) {
                if (ActivityStatusNone == [VerificationManager manager].status ||
                    ActivityStatusTrialExpire == [VerificationManager manager].status) {

                    [[FMTrackEventManager defaultManager] trackEventWithEvent:@"Tbr" withProperties:@{@"Tbr_Btn":@"Btn_Tbr_SecondTrial"}];
                    [[VerificationManager manager] trialForDays:7
                                                          email:email?:[VerificationManager manager].email
                                                           name:name?:[VerificationManager manager].accountName
                                                    complention:^(ActivityStatus status, NSDictionary *info, NSError *error) {
                        if (error ||
                            status != ActivityStatusTrial) {
                            NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Activation Error", nil)
                                                             defaultButton:NSLocalizedString(@"Try Again", nil)
                                                           alternateButton:nil
                                                               otherButton:nil
                                                 informativeTextWithFormat:NSLocalizedString(@"Failed to sign up for the free trial. Please make sure your internet connection is available and try again later.", nil), nil];
                            [alert runModal];
                        } else {
                            KMVerificationWindowController *vc = [KMVerificationWindowController verificationWithType:KMVerificationTypeRepeatTrialSuccess];
                            [vc showWindow:nil];
                        }
                    }];
                    [ftWC close];
                } else {
                    [ftWC close];
                    KMVerificationWindowController *vc = [KMVerificationWindowController verificationWithType:KMVerificationTypeActivate];
                    vc.callback = ^{
                        [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
                    };
                    [vc showWindow:nil];
                }
            } else if (btn.tag == 10002) {
                NSURL *url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/store?utm_source=app_dmg&utm_medium=dmg_puw_free_trial"];
                if([SKInspectPublicTool currentisLanguageHans]) {
                    url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/zh-cn/store?utm_source=app_dmg&utm_medium=dmg_puw_free_trial"];
                }
                [[NSWorkspace sharedWorkspace] openURL:url];
                [[FMTrackEventManager defaultManager] trackEventWithEvent:@"PUW" withProperties:@{@"PUW_Btn":@"PUW_Btn_UpgradeBuyNow"}];
            } else if (btn.tag == 10003) {
                KMVerificationWindowController *vc = [KMVerificationWindowController verificationWithType:KMVerificationTypeActivate];//KMVerificationTypeActivate
                [vc showWindow:nil];
                [ftWC close];
            }
        };
        [firstTrialWC.window center];
        [firstTrialWC showWindow:nil];
    } else if (ActivityStatusTrialExpire == [VerificationManager manager].status ||
               ActivityStatusTrial == [VerificationManager manager].status) {
//        if ([VerificationManager manager].secondTrialEnabled) {
//            if (!self.checkValue) {
//                [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
//            }
//        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"KMVerificationMessagePopShowNoti" object:nil];
            
        if (!self.testVC) {
            self.testVC = [[KMUnlockAlertViewController alloc] init];
        }
        [self.testVC addtrackingAreaInfo];
        self.testVC.callback = ^(NSInteger index) {
                if (index == 1) {
                    KMVerificationWindowController *vc = [KMVerificationWindowController verificationWithType:KMVerificationTypeActivate];
                    [vc showWindow:nil];
                } else if (index == 2) {
                    NSURL *url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/store"];
                    if([SKInspectPublicTool currentisLanguageHans]) {
                        url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/zh-cn/store"];
                    }
                    [[NSWorkspace sharedWorkspace] openURL:url];
                    [[FMTrackEventManager defaultManager] trackEventWithEvent:@"PUW" withProperties:@{@"PUW_Btn":@"Btn_PUW_BuyNow-Expire"}];
                }
            };
        self.testVC.mouseEventCall = ^(BOOL mouseEnter) {
            if (mouseEnter) {
                self.stopPopOverHide = YES;
                if (ActivityStatusTrialExpire == [VerificationManager manager].status ||
                    ActivityStatusTrial == [VerificationManager manager].status) {
                    if (!self.popover.isShown) {
                        [self buttonAction:self.button];
                    }
                }
            } else {
                self.stopPopOverHide = NO;
                if (self.popover) {
                    [self.popover close];
                }
                [self.testVC removeTrackingAreaInfo];
            }
        };
            NSPopover *popover = [[NSPopover alloc] init];
            popover.delegate = self;
            popover.contentViewController = self.testVC;
            popover.animates = YES;
            popover.behavior = NSPopoverBehaviorTransient;
            [popover showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge];
            self.popover = popover;
//        }
    } else if (ActivityStatusVerifExpire == [VerificationManager manager].status) {
        KMVerificationWindowController *vc = [KMVerificationWindowController verificationWithType:KMVerificationTypeActivateExpired];
        [vc showWindow:nil];
    } else if (ActivityStatusVerification == [VerificationManager manager].status) {
        if ([VerificationManager manager].needUpgradeLicense) {
            NSURL *url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/store?product_code=product_2"];
            if([SKInspectPublicTool currentisLanguageHans]) {
                url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/zh-cn/store?product_code=product_2"];
            }
            [[NSWorkspace sharedWorkspace] openURL:url];
            [[FMTrackEventManager defaultManager] trackEventWithEvent:@"Tbr" withProperties:@{@"Tbr_Btn":@"Btn_Tbr_PDFtoOffice"}];
        }
    } else {
        if ([VerificationManager manager].needUpgradeLicense) {
            NSURL *url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/store?product_code=product_2"];
            if([SKInspectPublicTool currentisLanguageHans]) {
                url = [NSURL URLWithString:@"https://www.pdfreaderpro.com/zh-cn/store?product_code=product_2"];
            }
            [[NSWorkspace sharedWorkspace] openURL:url];
            [[FMTrackEventManager defaultManager] trackEventWithEvent:@"Tbr" withProperties:@{@"Tbr_Btn":@"Btn_Tbr_PDFtoOffice"}];
        } else {
            KMVerificationWindowController *vc = [KMVerificationWindowController verificationWithType:KMVerificationTypeNormal];
            [vc showWindow:nil];
        }
    }
#else
    isFree = YES;
#if VERSION_FREE
    if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
        isFree = NO;
    }
    if (isFree) {
        [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
    }
#else
    if (![IAPProductsManager defaultManager].isAvailableAdvancedPDFToOffice) {
//        KMToolCompareWindowController *vc = [KMToolCompareWindowController toolCompareWithType:KMCompareWithToolType_Convert setSelectIndex:0];
        KMToolCompareWindowController *vc = [KMToolCompareWindowController toolCompareWithToolType:KMCompareWithToolTypeConvert selectNum:0];
        [vc.window center];
        [vc showWindow:nil];
    }
#endif
    
#endif
    
}

- (NSAttributedString *)numberConvertColor:(NSColor*)color String:(NSString *)string {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSString *temp = nil;
    for (NSUInteger i = 0; i <string.length; i++) {
        temp = [string substringWithRange:NSMakeRange(i, 1)];
        if ([self isPureInt:temp]) {
            [attributedString setAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                             color, NSForegroundColorAttributeName, nil] range:NSMakeRange(i, 1)];
        }
    }
    return attributedString;
}

- (BOOL)isPureInt:(NSString *)string {
    NSScanner *scan = [NSScanner scannerWithString:string];
    int value;
    return [scan scanInt:&value] && [scan isAtEnd];
}

- (IBAction)AIButtonAction:(NSButton *)sender {
    __block typeof(self) blockSelf = self;
    [[FMTrackEventManager defaultManager] trackEventWithEvent:@"Tbr" withProperties:@{@"Tbr_Btn":@"Btn_Tbr_AICredit"}];
    [[AIInfoManager defaultManager] fetchAIInfoWithComplention:^(NSDictionary *info, NSError *error) {
            
    }];
    AIUserInfoController *controller = [[AIUserInfoController alloc] init];
    controller.purchaseHandle = ^(AIUserInfoController * _Nonnull vc) {
#if VERSION_DMG
        NSURL *url = [NSURL URLWithString:kAIStoreServerLink];
        [[NSWorkspace sharedWorkspace] openURL:url];
#else
        
        [[AIPurchaseWindowController currentWC] showWindow:nil];
#endif
        [[FMTrackEventManager defaultManager] trackEventWithEvent:@"Tbr" withProperties:@{@"Tbr_Btn":@"Btn_Tbr_AICredit_BuyNow"}];
    };
    controller.enterLicenseHandle = ^(AIUserInfoController * _Nonnull vc) {
        KMVerificationWindowController *verifyVC = [KMVerificationWindowController verificationWithType:KMVerificationTypeActivateAIInfo];
        verifyVC.callback = ^{

        };
        [verifyVC showWindow:nil];
    };
    
    controller.guideHandle = ^(AIUserInfoController * _Nonnull vc) {
        if (!blockSelf.guideWindowVC) {
            KMFunctionGuideWindowController *guideWindowVC = [[KMFunctionGuideWindowController alloc] initWithWindowNibName:@"KMFunctionGuideWindowController"];
            blockSelf.guideWindowVC = guideWindowVC;
        }
        ((KMFunctionGuideWindowController *)(blockSelf.guideWindowVC)).type = KMGuideInfoTypeFunctionMulti;
        [blockSelf.guideWindowVC showWindow:nil];
        [KMFunctionGuideWindowController setDidShowFor:KMGuideInfoTypeFunctionMultiAIGuide];
        [blockSelf.guideWindowVC.window orderFront:nil];
    };
    
    NSPopover *popover = [[NSPopover alloc] init];
    popover.contentViewController = controller;
    popover.animates = YES;
    popover.behavior = NSPopoverBehaviorTransient;
    [popover showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge];
}


#pragma mark - NSNotification Methods
- (void)deviceActivateStatusChangeNotification:(NSNotification *)notification {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self reloadData];
    });
}

- (void)IAPResultReceived:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reloadData];
    });

}

- (void)IAPPurchaseSuccess:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reloadData];
    });
}

- (void)IAPRestoreFinish:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reloadData];
    });
}

#pragma mark - Event
- (void)mouseEntered:(NSEvent *)event {
    if (ActivityStatusTrialExpire == [VerificationManager manager].status ||
        ActivityStatusTrial == [VerificationManager manager].status) {
        [[self class] cancelPreviousPerformRequestsWithTarget:self];
        if (!self.popover.isShown) {
            [self buttonAction:self.button];
        }
    }
}

- (void)mouseExited:(NSEvent *)event {
    [super mouseExited:event];
    
    [self performSelector:@selector(popOverCloseAction) withObject:nil afterDelay:0.35];
}

- (void)popoverDidClose:(NSNotification *)notification {
    self.stopPopOverHide = NO;
}
    
- (void)popoverShowNoti:(NSNotification *)noti {
    if (self.popover) {
        [self.popover close];
        self.stopPopOverHide = NO;
    }
}

- (void)popOverCloseAction {
    if (self.stopPopOverHide == NO) {
        if (ActivityStatusTrialExpire == [VerificationManager manager].status ||
            ActivityStatusTrial == [VerificationManager manager].status) {
            if (self.popover.isShown) {
                [self.popover close];
                self.stopPopOverHide = NO;
            }
        }
    }
}

@end