//
//  KMAnnotationLinkViewController.m
//  SignFlow
//
//  Created by wanjun on 2021/6/23.
//

#import "KMAnnotationLinkViewController.h"
#import "NSButton+TitleColor.h"
#import "TextFieldFormatter.h"
#import "KMBox.h"
#import <ComPDFKit/ComPDFKit.h>
#import "KMCoverButton.h"

#define URLPlaceholder @"https://www.pdfreaderpro.com"
#define EmailPlaceholder @"support@pdfreaderpro.com"

typedef NS_ENUM(NSUInteger, KMAnnotationLinkType) {
    KMAnnotationLinkType_Page = 0,
    KMAnnotationLinkType_URL,
    KMAnnotationLinkType_Email
};

typedef NS_ENUM(NSUInteger, KMAnnotationLinkState) {
    KMAnnotationLinkStateNormal = 0,
    KMAnnotationLinkStateHover,
    KMAnnotationLinkStateSelected
};

@interface KMAnnotationLinkViewController () <NSTextFieldDelegate>

@property (weak) IBOutlet NSView *linkStyleView;

@property (assign) IBOutlet KMBox *linkPageBox;
@property (assign) IBOutlet NSImageView *linkPageImageView;
@property (weak) IBOutlet NSImageView *pageImageThumible;
@property (weak) IBOutlet KMCoverButton *targetButton;
@property (weak) IBOutlet NSTextField *targetLabel;
@property (weak) IBOutlet NSBox *tagrgetBox;

@property (assign) IBOutlet KMBox *linkUrlBox;
@property (assign) IBOutlet NSImageView *linkUrlImageView;

@property (assign) IBOutlet KMBox *linkEmailBox;
@property (assign) IBOutlet NSImageView *linkEmailImageView;

@property (assign) IBOutlet NSBox *contentBox;

@property (assign) IBOutlet NSView *urlView;
@property (assign) IBOutlet NSTextField *urlLabel;
@property (assign) IBOutlet NSTextField *inputUrlTextField;
@property (weak) IBOutlet NSBox *inputUrlBox;


@property (assign) IBOutlet NSButton *goButton;
@property (assign) IBOutlet NSTextField *errorLabel;
@property (weak) IBOutlet NSLayoutConstraint *goButtonTopComstraint;

@property (nonatomic, retain) CPDFLinkAnnotation *annotation;

@property (nonatomic, assign) KMAnnotationLinkType linkType;

@property (nonatomic, retain) KMBox *mouseDownBox;

@property (nonatomic, copy) NSString *pageRecord;
@property (nonatomic, copy) NSString *urlRecord;
@property (nonatomic, copy) NSString *emailRecord;
@property (nonatomic, copy) NSString *startPage;
@property (nonatomic, assign) BOOL isGo;

@property (nonatomic, strong) NSColor *boxNormalBorderColor;
@property (nonatomic, strong) NSColor *boxErrorBorderColor;
@property (nonatomic, assign) KMAnnotationLinkState targetButtonState;

@end

@implementation KMAnnotationLinkViewController

#pragma mark - Init Methods

