//
//  KMBatchOperateAddWatermarkViewController.swift
//  PDF Master
//
//  Created by tangchao on 2023/11/3.
//

import Cocoa

enum KMWatermarkType: Int {
    case txt = 0
    case file
}

class KMCollectionViewFlowLayout: NSCollectionViewFlowLayout {
    override func shouldInvalidateLayout(forBoundsChange newBounds: NSRect) -> Bool {
        self.collectionView?.reloadSections(IndexSet(integer: 0))
        return true
    }
}

class KMBatchOperateAddWatermarkViewController: KMBatchOperateBaseViewController {
    var isBackground = false
    var onlyManagerTemplate = false
    
    weak var pdfView: CPDFView?
    var isBatchOperation = false //是否在批量界面
    
    @IBOutlet var topBaseView: NSView!
    @IBOutlet var titleLabel: NSTextField!
    @IBOutlet var addButton: NSButton!
    @IBOutlet var textButton: NSButton!
    @IBOutlet var fileButton: NSButton!
    @IBOutlet var textBox: NSBox!
    @IBOutlet var fileBox: NSBox!
    @IBOutlet var actionButton: NSButton!
    @IBOutlet var collectionView: NSCollectionView!
    @IBOutlet var bottomBaseView: NSView!
    @IBOutlet var managerTemplateTitleLabel: NSTextField!
    
    @IBOutlet var blankView: KMBlankView!
    
    @IBOutlet var managerTemplateButtonTopConstraint: NSLayoutConstraint!
    @IBOutlet var managerTemplateButtonHeightConstraint: NSLayoutConstraint!
    @IBOutlet var topHeightConstraint: NSLayoutConstraint!
    @IBOutlet var addButtonHeightConstraint: NSLayoutConstraint!
    @IBOutlet var addButtonBottomConstraint: NSLayoutConstraint!
    
    private var _textTemplateArray: [NSObject]?
    private var _fileTemplateArray: [NSObject]?
    
    private var _currentTextData: KMPDFWatermarkData?
    private var _currentFileData: KMPDFWatermarkData?
    
    private var _currentColorData: KMBackgroundObject?
    private var _currentImageData: KMBackgroundObject?
     
    private var _currentBackgroundType: KMBackgroundType = .color
    var currentBackgroundType: KMBackgroundType {
        get {
            return self._currentBackgroundType
        }
        set {
            if (self._currentBackgroundType != newValue) {
                self._currentBackgroundType = newValue
                
                if (self._currentBackgroundType == .color) {
        //            self.textButton.layer.backgroundColor = [KMAppearance KMColor_Interactive_A0].CGColor;
        //            self.fileButton.layer.backgroundColor = [KMAppearance KMColor_Layout_L_1].CGColor;
                    self.textBox.fillColor = KMAppearance.Interactive.a0Color()
                    self.fileBox.fillColor = KMAppearance.Layout.l_1Color()
                    
                    self.textButton.setTitleColor(KMAppearance.Layout.w0Color())
                    self.fileButton.setTitleColor(KMAppearance.Layout.h1Color())
                } else {
        //            self.fileButton.layer.backgroundColor = [KMAppearance KMColor_Interactive_A0].CGColor;
        //            self.textButton.layer.backgroundColor = [KMAppearance KMColor_Layout_L_1].CGColor;
                    self.textBox.fillColor = KMAppearance.Layout.l_1Color()
                    self.fileBox.fillColor = KMAppearance.Interactive.a0Color()
                    
                    self.fileButton.setTitleColor(KMAppearance.Layout.w0Color())
                    self.textButton.setTitleColor(KMAppearance.Layout.h1Color())
                }
                self.collectionView.reloadData()
            }
        }
    }
    
    private var _currentType: KMWatermarkType = .txt
    var currentType: KMWatermarkType {
        set {
            if self.currentType != newValue {
                self._currentType = newValue
                
                if (currentType == .txt) {
        //            self.textButton.layer.backgroundColor = [KMAppearance KMColor_Interactive_A0].CGColor;
        //            self.fileButton.layer.backgroundColor = [KMAppearance KMColor_Layout_L_1].CGColor;
                    self.textBox.fillColor = KMAppearance.Interactive.a0Color()
                    self.fileBox.fillColor = KMAppearance.Layout.l_1Color()
                    self.textButton.setTitleColor(KMAppearance.Layout.w0Color())
                    self.fileButton.setTitleColor(KMAppearance.Layout.h1Color())
                } else {
        //            self.fileButton.layer.backgroundColor = [KMAppearance KMColor_Interactive_A0].CGColor;
        //            self.textButton.layer.backgroundColor = [KMAppearance KMColor_Layout_L_1].CGColor;
                    self.textBox.fillColor = KMAppearance.Layout.l_1Color()
                    self.fileBox.fillColor = KMAppearance.Interactive.a0Color()
                    self.fileButton.setTitleColor(KMAppearance.Layout.w0Color())
                    self.textButton.setTitleColor(KMAppearance.Layout.h1Color())
                }
                self.collectionView.reloadData()
            }
        }
        get {
            return self._currentType
        }
    }
    
    private var _haveFiles = false
    
