//
//  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: KMWatermarkModel?
    private var _currentFileData: KMWatermarkModel?
    
    private var _currentColorData: KMBackgroundModel?
    private var _currentImageData: KMBackgroundModel?
     
    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: KMWatermarkModel) {
        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: KMBackgroundModel) {
        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 buttonClicked_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) {
            if (sender.tag == 1) {
                var watermark: KMWatermarkModel?
                var background: KMBackgroundModel?
                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?.removeAll()
                            if (!self.isBackground) {
                                let file = KMBatchOperateFile(filePath: self.pdfView?.document.documentURL.path ?? "", type: .AddWatermark)
                                file.addWatermarkInfo.savePath = fileURL.path
                                file.addWatermarkInfo.pageChoice = KMBatchOperatePageChoice(rawValue: watermark?.pageRangeType.rawValue ?? 0) ?? .All
                                file.addWatermarkInfo.pageRangeString = watermark?.pagesString ?? ""
                                let op = KMBatchAddWatermarkOperation(file: file, waterMarkM: watermark!)
                                op.delegate = self
                                self.queue?.addOperation(op)
                            } else {
                                let file = KMBatchOperateFile(filePath: self.pdfView?.document.documentURL.path ?? "", type: .AddBackground)
                                file.addBackgroundInfo.savePath = fileURL.path
                                file.addWatermarkInfo.pageChoice = KMBatchOperatePageChoice(rawValue: watermark?.pageRangeType.rawValue ?? 0) ?? .All
                                file.addBackgroundInfo.pageRangeString = background?.pagesString ?? ""
                                let op = KMBatchAddBackgroundOperation(file: file, backgroundM: background!)
                                op.delegate = self
                                self.queue?.addOperation(op)
                            }
                            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: KMWatermarkModel?
                var background: KMBackgroundModel?
                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 func buttonClicked_addtemplate(_ sender: NSButton) {
        let filePath: String = Bundle.main.path(forResource: "PDF Master User Guide", ofType: "pdf") ?? ""
        var cdocument = self.pdfView?.document
        if isBatchOperation {
            cdocument = CPDFDocument(url: URL(fileURLWithPath: filePath))
        }
        if isBackground {
            let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
            controller.isBatch = isBatchOperation
            controller.type = .add
            controller.currentType = self.currentBackgroundType.rawValue
            controller.pdfDocument = cdocument
            controller.cancelAction = { [unowned self] controller in
                self.km_endSheet()
            }
            self.km_beginSheet(windowC: controller)
            controller.operateCallBack = { controller, background, countType in
                self.currentBackgroundType = KMBackgroundType(rawValue: countType) ?? .color
                self._loadData()
                var haveBackgrounds = false
                if self.currentBackgroundType == .color {
                    self._currentColorData = background
                    if self._textTemplateArray?.count ?? 0 > 0 {
                        haveBackgrounds = true
                    }
                } else if self.currentBackgroundType == .file {
                    self._currentImageData = background
                    if self._fileTemplateArray?.count ?? 0 > 0 {
                        haveBackgrounds = true
                    }
                }
                if haveBackgrounds {
                    let indexPath = IndexPath(item: 0, section: 0)
                    var set = Set<IndexPath>()
                    set.insert(indexPath)
                    self.collectionView.selectItems(at: set, scrollPosition: .bottom)
                }
                self._postNotification()
            }
        }else{
            let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
            controller.isBatch = isBatchOperation
            controller.type = .add
            controller.pdfDocument = cdocument
            controller.currentType = self.currentType.rawValue
            controller.cancelAction = { [unowned self] wmWindowC in
                self.km_endSheet()
            }
            controller.operateCallBack = { [unowned self] controller, watermark, countType in
                self.currentType = KMWatermarkType(rawValue: countType) ?? .txt
                self._loadData()
                var haveWaters = false
                if self.currentType == .txt {
                    self._currentTextData = watermark
                    if self._textTemplateArray?.count ?? 0 > 0 {
                        haveWaters = true
                    }
                } else if self.currentType == .file {
                    self._currentFileData = watermark
                    if self._fileTemplateArray?.count ?? 0 > 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)
                }
                self._postNotification()
            }
            
            self.km_beginSheet(windowC: controller)
        }
    }
    
}

// MARK: - Private Methods