- (instancetype)init {
    if (self = [super init]) {
        self.boxNormalBorderColor = [NSColor colorWithRed:223.0/255.0 green:225.0/255.0 blue:229.0/255.0 alpha:1];
        self.boxErrorBorderColor = [NSColor colorWithRed:243/255.f green:70/255.f blue:91/255.f alpha:1.f];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _inputUrlTextField.delegate = nil;
    
    NSLog(@"%s", __func__);
}

#pragma mark - View Methods

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.annotation = (CPDFLinkAnnotation *)self.annotationModel.annotation;
    
    self.pageRecord = @"";
    self.urlRecord = @"";
    self.emailRecord = @"";
        
    _linkStyleView.wantsLayer =
    _linkPageImageView.wantsLayer =
    _linkUrlImageView.wantsLayer =
    _linkEmailImageView.wantsLayer = YES;
    
    _linkStyleView.layer.backgroundColor = [NSColor colorWithRed:223.0/255.0 green:225.0/255.0 blue:229.0/255.0 alpha:1].CGColor;
    _linkStyleView.layer.cornerRadius = 6.0;
    _linkStyleView.layer.masksToBounds = YES;
    
    NSArray <KMBox *>*boxArr = @[_linkPageBox, _linkUrlBox, _linkEmailBox];
    __weak typeof(self) weakSelf = self;
    for (KMBox *box in boxArr) {
        box.mouseDownCallback = ^(BOOL downEntered, KMBox *mouseBox) {
            if (downEntered) {
                if ([weakSelf.mouseDownBox isEqual:mouseBox]) {
                    return;
                }
                NSInteger mouseDownInt = 0;
                if ([weakSelf.linkPageBox isEqual:mouseBox]) {
                    weakSelf.inputUrlTextField.stringValue = @"";
                    weakSelf.linkType = KMAnnotationLinkType_Page;
                    mouseDownInt = 0;
                } else if ([weakSelf.linkUrlBox isEqual:mouseBox]) {
                    weakSelf.inputUrlTextField.stringValue = @"";
                    weakSelf.linkType = KMAnnotationLinkType_URL;
                    mouseDownInt = 1;
                } else if ([weakSelf.linkEmailBox isEqual:mouseBox]) {
                    weakSelf.inputUrlTextField.stringValue = @"";
                    weakSelf.linkType = KMAnnotationLinkType_Email;
                    mouseDownInt = 2;
                }
                [[NSUserDefaults standardUserDefaults] setObject:@(mouseDownInt) forKey:@"kmLinkSelectIndex"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                weakSelf.mouseDownBox = mouseBox;
            }
        };
    }
    
    self.isGo = YES;
    
    self.targetLabel.stringValue = NSLocalizedStringFromTable(@"Locate the target page", @"MainMenu", nil);
    self.inputUrlTextField.wantsLayer = YES;

    self.inputUrlTextField.focusRingType = NSFocusRingTypeNone;
    self.linkPageImageView.layer.cornerRadius =
    self.linkUrlImageView.layer.cornerRadius =
    self.linkEmailImageView.layer.cornerRadius = 4.0f;
    [[self.inputUrlTextField cell] setAllowedInputSourceLocales:@[NSAllRomanInputSourcesLocaleIdentifier]];
    
    if (_linkType == KMAnnotationLinkType_Email) {
        [self setLinkType:KMAnnotationLinkType_Email];
        self.mouseDownBox = _linkEmailBox;
    } else if (_linkType == KMAnnotationLinkType_URL) {
        [self setLinkType:KMAnnotationLinkType_URL];
        self.mouseDownBox = _linkUrlBox;
    } else if (_linkType == KMAnnotationLinkType_Page) {
        [self setLinkType:KMAnnotationLinkType_Page];
        self.mouseDownBox = _linkPageBox;
    }
    
    self.targetButton.coverAction = ^(KMCoverButton * _Nonnull button, KMCoverAction action) {
        if (weakSelf.targetButtonState == KMAnnotationLinkStateSelected) {
            return;
        }
        if (action == KMCoverActionEnter) {
            [weakSelf updateTargetBoxState:KMAnnotationLinkStateHover];
        } else if (action == KMCoverActionExit) {
            [weakSelf updateTargetBoxState:KMAnnotationLinkStateNormal];
        }
    };
    
    [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^NSEvent * _Nullable(NSEvent * _Nonnull event) {
        if (event.keyCode == 53) {
            if ([self.inputUrlTextField isEditable]) {
                [self.pdfview setAnnotationType:CAnnotationTypeUnkown];
            }
        }
        return event;
    }];
}

- (void)viewDidAppear {
    [super viewDidAppear];
    self.inputUrlTextField.delegate = self;
    [_inputUrlTextField becomeFirstResponder];
}

- (void)setupUI {
    [super setupUI];
    
    NSString *fontName = @"SFProText-Regular";
    
    self.urlLabel.font = [NSFont fontWithName:fontName size:12];
    self.urlLabel.textColor= [NSColor colorWithRed:97.0/255.0 green:100.0/255.0 blue:105.0/255.0 alpha:1];
    
    self.inputUrlBox.borderColor = self.boxNormalBorderColor;
    self.inputUrlBox.fillColor = [NSColor whiteColor];
    self.errorLabel.textColor = self.boxErrorBorderColor;
    self.errorLabel.font = [NSFont fontWithName:fontName size:12];
    
    self.tagrgetBox.fillColor = [NSColor whiteColor];
    [self updateTargetBoxState:KMAnnotationLinkStateNormal];
    self.targetLabel.font = [NSFont fontWithName:fontName size:14];
    self.targetLabel.textColor = [NSColor colorWithRed:37/255.f green:38/255.f blue:41/255.f alpha:1.f];
    
    [self.goButton setTitle:NSLocalizedString(@"Go", nil)];
    [self.goButton setTitleColor:[NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:1]];
}

- (void)setLinkType:(KMAnnotationLinkType)linkType {
    _linkType = linkType;
    switch (_linkType) {
        case KMAnnotationLinkType_Page:
        {
            [self createLinkPageView];
            [_inputUrlTextField becomeFirstResponder];
        }
            break;
        case KMAnnotationLinkType_URL:
        {
            [self createLinkURLView];
            [_inputUrlTextField becomeFirstResponder];
        }
            break;
        case KMAnnotationLinkType_Email:
        {
            [self createLinkEmailView];
            [_inputUrlTextField becomeFirstResponder];
        }
            break;
        default:
            break;
    }
}

- (void)setContent:(NSString *)content
{
    if (_content) {
        _content = nil;
    }
    
    if (![content isEqualToString:@""]){
        if ([content length] > 0) {
            unsigned char typelocal = [content characterAtIndex:0];
            if (typelocal == '0') {
                _content = [content substringFromIndex:1];
                [self setLinkType:KMAnnotationLinkType_Page];
                self.inputUrlTextField.stringValue = _content;
                self.mouseDownBox = _linkPageBox;
            }else{
                if ([[content substringFromIndex:1] hasPrefix:@"mailto:"]) {
                    _content = [content substringFromIndex:8];
                    [self setLinkType:KMAnnotationLinkType_Email];
                    self.mouseDownBox = _linkEmailBox;
                } else {
                    _content = [content substringFromIndex:1];
                    [self setLinkType:KMAnnotationLinkType_URL];
                    self.mouseDownBox = _linkUrlBox;
                }
            }
            
        }
    } else {
        _content = [NSString stringWithFormat:@"http://"];
        [self setLinkType:KMAnnotationLinkType_URL];
        self.mouseDownBox = _linkUrlBox;
    }
}

- (void)setPdfview:(CPDFListView *)pdfview {
    [super setPdfview:pdfview];
    
    self.startPage = [NSString stringWithFormat:@"%ld", (self.pdfview.currentPageIndex + 1)];
}

- (void)setIsCreateLink:(BOOL)isCreateLink {
    _isCreateLink = isCreateLink;
    if (isCreateLink) {
        [self setLinkType:KMAnnotationLinkType_Page];
        self.mouseDownBox = _linkPageBox;
    }
}


#pragma mark - private

- (void)createLinkPageView {
    [self annotationLinkSelectBox:_linkPageBox];
    _urlLabel.stringValue = NSLocalizedString(@"Page", nil);
    
    [self.inputUrlTextField setFormatter:[[TextFieldFormatter alloc] init]];
    if (self.pdfview.document.pageCount > 1) {
//        self.inputUrlTextField.placeholderString = [NSString stringWithFormat:@"1-%ld",_pageCount];
        self.inputUrlTextField.placeholderString = NSLocalizedString(@"Enter target page", nil);
    } else {
        self.inputUrlTextField.placeholderString = @"1";
    }
    
    if (_annotation.destination) {
        NSInteger pageIndex = self.annotation.destination.pageIndex;
        self.inputUrlTextField.stringValue = [NSString stringWithFormat:@"%@",@(pageIndex+1)];
        self.pageRecord = [NSString stringWithFormat:@"%@",@(pageIndex+1)];
    }
    
    if (self.inputUrlTextField.stringValue.length == 0) {
        self.inputUrlTextField.stringValue = self.pageRecord;
    }
    
    self.tagrgetBox.hidden = NO;
    self.pageImageThumible.hidden = YES;
    self.goButton.hidden = YES;
    self.goButtonTopComstraint.constant = 20;
    self.errorLabel.stringValue = NSLocalizedString(@"Page number out of range", nil);
    
    if (self.inputUrlTextField.stringValue.length == 0) {

    } else {
        NSUInteger dexPage = [self.inputUrlTextField.stringValue integerValue];
        [self dealThumibleImage:dexPage];
    }
}

- (void)createLinkURLView {
    [self annotationLinkSelectBox:_linkUrlBox];
    _urlLabel.stringValue = NSLocalizedString(@"URL:", nil);

    [self.inputUrlTextField setFormatter:nil];
    self.inputUrlTextField.placeholderString = @"https://www.pdfreaderpro.com";
    if (_annotation.URL) {
        NSString *urlString = self.annotation.URL;
        if ([urlString hasPrefix:@"http://"]) {
            urlString = [urlString substringFromIndex:7];
            self.inputUrlTextField.stringValue = urlString ? : @"";
            self.urlRecord = urlString ? : @"";
        } else if ([urlString hasPrefix:@"https://"]) {
            urlString = [urlString substringFromIndex:8];
            self.inputUrlTextField.stringValue = urlString ? : @"";
            self.urlRecord = urlString ? : @"";
        }
    }
    
    if (self.inputUrlTextField.stringValue.length == 0) {
        self.inputUrlTextField.stringValue = self.urlRecord;
    }
    self.tagrgetBox.hidden = YES;
    self.pageImageThumible.hidden = YES;
    self.goButton.hidden = YES;
    self.goButtonTopComstraint.constant = -390;
    self.errorLabel.stringValue = NSLocalizedString(@"nvalid Email. Please re-enter correct email.", nil);
    [self.goButton setTitle:NSLocalizedString(@"Go", nil)];
    [self.goButton setTitleColor:[NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:1]];
    if(self.inputUrlTextField.stringValue.length > 0) {
        self.goButton.hidden = NO;
    }
}

- (void)createLinkEmailView {
    [self annotationLinkSelectBox:_linkEmailBox];
    _urlLabel.stringValue = NSLocalizedString(@"Email:", nil);
    [self.inputUrlTextField setFormatter:nil];
    self.inputUrlTextField.placeholderString = @"support@pdfreaderpro.com";
    
    if ([self.annotation.URL containsString:@"mailto"]) {
        NSString *urlString = self.annotation.URL;
        if ([urlString hasPrefix:@"mailto:"]) {
            urlString = [urlString substringFromIndex:7];
            self.inputUrlTextField.stringValue = urlString ? : @"";
            self.emailRecord = urlString ? : @"";
        }
        if (self.inputUrlTextField.stringValue.length == 0) {
            self.inputUrlTextField.stringValue = self.emailRecord;
        }
    }
    self.tagrgetBox.hidden = YES;
    self.pageImageThumible.hidden = YES;
    self.goButton.hidden = YES;
    self.goButtonTopComstraint.constant = -390;
    self.errorLabel.stringValue = NSLocalizedString(@"nvalid Email. Please re-enter correct email.", nil);
    [self.goButton setTitle:NSLocalizedString(@"Go", nil)];
    [self.goButton setTitleColor:[NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:1]];
    if(self.inputUrlTextField.stringValue.length > 0) {
        self.goButton.hidden = NO;
    }
}

- (BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
    return [emailTest evaluateWithObject:email];
}

- (NSString *)judgeWebURL:(NSString *)urlString {
    if (![urlString hasPrefix:@"http://"] && ![urlString hasPrefix:@"https://"]) {
        urlString = [NSString stringWithFormat:@"https://%@",urlString];
    }
    if ([urlString isEqualToString:@"https://"]) {
        urlString = @"";
    }
    return urlString;
}

- (NSString *)judgeEmailURL:(NSString *)urlString {
    if (![urlString hasPrefix:@"mailto:"]) {
        urlString = [NSString stringWithFormat:@"mailto:%@",urlString];
    }
    if ([urlString isEqualToString:@"mailto:"]) {
        urlString = @"";
    }
    return urlString;
}

- (void)annotationLinkSelectBox:(KMBox *)box {
    if ([box isEqual:_linkPageBox]) {
        _linkPageBox.fillColor = [NSColor whiteColor];
        _linkEmailBox.fillColor =
        _linkUrlBox.fillColor = [NSColor clearColor];
        _linkPageImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkPageSel"];
        _linkUrlImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkUrlNor"];
        _linkEmailImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkEmailNor"];
        NSUInteger dexPage = [_pageRecord integerValue];
        if(_pageRecord.length < 1) return;
        if (dexPage < 1 || dexPage > _pageCount) {
            _errorLabel.hidden = NO;
        } else {
            _errorLabel.hidden = YES;
        }
    } else if ([box isEqual:_linkUrlBox]) {
        _linkUrlBox.fillColor = [NSColor whiteColor];
        _linkEmailBox.fillColor =
        _linkPageBox.fillColor = [NSColor clearColor];
        _linkPageImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkPageNor"];
        _linkUrlImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkUrlSel"];
        _linkEmailImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkEmailNor"];
        _errorLabel.hidden = YES;
    } else if ([box isEqual:_linkEmailBox]) {
        _linkEmailBox.fillColor = [NSColor whiteColor];
        _linkUrlBox.fillColor =
        _linkPageBox.fillColor = [NSColor clearColor];
        _linkPageImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkPageNor"];
        _linkUrlImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkUrlNor"];
        _linkEmailImageView.image = [NSImage imageNamed:@"KMImageNamePropertybarLinkEmailSel"];
        _errorLabel.hidden = YES;
    }
    
    [self updateInputUrlBoxState];
}

- (void)updateInputUrlBoxState {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.errorLabel.isHidden) {
            self.inputUrlBox.borderColor = self.boxNormalBorderColor;
        } else {
            self.inputUrlBox.borderColor = self.boxErrorBorderColor;
        }
    });
}