    deinit {
        KMPrint("KMBatchOperateAddWatermarkViewController deinit.")
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self._localizedlanguage()
        self._configuiUI()
        self._loadData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(_watermarksNotification), name: NSNotification.Name("KMBatchOperateWatermarksNotification"), object: nil)
    }
     
    func watermarkInterfaceSelectWatermark(_ watermark: KMPDFWatermarkData) {
        if(watermark.image != nil) {
            self._currentFileData = watermark
        }else {
            self._currentTextData = watermark
        }

        self._loadData()
        self.currentType = watermark.image != nil ? .file : .txt
        let arr = self.currentType == .file ? self._fileTemplateArray : self._textTemplateArray
        let index = arr?.index(of: watermark)
        if (index != NSNotFound) {
            let indexpath = IndexPath(item: index!, section: 0)
            var set = Set<IndexPath>()
            set.insert(indexpath)
            self.collectionView.selectItems(at: set, scrollPosition: .bottom)
        }
    }
    
    func backgroundInterfaceSelectBackGround(_ background: KMBackgroundObject) {
        if(background.type == .file) {
            self._currentImageData = background
        }else {
            self._currentColorData = background
        }
        
        self._loadData()
        self.currentBackgroundType = background.type
        let arr = self.currentBackgroundType == .file ? self._fileTemplateArray : self._textTemplateArray
        let index = arr?.index(of: background)
        if (index != NSNotFound) {
            let indexpath = IndexPath(item: index!, section: 0)
            var set = Set<IndexPath>()
            set.insert(indexpath)
            self.collectionView.selectItems(at: set, scrollPosition: .bottom)
        }
    }
    
    override var interfaceStatus: KMBatchOperateInterfaceStatus? {
        didSet {
            if (self.interfaceStatus == .PrepareProcess) {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
                    var files: [URL] = []
                    for url in self.successFilePathURLArray ?? [] {
                        if FileManager.default.fileExists(atPath: url.path) {
                            files.append(url)
                        }
                    }
                    if (files.count > 0) {
                        let workspace = NSWorkspace.shared
                        workspace.activateFileViewerSelecting(files)
                    }
                }

                self.collectionView.isSelectable = true
                self.actionButton.tag = 1
        //        if (self.isBackground) {
        //            self.actionButton.title = NSLocalizedString(@"Add Background", nil);
        //        } else {
        //            self.actionButton.title = NSLocalizedString(@"Add Watermark", nil);
        //        }
                self.actionButton.title = KMLocalizedString("Apply", nil)
                self.addButton.isEnabled = true
        //        if (self.onlyManagerTemplate) {
        //            self.actionButton.title = NSLocalizedString(@"Add Template", nil);
        //        }
            } else {
                self.collectionView.isSelectable = false
                self.addButton.isEnabled = false
                self.actionButton.tag = 0
                self.actionButton.title = KMLocalizedString("Cancel", nil);
            }
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
        }
    }
    
    //button Actions,切换水印类型
    @IBAction func funcbuttonClicked_SwitchWaterMarkType(_ sender: NSButton) {
        if (self.isBackground) {
            self.currentBackgroundType = KMBackgroundType(rawValue: sender.tag) ?? .color
        } else {
            self.currentType = KMWatermarkType(rawValue: sender.tag) ?? .txt
        }
        self._updateActionButtonbackgroundColor()
    }
    
    @IBAction func buttonClicked_addWaterMark(_ sender: NSButton) {
        if (!self.onlyManagerTemplate) {
            if (!self._haveFiles) {
                return
            }
        }
        
        self.view.window?.makeFirstResponder(nil)
    //    if (self.onlyManagerTemplate) {
    //        [self buttonClicked_addtemplate:sender];
    //        return;
    //    }
    //    //点击开始
    //    if (sender.tag == 1) {
    //        if (![self checkAndResetTask]) {
    //            NSBeep();
    //            return;
    //        }
    //        KMPDFWatermark *watermark = nil;
    //        KMBackgroundObject *background = nil;
    //        NSIndexSet *indexSet = self.collectionView.selectionIndexes;
    //        if (indexSet.firstIndex == NSNotFound || self.files.count < 1) {
    //            NSBeep();
    //            return;
    //        } else {
    //            NSUInteger index = indexSet.firstIndex;
    //
    //            if (!self.isBackground) {
    //                if (self.currentType == KMWatermarkType_Txt) {
    //                    watermark = [self.textTemplateArray objectAtIndex:index];
    //                } else {
    //                    watermark = [self.fileTemplateArray objectAtIndex:index];
    //                }
    //            } else {
    //                if (self.currentBackgroundType == KMBackgroundType_Color) {
    //                    background = [self.textTemplateArray objectAtIndex:index];
    //                } else {
    //                    background = [self.fileTemplateArray objectAtIndex:index];
    //                }
    //            }
    //
    //        }
    //
    //        if (self.isBackground) {
    //            [self choosePathAndBeginOperation:background];
    //        } else {
    //            [self choosePathAndBeginOperation:watermark];
    //        }
    //    } else if (sender.tag == 0) {
    //        if (self.queue.operations.count > 0) {
    //            [self.queue cancelAllOperations];
    //        }
    //        [self setInterfaceStatus:KMBatchOperateInterfaceStatus_PrepareProcess];
    //    }
        
        if (self.onlyManagerTemplate) {
            if (sender.tag == 1) {
                var watermark: KMPDFWatermarkData?
                var background: KMBackgroundObject?
                let indexSet = self._isSelectIndex()
                if (!indexSet) {
                    return
                } else {
                    if (!self.isBackground) {
                        if (self.currentType == .txt) {
                            watermark = self._currentTextData
                        } else {
                            watermark = self._currentFileData
                        }
                    } else {
                        if (self.currentBackgroundType == .color) {
                            background = self._currentColorData
                        } else {
                            background = self._currentImageData
                        }
                    }
                }

                let openPanel = NSOpenPanel()
                openPanel.canChooseFiles = false
                openPanel.canChooseDirectories = true
                openPanel.canCreateDirectories = true
                openPanel.beginSheetModal(for: self.view.window!) { result in
                    if (result == .OK) {
                        for fileURL in openPanel.urls {
                            self.hiddenWindowCloseButtonIfNeeded()
    //                        [self.successFilePathURLArray removeAllObjects];
                            if (!self.isBackground) {
                                let file = KMBatchOperateFile(filePath: self.pdfView?.document.documentURL.path ?? "")
                                file.addWatermarkInfo.savePath = fileURL.path
//                                file.addWatermarkInfo.pageChoice = watermark.pageRangeType
                                file.addWatermarkInfo.pageRangeString = watermark?.pagesString ?? ""
//                                KMBatchAddWatermarkOperation *operation = [[[KMBatchAddWatermarkOperation alloc] initWithFile:file waterMark:watermark] autorelease];
//                                operation.delegate = self;
//                                [self.queue addOperation:operation];
                            } else {
                                let file = KMBatchOperateFile(filePath: self.pdfView?.document.documentURL.path ?? "")
                                file.addBackgroundInfo.savePath = fileURL.path
//                                file.addBackgroundInfo.pageChoice = background.pageRangeType
                                file.addBackgroundInfo.pageRangeString = background?.pagesString ?? ""

//                                KMBatchAddBackgroundOperation *operation = [[[KMBatchAddBackgroundOperation alloc] initWithFile:file background:background] autorelease];
//                                operation.delegate = self;
//                                [self.queue addOperation:operation];
                            }
                            if let cnt = self.queue?.operations.count, cnt > 0 {
                                self.interfaceStatus = .Processing
                            }
                        }
                    }
                }
            } else if (sender.tag == 0) {
                if let cnt = self.queue?.operations.count, cnt > 0 {
                    self.queue?.cancelAllOperations()
                }
                self.interfaceStatus = .PrepareProcess
            }
        } else {
            //点击开始
            if (sender.tag == 1) {
                if (!self._checkAndResetTask()) {
                    return;
                }
                var watermark: KMPDFWatermarkData?
                var background: KMBackgroundObject?
                let indexSet = self._isSelectIndex()
                if (!indexSet || self.files!.count < 1) {
                    return;
                } else {
                    if (!self.isBackground) {
                        if (self.currentType == .txt) {
                            watermark = self._currentTextData
                        } else {
                            watermark = self._currentFileData
                        }
                    } else {
                        if (self.currentBackgroundType == .color) {
                            background = self._currentColorData
                        } else {
                            background = self._currentImageData
                        }
                    }
                }
                
                if (self.isBackground) {
                    self._choosePathAndBeginOperation(background)
                } else {
                    self._choosePathAndBeginOperation(watermark)
                }
            } else if (sender.tag == 0) {
                if let cnt = self.queue?.operations.count, cnt > 0 {
                    self.queue?.cancelAllOperations()
                }
                self.interfaceStatus = .PrepareProcess
            }
        }
    }
    
    
    /*






     //添加水印模版
     - (IBAction)buttonClicked_addtemplate:(id)sender {
         NSWindowController *windowController = self.view.window.windowController;
         NSString *filePath = nil;
         NSString *password = nil;
     //    if ([self.view.window.windowController isKindOfClass:[SKMainWindowController class]]) {
     //        filePath = [[(SKMainWindowController *)windowController pdfView].document.documentURL path];
     //        SKPDFDocument *document =  (SKPDFDocument *)[(SKMainWindowController *)windowController pdfView].document;
     //        password = document.password;
     //    }
         
         if (!self.isBackground) {
     //        KMWatermarkManagerWindowController *watermarWindowController = [[[KMWatermarkManagerWindowController alloc] initWithBaseFile:filePath watermark:nil password:password type:KMWatermarkManagerType_Add fileType:self.currentType] autorelease];
     //        __block typeof(self) blockSelf = self;
     //        watermarWindowController.operateCallBack = ^(KMPDFWatermarkData *watermark, NSInteger currentType) {
     //            blockSelf.currentType = currentType;
     //
     //            [blockSelf loadData];
     ////            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     ////                if ([self checkAndResetTask]) {
     ////                    [self choosePathAndBeginOperation:watermark];
     ////                }
     ////            });
     //
     //            BOOL haveWaters = NO;
     //            if (blockSelf.currentType == KMWatermarkType_Txt) {
     //                blockSelf.currentTextData = watermark;;
     //                if (blockSelf.textTemplateArray.count > 0) {
     //                    haveWaters = YES;
     //                }
     //            } else if (blockSelf.currentType == KMWatermarkType_File) {
     //                blockSelf.currentFileData = watermark;;
     //                if (blockSelf.fileTemplateArray.count > 0) {
     //                    haveWaters = YES;
     //                }
     //            }
     //            if (haveWaters) {
     //                NSIndexPath *indexpath = [NSIndexPath indexPathForItem:0 inSection:0];
     //                NSMutableSet *set = [NSMutableSet set];
     //                [set addObject:indexpath];
     //                [blockSelf.collectionView selectItemsAtIndexPaths:set scrollPosition:NSCollectionViewScrollPositionBottom];
     //            }
     //
     //            [blockSelf postNotification];
     //        };
     //        [watermarWindowController beginSheetModalForWindow:[NSApp keyWindow] completionHandler:nil];
         } else {
     //        KMBackgroundManagerWindowController *backgroundWindowController = [[[KMBackgroundManagerWindowController alloc] initWithBaseFile:filePath background:nil password:password type:KMBackgroundManagerType_Add fileType:self.currentBackgroundType] autorelease];
     //        __block typeof(self) blockSelf = self;
     //        backgroundWindowController.operateCallBack = ^(KMBackgroundObject *background, NSInteger currentType) {
     //            blockSelf.currentBackgroundType = currentType;
     //
     //            [blockSelf loadData];
     ////            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     ////                if ([self checkAndResetTask]) {
     ////                    [self choosePathAndBeginOperation:background];
     ////                }
     ////            });
     //
     //            BOOL haveBackgrounds = NO;
     //            if (blockSelf.currentBackgroundType == KMBackgroundType_Color) {
     //                blockSelf.currentColorData = background;
     //                if (blockSelf.textTemplateArray.count > 0) {
     //                    haveBackgrounds = YES;
     //                }
     //            } else if (blockSelf.currentBackgroundType == KMBackgroundType_File) {
     //                blockSelf.currentImageData = background;
     //                if (blockSelf.fileTemplateArray.count > 0) {
     //                    haveBackgrounds = YES;
     //                }
     //            }
     //            if (haveBackgrounds) {
     //                NSIndexPath *indexpath = [NSIndexPath indexPathForItem:0 inSection:0];
     //                NSMutableSet *set = [NSMutableSet set];
     //                [set addObject:indexpath];
     //                [blockSelf.collectionView selectItemsAtIndexPaths:set scrollPosition:NSCollectionViewScrollPositionBottom];
     //            }
     //
     //            [blockSelf postNotification];
     //        };
     //        [backgroundWindowController beginSheetModalForWindow:[NSApp keyWindow] completionHandler:nil];
         }
     }

     - (void)editWatermark:(KMPDFWatermarkData *)waterMark {
         if (!self.isBackground) {
             NSString *filePath = nil;
             NSString *password = nil;
             
             NSWindowController *windowController = self.view.window.windowController;
     //        if ([self.view.window.windowController isKindOfClass:[SKMainWindowController class]]) {
     //            filePath = [[(SKMainWindowController *)windowController pdfView].document.documentURL path];
     //            SKPDFDocument *document =  (SKPDFDocument *)[(SKMainWindowController *)windowController pdfView].document;
     //            password = document.password;
     //        }
             
     //        KMWatermarkManagerWindowController *watermarWindowController = [[[KMWatermarkManagerWindowController alloc] initWithBaseFile:filePath watermark:waterMark password:password type:KMWatermarkManagerType_Edit fileType:self.currentType] autorelease];
     //        __block typeof(self) blockSelf = self;
     //        watermarWindowController.operateCallBack = ^(KMPDFWatermarkData *watermark, NSInteger currentType) {
     //            blockSelf.currentType = currentType;
     //            if (currentType == 0) {
     //                blockSelf.currentTextData = watermark;
     //            } else {
     //                blockSelf.currentFileData = watermark;
     //            }
     //            [blockSelf loadData];
     //
     //            [blockSelf postNotification];
     //        };
     //        [watermarWindowController beginSheetModalForWindow:[NSApp keyWindow] completionHandler:nil];
         } else {
             
         }
     }

     - (void)editBackground:(KMBackgroundObject *)background {
         NSWindowController *windowController = self.view.window.windowController;
         NSString *filePath = nil;
         NSString *password = nil;
     //    if ([self.view.window.windowController isKindOfClass:[SKMainWindowController class]]) {
     //        filePath = [[(SKMainWindowController *)windowController pdfView].document.documentURL path];
     //        SKPDFDocument *document =  (SKPDFDocument *)[(SKMainWindowController *)windowController pdfView].document;
     //        password = document.password;
     //    }
     //
     //    KMBackgroundManagerWindowController *backgroundWindowController = [[[KMBackgroundManagerWindowController alloc] initWithBaseFile:filePath background:background password:password type:KMBackgroundManagerType_Edit fileType:self.currentBackgroundType] autorelease];
     //    __block typeof(self) blockSelf = self;
     //    backgroundWindowController.operateCallBack = ^(KMBackgroundObject *background, NSInteger currentType) {
     //        blockSelf.currentBackgroundType = currentType;
     //        if (currentType == 0) {
     //            blockSelf.currentColorData = background;
     //        } else {
     //            blockSelf.currentImageData = background;
     //        }
     //        [blockSelf loadData];
     //
     //        [blockSelf postNotification];
     //    };
     //    [backgroundWindowController beginSheetModalForWindow:[NSApp keyWindow] completionHandler:nil];
     }

     - (void)deleteBackground:(KMBackgroundObject *)background {
     //    [[KMBackgroundManager defaultManager] removeBackground:background];
         [self loadData];

         [self postNotification];
     }

     */
    
}