extension KMBatchOperateAddWatermarkViewController {
    private func _localizedlanguage() {
        self.addButton.title = KMLocalizedString("  Add Template", nil)
        self.addButton.imageHugsTitle = true
        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 = true
            self.addButton.isHidden = false
            self.managerTemplateTitleLabel.isHidden = false
        } 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
      
        self.collectionView.register(KMWatermarkCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMWatermarkCollectionViewItem"))
        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 = 40
            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) {
            let watermarkArr = KMWatermarkManager.defaultManager.watermarks
            for i in 0 ..< watermarkArr.count {
                let watermark = watermarkArr[i]
                if ((watermark.image) != nil) {
                    self._fileTemplateArray?.append(watermark)
                } else {
                    self._textTemplateArray?.append(watermark)
                }
            }
        } else {
            let arr = KMBackgroundManager.defaultManager.datas
            for i in 0 ..< arr.count {
                let obj = arr[i]
                if (obj.type == .color) {
                    self._textTemplateArray?.append(obj)
                } else {
                    self._fileTemplateArray?.append(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 (self.files?.count ?? 0 > 0 || self.pdfView?.document.documentURL.path.count ?? 0 > 0 ) && 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")
       
//        NSMutableArray *arr = [NSMutableArray array];
        
        let file = KMBatchOperateFile(filePath: self.pdfView!.document.documentURL.path, type: self.isBackground ? .AddBackground : .AddWatermark)
        
        baseWindowController.window?.makeKeyAndOrderFront(nil)
        baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: self.isBackground ? .AddBackground : .AddWatermark, files: [file])
    }
    
    @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()
            }
        }
    }
    func editBackground(_ background: KMBackgroundModel) {
        var filePath: String = Bundle.main.path(forResource: "PDF Master User Guide", ofType: "pdf") ?? ""
        if self.pdfView?.document.documentURL.path.count ?? 0 > 0 {
            filePath = self.pdfView?.document.documentURL.path ?? ""
        }
        let cdocument = CPDFDocument(url: URL(fileURLWithPath: filePath))
        
        let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
        controller.isBatch = isBatchOperation
        controller.type = .edit
        controller.background = background
        controller.currentType = self.currentBackgroundType.rawValue
        controller.pdfDocument = cdocument
        controller.cancelAction = { [unowned self] controller in
            self.km_endSheet()
        }
        self.km_beginSheet(windowC: controller)
        controller.operateCallBack = { controller, background, countType in
            self.currentBackgroundType = KMBackgroundType(rawValue: countType) ?? .color
            self._loadData()
            var haveBackgrounds = false
            if self.currentBackgroundType == .color {
                self._currentColorData = background
                if self._textTemplateArray?.count ?? 0 > 0 {
                    haveBackgrounds = true
                }
            } else if self.currentBackgroundType == .file {
                self._currentImageData = background
                if self._fileTemplateArray?.count ?? 0 > 0 {
                    haveBackgrounds = true
                }
            }
            if haveBackgrounds {
                let indexPath = IndexPath(item: 0, section: 0)
                var set = Set<IndexPath>()
                set.insert(indexPath)
                self.collectionView.selectItems(at: set, scrollPosition: .bottom)
            }
            self._postNotification()
        }
    }

    private func deleteBackground(_ background: KMBackgroundModel) {
        let _ = KMBackgroundManager.defaultManager.deleteTemplate(model: background)
        self._loadData()
        self._postNotification()
    }
    
    func editWatermark(_ waterMark: KMWatermarkModel) {
        if !isBackground {
            var filePath: String = Bundle.main.path(forResource: "PDF Master User Guide", ofType: "pdf") ?? ""
            if self.pdfView?.document.documentURL.path.count ?? 0 > 0 {
                filePath = self.pdfView?.document.documentURL.path ?? ""
            }
        
            let cdocument = CPDFDocument(url: URL(fileURLWithPath: filePath))
            let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
            controller.watermark = waterMark
            controller.isBatch = isBatchOperation
            controller.type = .edit
            controller.pdfDocument = cdocument
            controller.currentType = self.currentType.rawValue
            controller.cancelAction = { [unowned self] wmWindowC in
                self.km_endSheet()
            }
            controller.operateCallBack = { controller, watermark, countType in
                self._loadData()
                var haveWaters = false
                if self.currentType == .txt {
                    self._currentTextData = watermark
                    if self._textTemplateArray?.count ?? 0 > 0 {
                        haveWaters = true
                    }
                } else if self.currentType == .file {
                    self._currentFileData = watermark
                    if self._fileTemplateArray?.count ?? 0 > 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)
                }
                self._postNotification()
            }
            self.km_beginSheet(windowC: controller)
        } else {
            // Handle background case
        }
    }
    
    private func _deleteAllWatermark() {
        if(!self.isBackground) {
            for waterMark in self._textTemplateArray ?? [] {
                _ = KMWatermarkManager.defaultManager.removeWatermark(watermark: waterMark as! KMWatermarkModel)
            }
            for waterMark in self._fileTemplateArray ?? [] {
//                [[KMWatermarkManager defaultManager] removeWatermarkWithData:waterMark];
                _ = KMWatermarkManager.defaultManager.removeWatermark(watermark: waterMark as! KMWatermarkModel)
            }
        } else {
            for background in self._textTemplateArray ?? [] {
//                [[KMBackgroundManager defaultManager] removeBackground:background];
                _ = KMBackgroundManager.defaultManager.deleteTemplate(model: background as! KMBackgroundModel)
            }

            for background in self._fileTemplateArray ?? [] {
//                [[KMBackgroundManager defaultManager] removeBackground:background];
                _ = KMBackgroundManager.defaultManager.deleteTemplate(model: background as! KMBackgroundModel)
            }
        }
        
        self._loadData()
        self._postNotification()
    }
    
    private func _deleteWatermark(_ waterMark: KMWatermarkModel) {
        //    [[KMWatermarkManager defaultManager] removeWatermarkWithData:waterMark];
        let _ = KMWatermarkManager.defaultManager.removeWatermark(watermark: 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! KMWatermarkModel)
                    } else {
                        self._beginAddBackground(obj as! KMBackgroundModel)
                    }
                }
            }
        }
    }
    
    private func _beginAddWatermark(_ watermark: KMWatermarkModel) {
        self.hiddenWindowCloseButtonIfNeeded()
        self.successFilePathURLArray?.removeAll()
        for i in 0 ..< self.files!.count {
            let file = self.files![i]
            file.addWatermarkInfo.savePath = self.choosePath
  
            let operation = KMBatchAddWatermarkOperation(file: file, waterMarkM: watermark)
            operation.delegate = self
            self.queue?.addOperation(operation)
        }
        if let cnt = self.queue?.operations.count, cnt > 0 {
            self.interfaceStatus = .Processing
        }
    }
    
    private func _beginAddBackground(_ background: KMBackgroundModel) {
        self.hiddenWindowCloseButtonIfNeeded()
        self.successFilePathURLArray?.removeAll()
        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];
            let operation = KMBatchAddBackgroundOperation(file: file, backgroundM: background)
            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: Array? = notification.object as? [KMBatchOperateFile]
            self.files? = files ?? []
            
            if (files?.count ?? 0 > 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: KMWatermarkModel?
            if (self.currentType == .txt) {
                waterMark = (self._textTemplateArray![indexPath.item] as! KMWatermarkModel)
                if(self._currentTextData == waterMark) {
                    item.isSelected = true
                }else {
                    item.isSelected = false
                }
            } else {
                waterMark = (self._fileTemplateArray![indexPath.item] as! KMWatermarkModel)
                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()
                        self.editWatermark(waterMark!)
                    } else {
                        self._deleteWatermark(waterMark!)
                    }
                }
            };
        } else {
            var background: KMBackgroundModel?
            if (self.currentBackgroundType == .color) {
                background = (self._textTemplateArray![indexPath.item] as! KMBackgroundModel)
                if(self._currentColorData == background) {
                    item.isSelected = true
                }else {
                    item.isSelected = false
                }
            } else {
                background = (self._fileTemplateArray![indexPath.item] as! KMBackgroundModel)
                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()
                    self.editBackground(background!)
                } else {
                    self.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: KMBackgroundModel?
            if (self.currentBackgroundType == .color) {
                background = self._textTemplateArray![_indexPath.item] as? KMBackgroundModel
                self._currentColorData = background
            } else {
                background = self._fileTemplateArray![_indexPath.item] as? KMBackgroundModel
                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: KMWatermarkModel?
            if (self.currentType == .txt) {
                waterMark = self._textTemplateArray![_indexPath.item] as? KMWatermarkModel
                self._currentTextData = waterMark
            } else {
                waterMark = self._fileTemplateArray![_indexPath.item] as? KMWatermarkModel
                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()
    }
}