- (void)updateTargetBoxState:(KMAnnotationLinkState)state {
    self.targetButtonState = state;
    if ([NSThread isMainThread]) {
        if (state == KMAnnotationLinkStateNormal) {
            self.tagrgetBox.borderColor = self.boxNormalBorderColor;
        } else if (state == KMAnnotationLinkStateHover) {
            self.tagrgetBox.borderColor = [NSColor colorWithRed:104/255.f green:172/255.f blue:248/255.f alpha:1.f];
        } else if (state == KMAnnotationLinkStateSelected) {
            self.tagrgetBox.borderColor = [NSColor colorWithRed:23/255.f green:112/255.f blue:244/255.f alpha:1.f];
        }
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (state == KMAnnotationLinkStateNormal) {
                self.tagrgetBox.borderColor = self.boxNormalBorderColor;
            } else if (state == KMAnnotationLinkStateHover) {
                self.tagrgetBox.borderColor = [NSColor colorWithRed:104/255.f green:172/255.f blue:248/255.f alpha:1.f];
            } else if (state == KMAnnotationLinkStateSelected) {
                self.tagrgetBox.borderColor = [NSColor colorWithRed:23/255.f green:112/255.f blue:244/255.f alpha:1.f];
            }
        });
    }
}

- (void)dealThumibleImage:(NSUInteger)dexPage {
    if ((dexPage >0 || dexPage < _pageCount) && _pageRecord.length > 0) {
        self.pageImageThumible.hidden = NO;
        self.goButton.hidden = NO;
        NSInteger goPage = [self.inputUrlTextField.stringValue integerValue] - 1;
        CPDFPage *page = [self.pdfview.document pageAtIndex:goPage];
        self.pageImageThumible.image = [page thumbnailOfSize:[page boundsForBox:CPDFDisplayMediaBox].size];
    } else {
        self.pageImageThumible.hidden = YES;
        self.goButton.hidden = YES;
    }
}