// MARK: - Private Methods

extension KMBatchOperateAddWatermarkViewController {
    private func _localizedlanguage() {
        self.addButton.title = KMLocalizedString("Add Template", nil)
        self.fileButton.title = KMLocalizedString("File", nil)
        self.actionButton.title = KMLocalizedString("Apply", nil)
        if (!self.isBackground) {
            self.titleLabel.stringValue = KMLocalizedString("Watermark", nil)
            self.textButton.title = KMLocalizedString("Text", nil)
    //        self.actionButton.title = NSLocalizedString(@"Add Watermark", nil);
        } else {
            self.titleLabel.stringValue = KMLocalizedString("Background", nil)
            self.textButton.title = KMLocalizedString("Color", nil)
    //        self.actionButton.title = NSLocalizedString(@"Add Background", nil);
        }
    //    if (self.onlyManagerTemplate) {
    //        self.actionButton.title = NSLocalizedString(@"Add Template", nil);
    //    }

        if (self.onlyManagerTemplate) {
    //        self.titleLabel.hidden = self.addButton.hidden = YES;
    //        self.managerTemplateTitleLabel.hidden = NO;
    //        self.addButtonHeightConstraint.constant = 0;
    //        self.addButtonBottomConstraint.constant = 0;
            
            self.titleLabel.isHidden = false
            self.addButton.isHidden = false
            self.managerTemplateTitleLabel.isHidden = true
        } else {
            self.titleLabel.isHidden = false
            self.addButton.isHidden = false
            self.managerTemplateTitleLabel.isHidden = true
        }
        
        self.managerTemplateTitleLabel.stringValue = KMLocalizedString("Manage Templates", nil)
    }
    
