//
//  KMAccountInfoWindowController.swift
//  PDF Master
//
//  Created by lizhe on 2023/2/24.
//

import Cocoa

var accountInfoController: KMAccountInfoWindowController?
var accountInfoMainWindow: NSWindow?
typealias KMAccountInfoWindowControllerCancellationAction = (_ controller: KMAccountInfoWindowController) -> Void
class KMAccountInfoWindowController: NSWindowController {

    @IBOutlet weak var accountInfoView: KMAccountInfoView!
    
    var inputType: DataNavigationViewButtonActionType?
    var cancellAtionAction: KMAccountInfoWindowControllerCancellationAction?
    
    deinit {
        print("KMAccountInfoWindowController 释放")
    }
    
    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
        self.setup()
        self.reloadData()
    }
    
    //MARK: 打开文件
    static func show(window: NSWindow, _ type: DataNavigationViewButtonActionType = .Batch, _ logType: KMRegisterLogType = .login) -> KMAccountInfoWindowController {
        if KMAccountInfoWindowController.isSampleController() {
            let controller: KMAccountInfoWindowController = KMAccountInfoWindowController.fetchSampleController()
            controller.inputType = type
            window.beginSheet(controller.window!)
            return controller
        } else {
            let controller: KMAccountInfoWindowController = KMAccountInfoWindowController.init(windowNibName: "KMAccountInfoWindowController")
            controller.inputType = type
            controller.cancellAtionAction = { controller in
                KMVerficationCodeWindowController.show(window: controller.window!)
            }
            window.beginSheet(controller.window!)
            accountInfoController = controller
            accountInfoMainWindow = window
            return controller
        }
    }
    
    static func isSampleController() -> Bool {
        for window in NSApp.windows {
            let controller = window.windowController
            if controller is KMAccountInfoWindowController {
                return true
            }
        }
        return false
    }
    
    static func fetchSampleController() -> KMAccountInfoWindowController {
        for window in NSApp.windows {
            let controller = window.windowController
            if controller is KMAccountInfoWindowController {
                return controller as! KMAccountInfoWindowController
            }
        }
        
        return NSWindowController() as! KMAccountInfoWindowController
    }
    
    func setup() {
        self.window?.contentView?.backgroundColor(NSColor(hex: "#FFFFFF"))
        
        self.accountInfoView.closeAction = { view in
            print("关闭")
            accountInfoMainWindow?.endSheet(view.window!)
            view.window?.close()
            accountInfoController = nil
            accountInfoMainWindow = nil
        }
        
        self.accountInfoView.logOutAction = { view in
            print("登出")
            KMLightMemberManager.manager.logOut()
            accountInfoMainWindow?.endSheet(view.window!)
            view.window?.close()
            KMRequestServerManager.manager.logout { success, result in
                if success {
                    accountInfoController = nil
                    accountInfoMainWindow = nil
                }
            }
        }
        
        self.accountInfoView.cancellationAction = { view in
            print("注销")
            
            let alert = NSAlert()
            alert.messageText = NSLocalizedString("Are you sure you want to cancel?", comment: "")
            alert.informativeText = NSLocalizedString("Cancellation cannot be withdrawn, it will be completed within 3 working days, until then your account will be frozen and cannot be logged in, are you sure you want to delete your account?", comment: "")
            alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
            alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
            alert.beginSheetModal(for: view.window!) { [unowned self] result in
                if (result == .alertFirstButtonReturn) { /// 取消
                    return
                } else if result == .alertSecondButtonReturn {
                    guard let callBack = cancellAtionAction else { return }
//                    accountInfoMainWindow?.endSheet(view.window!)
//                    view.window?.close()
//                    accountInfoController = nil
//                    accountInfoMainWindow = nil
                    callBack(self)
                }
                
            }
        }
    }
    
    func reloadData() {
        KMRequestServerManager.manager.getUserInfo { [unowned self] success, data, error, isLocal in
            if success {
                self.accountInfoView.userInfo = data
                KMLightMemberManager.manager.reloadUserInfo()
            } else {
                if error?.code == 304 {
                    accountInfoMainWindow?.endSheet(self.window!)
                    self.window?.close()
                    KMLightMemberManager.manager.logOut()
                    accountInfoController = nil
                    accountInfoMainWindow = nil
                }
            }
        }
    }
}