#pragma mark - Action

- (IBAction)goButtonAction:(NSButton *)sender {
    switch (_linkType) {
        case KMAnnotationLinkType_Page:
        {
            if(sender == self.goButton) {
                [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:nil];
             
                NSUInteger dexPage;
                if (_isGo) {
                    _isGo = NO;
                    self.startPage = [NSString stringWithFormat:@"%ld", (self.pdfview.currentPageIndex + 1)];
                    
                    dexPage = [self.inputUrlTextField.stringValue integerValue];

                    [self.goButton setTitle:NSLocalizedString(@"Go Back", nil)];
                    [self.goButton setTitleColor:[NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:1]];
                } else {
                    _isGo = YES;
                    dexPage = [self.startPage integerValue];
                    [self.goButton setTitle:NSLocalizedString(@"Go", nil)];
                    [self.goButton setTitleColor:[NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:1]];
                }

                if (dexPage < 1 || dexPage > _pageCount) {
                    NSAlert *alert = [[NSAlert alloc] init];
                    [alert setAlertStyle:NSAlertStyleCritical];
                    [alert setMessageText:NSLocalizedString(@"Invalid page range or the page number is out of range. Please try again.", nil)];
                    [alert runModal];
                    return;
                }
                NSInteger goPage = [self.inputUrlTextField.stringValue integerValue];
                CPDFDestination *destination = self.targetDestination;
                if (!destination) {
                   destination = [[CPDFDestination alloc] initWithDocument:self.pdfview.document pageIndex:(goPage-1)];
                }
                
                [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setDestination:destination];
                [self.pdfview setNeedsDisplayAnnotation:_annotation];

                if (_isGo) {
                    if (self.startDestination) {
                        [self.pdfview goToDestination:self.startDestination];
                        return;
                    }
                } else {
                    if (self.targetDestination) { // 目标定位模式
                        [self.pdfview goToDestination:self.targetDestination];
                        return;
                    }
                }
                
                CPDFDestination *dest = [[CPDFDestination alloc] initWithDocument:self.pdfview.document pageIndex:(dexPage-1)];
                if (dest){
                    [self.pdfview goToPageIndex:dest.pageIndex animated:YES];
                }
                return;
            }
            [self updateTargetBoxState:KMAnnotationLinkStateSelected];
            [self.pdfview setIsSetLinkDestinationArea:YES];
        }
            break;
        case KMAnnotationLinkType_URL:
        {
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setDestination:nil];

            NSString *linkUrlPath = [self judgeWebURL:self.inputUrlTextField.stringValue];
            
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:linkUrlPath];
            [self.pdfview setNeedsDisplayAnnotation:_annotation];

            NSURL *url = [NSURL URLWithString:[(CPDFLinkAnnotation *)self.pdfview.activeAnnotation URL]];
            [[NSWorkspace sharedWorkspace] openURL:url];
        }
            break;
        case KMAnnotationLinkType_Email:
        {
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setDestination:nil];

            if (![self isValidateEmail:self.inputUrlTextField.stringValue]) {
                NSAlert *alert = [[NSAlert alloc] init];
                [alert setAlertStyle:NSAlertStyleCritical];
                [alert setMessageText:NSLocalizedString(@"Invalid email address. Please enter a valid email address.", nil)];
                [alert runModal];
                return;
            }
            
            NSString *linkUrlPath = [self judgeEmailURL:self.inputUrlTextField.stringValue];
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:linkUrlPath];
            [self.pdfview setNeedsDisplayAnnotation:_annotation];

            NSURL *url = [NSURL URLWithString:[(CPDFLinkAnnotation *)self.pdfview.activeAnnotation URL]];
            [[NSWorkspace sharedWorkspace] openURL:url];
        }
            break;
        default:
            break;
    }
}