    private func _configuiUI() {
        self.topBaseView.wantsLayer = true
        self.topBaseView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
        
        self.collectionView.wantsLayer = true
        self.collectionView.isSelectable = true
        self.collectionView.allowsMultipleSelection = false
        self.collectionView.allowsEmptySelection = false
        self.collectionView.enclosingScrollView?.borderType = .noBorder
        self.collectionView.enclosingScrollView?.drawsBackground = false
        
        let v = NSView(frame: CGRectMake(0, 0, 100, 100))
        v.wantsLayer = true
        v.layer?.backgroundColor = .clear
        
        self.collectionView.backgroundView = v;
        self.collectionView.enclosingScrollView?.horizontalScrollElasticity = .none
        self.collectionView.enclosingScrollView?.verticalScrollElasticity = .none
        
        self.titleLabel.font = .boldSystemFont(ofSize: 14)
        self.titleLabel.textColor = KMAppearance.Layout.h0Color()
        
        self.actionButton.font = .systemFont(ofSize: 13)
        self.fileButton.font = .systemFont(ofSize: 13)
        self.textButton.font = .systemFont(ofSize: 13)
        
        self.actionButton.wantsLayer = true
        self.addButton.wantsLayer = true
        if (self.onlyManagerTemplate) {
    //        [self.actionButton setImage:[NSImage imageNamed:KMImageNameUXIconBtnAddWhite]];
    //        self.actionButton.imagePosition = NSImageLeft;
    //        [self.actionButton setTitleColor:[KMAppearance KMColor_Layout_W0]];
            
            self.topHeightConstraint.constant = 0
            self.addButton.imagePosition = .imageLeft
            self.addButton.image = NSImage(named: "KMImageNameHeaderFooterAddBtn")
    //        self.addButton.layer.backgroundColor = [KMAppearance KMColor_Interactive_S0].CGColor;
            self.addButton.setTitleColor(KMAppearance.Layout.h0Color())
            
            self.actionButton.layer?.backgroundColor = KMAppearance.Interactive.m0Color().cgColor
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
            self.actionButton.imagePosition = .noImage
        } else {
            self.topHeightConstraint.constant = 0
            self.addButton.imagePosition = .imageLeft
            self.addButton.image = NSImage(named: "KMImageNameHeaderFooterAddBtn")
    //        self.addButton.layer.backgroundColor = [KMAppearance KMColor_Interactive_S0].CGColor;
            self.addButton.setTitleColor(KMAppearance.Layout.h0Color())
            
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color().withAlphaComponent(0.6))
            self.actionButton.layer?.backgroundColor = KMAppearance.Interactive.m0Color().withAlphaComponent(0.6).cgColor
            self.actionButton.imagePosition = .noImage
        }
        