#pragma mark - NSTextFieldDelegate Methods

- (void)controlTextDidChange:(NSNotification *)obj {
    NSTextField *textField = (NSTextField *)obj.object;

    _errorLabel.hidden = YES;
    if ([_mouseDownBox isEqual:_linkPageBox]) {
        _pageRecord = textField.stringValue;
    } else if ([_mouseDownBox isEqual:_linkUrlBox]) {
        _urlRecord = textField.stringValue;
    } else if ([_mouseDownBox isEqual:_linkEmailBox]) {
        _emailRecord = textField.stringValue;
    }

    if (_linkType == KMAnnotationLinkType_Page) {
        [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:nil];

        NSUInteger dexPage = [self.inputUrlTextField.stringValue integerValue];

        if ((dexPage < 1 || dexPage > _pageCount) && _pageRecord.length > 0) {
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setDestination:nil];
            _errorLabel.hidden = NO;
            [self updateInputUrlBoxState];
            return;
        } else if(_pageRecord.length > 0){
            _errorLabel.hidden = YES;
        }
        CPDFPage *page = [self.pdfview.document pageAtIndex:(dexPage-1)];
        CPDFDestination *destination = [[CPDFDestination alloc] initWithDocument:self.pdfview.document pageIndex:(dexPage-1)  atPoint:CGPointMake(0, page.bounds.size.height) zoom:self.pdfview.scaleFactor];

        [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setDestination:destination];
        [self.pdfview setNeedsDisplayAnnotationViewForPage:self.pdfview.activeAnnotation.page];
        
        ///显示预览图
        [self dealThumibleImage:dexPage];
        
        [self updateInputUrlBoxState];
    } else if (_linkType == KMAnnotationLinkType_URL) {
        [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setDestination:nil];
//        NSString *linkUrlPath = [self judgeWebURL:_urlRecord];
        NSString *linkUrlPath = _urlRecord;
        if ([linkUrlPath isEqualToString:@""]) {
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:nil];
        } else {
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:linkUrlPath];
        }
        [self.pdfview setNeedsDisplayAnnotationViewForPage:self.pdfview.activeAnnotation.page];

    } else if (_linkType == KMAnnotationLinkType_Email) {
        [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setDestination:nil];
        NSString *linkUrlPath = [self judgeEmailURL:_emailRecord];
        if ([linkUrlPath isEqualToString:@""]) {
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:nil];
        } else {
            [(CPDFLinkAnnotation *)self.pdfview.activeAnnotation setURL:linkUrlPath];
        }
        [self.pdfview setNeedsDisplayAnnotationViewForPage:self.pdfview.activeAnnotation.page];
    }
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
    if (commandSelector == @selector(insertNewline:)) {
        [self.view.window makeFirstResponder:self.pdfview];
        return YES;
    }
    return NO;
}

- (void)mouseDown:(NSEvent *)event {
    [super mouseDown:event];
    
    [self.view.window makeFirstResponder:self.pdfview];
}

//- (void)controlTextDidEndEditing:(NSNotification *)obj {
//    switch (_linkType) {
//        case KMAnnotationLinkType_Page: {
//            NSUInteger dexPage = [self.inputUrlTextField.stringValue integerValue];
//            if ((dexPage <0 || dexPage > _pageCount) && _pageRecord.length > 0) {
//                self.errorLabel.hidden = NO;
//            } else {
//                self.errorLabel.hidden = YES;
//                NSInteger goPage = [self.inputUrlTextField.stringValue integerValue];
//                CPDFDestination *destination = [[CPDFDestination alloc] initWithDocument:_pdfview.document pageIndex:(goPage-1)];
//
//                [(CPDFLinkAnnotation *)_pdfview.activeAnnotation setDestination:destination];
//                [_pdfview setNeedsDisplayAnnotationViewForPage:_pdfview.activeAnnotation.page];
//            }
//            self.goButton.hidden = YES;
//        }
//            break;
//        case KMAnnotationLinkType_URL:
//        {
//            if (self.urlRecord.length > 0) {
//                [(CPDFLinkAnnotation *)_pdfview.activeAnnotation setDestination:nil];
//
//                NSString *linkUrlPath = [self judgeWebURL:self.urlRecord];
//
//                [(CPDFLinkAnnotation *)_pdfview.activeAnnotation setURL:linkUrlPath];
//                [_pdfview setNeedsDisplayAnnotationViewForPage:_pdfview.activeAnnotation.page];
//                self.goButton.hidden = NO;
//            } else {
//                self.goButton.hidden = YES;
//            }
//        }
//            break;
//        case KMAnnotationLinkType_Email:
//        {
//            if (self.emailRecord.length == 0) return;
//            if (![self isValidateEmail:self.emailRecord]) {
//                self.errorLabel.hidden = NO;
//                self.goButton.hidden = YES;
//                return;
//            }
//            self.errorLabel.hidden = YES;
//            self.goButton.hidden = NO;
//            [(CPDFLinkAnnotation *)_pdfview.activeAnnotation setDestination:nil];
//            NSString *linkUrlPath = [self judgeEmailURL:self.emailRecord];
//            [(CPDFLinkAnnotation *)_pdfview.activeAnnotation setURL:linkUrlPath];
//            [_pdfview setNeedsDisplayAnnotationViewForPage:_pdfview.activeAnnotation.page];
//        }
//            break;
//        default:
//            break;
//    }
//}

@end