        if (!self.onlyManagerTemplate) {
            if let cnt = self.files?.count, cnt > 0 {
                self._haveFiles = true
            } else {
                self._haveFiles = false
            }
            self._updateActionButtonbackgroundColor()
        }
        
        self.addButton.layer?.cornerRadius = 1.0
        self.actionButton.layer?.cornerRadius = 1.0
        
        self.actionButton.layer?.cornerRadius = 1.0
        
        //    self.bottomBaseView.wantsLayer = YES;
        //    self.bottomBaseView.layer.backgroundColor =  [KMAppearance KMColor_Layout_L0].CGColor;
            
            self.textButton.wantsLayer = true
            self.fileButton.wantsLayer = true
        //    self.textButton.layer.backgroundColor = [KMAppearance KMColor_Interactive_A0].CGColor;
        //    self.fileButton.layer.backgroundColor = [KMAppearance KMColor_Layout_L_1].CGColor;
        self.textBox.fillColor = KMAppearance.Interactive.a0Color()
        self.fileBox.fillColor = KMAppearance.Layout.l_1Color()
            
        self.textButton.setTitleColor(KMAppearance.Layout.w0Color())
        self.fileButton.setTitleColor(KMAppearance.Layout.h0Color())
        self.managerTemplateTitleLabel.font = .systemFont(ofSize: 14)
        self.managerTemplateTitleLabel.textColor = KMAppearance.Layout.h0Color()
            
        self.view.addSubview(self.blankView)
        self.blankView.mas_makeConstraints { make in
            make?.top.equalTo()(self.topBaseView.mas_bottom)
            make?.left.right().equalTo()(self.view)
            make?.bottom.equalTo()(self.bottomBaseView.mas_top)
            make?.height.greaterThanOrEqualTo()(200)
        }
            self.blankView.titleLabel.stringValue = KMLocalizedString("No Templates", nil)
            
            if (self.isBackground) {
                self.blankView.imageView.image = NSImage(named: KMImageNameEmptyBackground)
            }
            self.blankView.wantsLayer = true
        //    self.blankView.layer.backgroundColor = [KMAppearance KMColor_Layout_L0].CGColor;
            
//            NSMenu * = [[NSMenu alloc]initWithTitle:@""];
        let menu = NSMenu()
            if(!self.isBackground) {
                    if(!self.isBatchOperation) {
                        _ = menu.addItem(title: KMLocalizedString("Batch Add Watermarks", nil), action: #selector(_buttonItemClick_addBatch), target: self)
                    }
                _ = menu.addItem(title: KMLocalizedString("Remove All Watermark Templates", nil), action: #selector(_buttonItemClick_CleanAll), target: self)
            } else {
                if(!self.isBatchOperation) {
                    _ = menu.addItem(title: KMLocalizedString("Batch Add Background", nil), action: #selector(_buttonItemClick_addBatch), target: self)
                }
                _ = menu.addItem(title: KMLocalizedString("Remove All Background Templates", nil), action: #selector(_buttonItemClick_CleanAll), target: self)
            }
            self.view.menu = menu;
    }
    
    private func _loadData() {
        self._textTemplateArray = []
        self._fileTemplateArray = []
        if (!self.isBackground) {
    //        NSArray *watermarkArr = [KMWatermarkManager defaultManager].watermarks;
    //        for (NSUInteger i = 0 ; i < watermarkArr.count; i++) {
    //            KMPDFWatermarkData *watermark = [watermarkArr objectAtIndex:i];
    //            if (watermark.image) {
    //                [self.fileTemplateArray addObject:watermark];
    //            } else {
    //                [self.textTemplateArray addObject:watermark];
    //            }
    //        }
        } else {
    //        for (NSUInteger i = 0; i < [KMBackgroundManager defaultManager].datas.count; i++) {
    //            KMBackgroundObject *obj = [[KMBackgroundManager defaultManager].datas objectAtIndex:i];
    //            if (obj.type == KMBackgroundTypeColor) {
    //                [self.textTemplateArray addObject:obj];
    //            } else {
    //                [self.fileTemplateArray addObject:obj];
    //            }
    //        }
        }
        self.collectionView.reloadData()
        self._updateActionButtonbackgroundColor()
        NotificationCenter.default.addObserver(self, selector: #selector(_batchFilesCountNotification), name: NSNotification.Name("KMBatchFilesCountNotification"), object: nil)
    }
    
    private func _isSelectIndex() -> Bool {
        var indexSet = false
        if (!self.isBackground) {
            if(self.currentType == .txt) {
                if let data = self._currentTextData {
                    indexSet = (self._textTemplateArray ?? []).contains(data)
                }
            }else {
                if let data = self._currentFileData {
                    indexSet = (self._fileTemplateArray ?? []).contains(data)
                }
            }
        } else {
            if(self.currentBackgroundType == .color) {
                if let data = self._currentColorData {
                    indexSet = (self._textTemplateArray ?? []).contains(data)
                }
            }else {
                if let data = self._currentImageData {
                    indexSet = (self._fileTemplateArray ?? []).contains(data)
                }
            }
        }
        return indexSet;
    }
    
    private func _updateActionButtonbackgroundColor() {
        let indexSet = self._isSelectIndex()
        if let cnt = self.files?.count, cnt > 0 {
            if self.pdfView != nil && indexSet {
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
                self.actionButton.layer?.backgroundColor = KMAppearance.Interactive.m0Color().cgColor
            }
        } else {
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color().withAlphaComponent(0.6))
            self.actionButton.layer?.backgroundColor = KMAppearance.Interactive.m0Color().withAlphaComponent(0.6).cgColor
        }
    }
    
    @objc private func _buttonItemClick_addBatch(_ sender: Any?) {
        let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
        baseWindowController.window?.makeKeyAndOrderFront(nil)
//        NSMutableArray *arr = [NSMutableArray array];
        
//        KMBatchOperateFile *file = [[KMBatchOperateFile alloc] initWithFilePath:self.pdfView.document.documentURL.path type:self.isBackground ? KMBatchOperationTypeAddBackground : KMBatchOperationTypeAddWatermark];
//        [arr addObject:file];
    //    [baseWindowController checkNeedPasswordSwitchToOperateType:self.isBackground ? KMBatchOperationTypeAddBackground : KMBatchOperationTypeAddWatermark files:arr];
    }
    
    @objc private func _buttonItemClick_CleanAll(_ sender: Any?) {
        let alert = NSAlert()
        alert.alertStyle = .warning
        alert.messageText = ""
        alert.informativeText = KMLocalizedString("Are you sure to delete all templates?", nil)
        alert.addButton(withTitle: KMLocalizedString("Delete", nil))
        alert.addButton(withTitle: KMLocalizedString("Cancel", nil))
        alert.beginSheetModal(for: NSApp.mainWindow!) { returnCode in
            if returnCode == .alertFirstButtonReturn {
                self._deleteAllWatermark()
            }
        }
    }
    
    private func _deleteAllWatermark() {
        if(!self.isBackground) {
            for waterMark in self._textTemplateArray ?? [] {
//                [[KMWatermarkManager defaultManager] removeWatermarkWithData:waterMark];
            }
            for waterMark in self._fileTemplateArray ?? [] {
//                [[KMWatermarkManager defaultManager] removeWatermarkWithData:waterMark];
            }
        } else {
            for background in self._textTemplateArray ?? [] {
//                [[KMBackgroundManager defaultManager] removeBackground:background];
            }

            for background in self._fileTemplateArray ?? [] {
//                [[KMBackgroundManager defaultManager] removeBackground:background];
            }
        }
        
        self._loadData()
        self._postNotification()
    }
    
    private func _deleteWatermark(_ waterMark: KMPDFWatermarkData) {
        //    [[KMWatermarkManager defaultManager] removeWatermarkWithData:waterMark];
        self._loadData()
        self._postNotification()
    }
    
    private func _postNotification() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMBatchOperateWatermarksNotification"), object: self)
    }
    
    @objc private func _watermarksNotification(_ notification: NSNotification) {
        let addWatermark = notification.object as? KMBatchOperateAddWatermarkViewController
        if self.isEqual(to: addWatermark) == false {
            self._loadData()
            
            var haveWaters = false
            if (self.currentType == .txt) {
                if let cnt = self._textTemplateArray?.count, cnt > 0 {
                    haveWaters = true
                }
            } else if (self.currentType == .file) {
                if let cnt = self._fileTemplateArray?.count, cnt > 0 {
                    haveWaters = true
                }
            }
            if (haveWaters) {
                let indexpath = IndexPath(item: 0, section: 0)
                var set = Set<IndexPath>()
                set.insert(indexpath)
                self.collectionView.selectItems(at: set, scrollPosition: .bottom)
            }
        }
    }
    
    //检查是否有任务文件要加载,如果有,重置任务。如果返回YES,表示有任务并且任务已经重置,否则表示没有任务,需要中断操作
    private func _checkAndResetTask() -> Bool {
        if let cnt = self.files?.count, cnt < 1 {
            return false
        }
        for i in 0 ..< self.files!.count {
            let file = self.files![i]
            if (self.isBackground) {
//                [file.addBackgroundInfo resetState];
            } else {
//                [file.addWatermarkInfo resetState];
            }
        }
        return true
    }
    
    private func _choosePathAndBeginOperation(_ obj: Any?) {
        let openPanel = NSOpenPanel()
        openPanel.canChooseFiles = false
        openPanel.canChooseDirectories = true
        openPanel.canCreateDirectories = true
        openPanel.beginSheetModal(for: self.view.window!) { result in
            if (result == .OK) {
                for fileURL in openPanel.urls {
                    self.choosePath = fileURL.path
                    if (!self.isBackground) {
                        self._beginAddWatermark(obj as! KMPDFWatermarkData)
                    } else {
                        self._beginAddBackground(obj as! KMBackgroundObject)
                    }
                }
            }
        }
    }
    
    private func _beginAddWatermark(_ watermark: KMPDFWatermarkData) {
        self.hiddenWindowCloseButtonIfNeeded()
    //    [self.successFilePathURLArray removeAllObjects];
        for i in 0 ..< self.files!.count {
            let file = self.files![i]
            file.addWatermarkInfo.savePath = self.choosePath
    //        KMBatchAddWatermarkOperation *operation = [[[KMBatchAddWatermarkOperation alloc] initWithFile:file waterMark:watermark] autorelease];
    //        operation.delegate = self;
    //        [self.queue addOperation:operation];
        }
        if let cnt = self.queue?.operations.count, cnt > 0 {
            self.interfaceStatus = .Processing
        }
    }
    
    private func _beginAddBackground(_ background: KMBackgroundObject) {
        self.hiddenWindowCloseButtonIfNeeded()
    //    [self.successFilePathURLArray removeAllObjects];
        for i in 0 ..< self.files!.count {
            let file = self.files![i]
            file.addBackgroundInfo.savePath = self.choosePath
    //        KMBatchAddBackgroundOperation *operation = [[[KMBatchAddBackgroundOperation alloc] initWithFile:file background:background] autorelease];
    //        operation.delegate = self;
    //        [self.queue addOperation:operation];
        }
        if let cnt = self.queue?.operations.count, cnt > 0 {
            self.interfaceStatus = .Processing
        }
    }
    
    @objc private func _batchFilesCountNotification(_ notification: NSNotification) {
        if (!self.onlyManagerTemplate) {
            let files = notification.object as? [AnyObject] ?? []
            
            if (files.count > 0) {
                self._haveFiles = true
            } else {
                self._haveFiles = false
            }
            self._updateActionButtonbackgroundColor()
        }
    }
}

extension KMBatchOperateAddWatermarkViewController: NSMenuItemValidation {
    func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
        let action  = menuItem.action
        if (action == #selector(_buttonItemClick_CleanAll)) {
            if (self._textTemplateArray!.count == 0 && self._fileTemplateArray!.count == 0) {
                return false
            }
            return true
        }
        return true
    }
}

extension KMBatchOperateAddWatermarkViewController: NSCollectionViewDelegate, NSCollectionViewDataSource, NSCollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        var count = 0
        if (!self.isBackground) {
            if (self.currentType == .txt) {
                count = self._textTemplateArray?.count ?? 0
            } else {
                count = self._fileTemplateArray?.count ?? 0
            }
        } else {
            if (self.currentBackgroundType == .color) {
                count =  self._textTemplateArray?.count ?? 0
            } else {
                count =  self._fileTemplateArray?.count ?? 0
            }
        }
        
        self.blankView.isHidden = count != 0

        return count
    }
    
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMWatermarkCollectionViewItem"), for: indexPath)
        if (!self.isBackground) {
            var waterMark: KMPDFWatermarkData?
            if (self.currentType == .txt) {
                waterMark = self._textTemplateArray![indexPath.item] as! KMPDFWatermarkData
                if(self._currentTextData == waterMark) {
                    item.isSelected = true
                }else {
                    item.isSelected = false
                }
            } else {
                waterMark = self._fileTemplateArray![indexPath.item] as! KMPDFWatermarkData
                if(self._currentFileData == waterMark) {
                    item.isSelected = true
                }else{
                    item.isSelected = false
                }
            }
            //            __block typeof(self) blockSelf = self;
            let _item = item as? KMWatermarkCollectionViewItem
            _item?.updateInterface(waterMark!)
            _item?.waterMarkOprateCallback = { [unowned self] type, wm in
                if (wm != nil) {
                    if (type == .Edit) {
                        if (self.currentType == .txt) {
                            self._currentTextData = waterMark
                        } else {
                            self._currentFileData = waterMark
                        }
                        collectionView.reloadData()
                        //                        [blockSelf editWatermark:watermark];
                    } else {
                        //                        [blockSelf deleteWatermark:watermark];
                    }
                }
            };
        } else {
            var background: KMBackgroundObject?
            if (self.currentBackgroundType == .color) {
                background = self._textTemplateArray![indexPath.item] as! KMBackgroundObject
                if(self._currentColorData == background) {
                    item.isSelected = true
                }else {
                    item.isSelected = false
                }
            } else {
                background = self._fileTemplateArray![indexPath.item] as! KMBackgroundObject
                if(self._currentImageData == background) {
                    item.isSelected = true
                }else {
                    item.isSelected = false
                }
            }
            
            let _item = item as? KMWatermarkCollectionViewItem
            _item?.updateBackgroundInterface(background!)
            //            __block typeof(self) blockSelf = self;
            _item?.backgroundOperateCallback = { [unowned self] type, bg in
                if (type == .Edit) {
                    if (self.currentBackgroundType == .color) {
                        self._currentColorData = background
                    } else {
                        self._currentImageData = background
                    }
                    collectionView.reloadData()
                    //                    [blockSelf editBackground:background];
                } else {
                    //                    [blockSelf deleteBackground:background];
                }
            } ;
        }
        self._updateActionButtonbackgroundColor()
        
        return item
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
        if (collectionView.frame.size.width < 240) {
            return CGSizeMake(0, 0)
        } else {
            return CGSizeMake(104, 167)
        }
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets {
        if (collectionView.frame.size.width < 32) {
            return NSEdgeInsetsMake(0, 0, 0, 0)
        }
        return NSEdgeInsetsMake(0, 16, 0, 16)
    }
    
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        let indexPath = indexPaths.first
        guard let _indexPath = indexPath else {
            return
        }
        if (indexPath!.item < 0) {
            return
        }
        if (self.isBackground) {
            var background: KMBackgroundObject?
            if (self.currentBackgroundType == .color) {
                background = self._textTemplateArray![_indexPath.item] as? KMBackgroundObject
                self._currentColorData = background
            } else {
                background = self._fileTemplateArray![_indexPath.item] as? KMBackgroundObject
                self._currentImageData = background
            }
            for i in 0 ..< self.files!.count {
                let file = self.files![i]
//                file.addBackgroundInfo.pageChoice = background.pageRangeType;
//                if (file.addBackgroundInfo.pageChoice == KMBatchOperatePageChoice_Input) {
//                    NSArray *arr = [self allPageNumbers:background.pagesString];
//                    NSArray *sortedArray = [file pagesArrayIntersectWithArray:arr];
//                    if (sortedArray.count < 1) {
//                        file.addBackgroundInfo.pageChoice = KMBatchOperatePageChoice_All;
//                    } else {
//                        file.addBackgroundInfo.pageRangeString = [sortedArray componentsJoinedByString:@","];
//                    }
//                }
            }
      
        } else {
            var waterMark: KMPDFWatermarkData?
            if (self.currentType == .txt) {
                waterMark = self._textTemplateArray![_indexPath.item] as? KMPDFWatermarkData
                self._currentTextData = waterMark
            } else {
                waterMark = self._fileTemplateArray![_indexPath.item] as? KMPDFWatermarkData
                self._currentFileData = waterMark
            }
            
            for i in 0 ..< self.files!.count {
                let file = self.files![i]
//                file.addWatermarkInfo.pageChoice = waterMark.pageRangeType;
//                if (file.addWatermarkInfo.pageChoice == KMBatchOperatePageChoice_Input) {
//                    NSArray *arr = [self allPageNumbers:waterMark.pagesString];
//                    NSArray *sortedArray = [file pagesArrayIntersectWithArray:arr];
//                    if (sortedArray.count < 1) {
//                        file.addWatermarkInfo.pageChoice = KMBatchOperatePageChoice_All;
//                    } else {
//                        file.addWatermarkInfo.pageRangeString = [sortedArray componentsJoinedByString:@","];
//                    }
//                }
            }
        }
        NotificationCenter.default.post(name: NSNotification.Name("kNeedChangePageRangeNotification"), object: nil)
        collectionView.reloadData()
        self._updateActionButtonbackgroundColor()
    }
}