//
//  KMPurchaseEmbeddedWindowController.swift
//  PDF Reader Pro
//
//  Created by wanjun on 2024/8/29.
//

import Cocoa

#if VERSION_DMG
// paypal alipay wxpay paddle
@objc enum KMPaymentType: UInt32 {
    case paypal = 0
    case paddle
    case wxpay
    case alipay
}

@objc enum KMDMGProductType: UInt32 {
    
    case advanced_annual_subscription_trail = 0                    // 全平台高级版年订阅             99.9 美金,带免费试用
    case advanced_annual_subscription                              // 全平台高级版年订阅             99.9 美金
    case advanced_annual_subscription_blackFive                    // 全平台高级版年订阅             99.9 美金,黑五订单,优惠价格不为空
    
    case standard_annual_subscription                              // 全平台标准版年订阅             79.9 美金
    
    case advanced_permanent                                        // Mac & Win 双平台高级永久      119.99 美金
    case advanced_permanent_blackFive                              // Mac & Win 双平台高级永久      119.99 美金,黑五订单,优惠价格不为空
    
    case ai_subscription_year_trail                                // AI 年订阅                    125.99 美金,带免费试用
    case ai_subscription_month                                     // AI 月订阅                    14.99 美金
}

let kKMNewUserGiftDiscountCodeId                                = "B89EF-166C-4AD"
let kKMAdvancedYearSubscribeDiscountCodeId                      = "B89EF-166C-4AD"

class KMPurchaseEmbeddedWindowController: NSWindowController {
    
    @IBOutlet weak var mainBox: NSBox!
    
    @IBOutlet weak var yourOrderLabel: NSTextField!
    
    @IBOutlet weak var pdfReaderProLabel: NSTextField!
    @IBOutlet weak var prmiumLabel: NSTextField!
    @IBOutlet weak var oneLicenseLabel: NSTextField!
    @IBOutlet weak var removeButton1: NSButton! // 减少按钮1
    @IBOutlet weak var addButton1: NSButton! // 增加按钮1
    @IBOutlet weak var amountTextField1: NSTextField! // 数目1
    @IBOutlet weak var originalPriceLabel1: NSTextField! // 原价
    @IBOutlet weak var discountPriceLabel1: NSTextField! // 折扣
    
    @IBOutlet weak var usualAddonView: NSView!
            
    @IBOutlet weak var firmLabel: NSTextField!
    @IBOutlet weak var addbox: NSBox!
    @IBOutlet weak var textbox: NSBox!
    @IBOutlet weak var removebox: NSBox!
    @IBOutlet weak var linebox: NSBox!

    @IBOutlet weak var prodocumentView: NSView!
    @IBOutlet weak var couponView: NSView!
    @IBOutlet private weak var couponButton: NSButton!
    @IBOutlet weak var couponBox: NSBox!
    @IBOutlet weak var coupomTextField: NSTextField!
    @IBOutlet weak var couponClearButton: NSButton!
    @IBOutlet weak var applyBox: NSBox!
    @IBOutlet weak var applyButton: NSButton!
    @IBOutlet weak var coupomErrorLabel: NSTextField!
    @IBOutlet weak var coupomErrorTopLayout: NSLayoutConstraint!
    
    @IBOutlet weak var lastPriceLabel: NSTextField!
    @IBOutlet weak var lastPriceLabel1: NSTextField!
    @IBOutlet weak var discountView: NSView!
    @IBOutlet weak var discountLabel: NSTextField!
    @IBOutlet weak var discountLabel1: NSTextField!
    @IBOutlet weak var paySumLabel: NSTextField!
    @IBOutlet weak var paySumLabel1: NSTextField!
    @IBOutlet weak var discountLayoutConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var privacyLabel: NSTextField!
    
    @IBOutlet weak var billInformationLabel: NSTextField!
        
    @IBOutlet weak var emailLabel: NSTextField!
    @IBOutlet weak var emailTextField: NSTextField!
    @IBOutlet weak var emailBox: NSBox!
    @IBOutlet weak var errorView: NSView!
    @IBOutlet weak var errorLabel: NSTextField!
    @IBOutlet weak var errorLabelTopLayout: NSLayoutConstraint!
    
    @IBOutlet weak var paymentMethodLabel: NSTextField!
    @IBOutlet weak var paypalButton: NSButton!
    @IBOutlet weak var cardButton: NSButton!
    @IBOutlet weak var wechatPayButton: NSButton!
    @IBOutlet weak var alipayButton: NSButton!
    @IBOutlet weak var wechatPayButton2: NSButton!
    
    @IBOutlet weak var payBox: NSBox!
    @IBOutlet weak var payBoxHeight: NSLayoutConstraint!
    @IBOutlet weak var payExplainLabel: NSTextField!
    
    @IBOutlet var paypalView: NSView!
    @IBOutlet weak var paypalBox: NSBox!
    @IBOutlet weak var paypalBuyNowLabel: NSTextField!
    
    @IBOutlet var cardView: NSView!
    @IBOutlet var paddleView: NSView!
    @IBOutlet weak var paddleButton: NSButton!
    @IBOutlet weak var paddlePopUpButton: KMPopUpButton!
    @IBOutlet weak var paddleBox: NSBox!
    @IBOutlet weak var paddleTextField: NSTextField!
    
    @IBOutlet var weChatPayView: NSView!
    @IBOutlet weak var weChatBox: NSBox!
    @IBOutlet weak var weChatButton: NSButton!
    
    @IBOutlet var payResult: NSView!
    @IBOutlet weak var scanLabel: NSTextField!
    @IBOutlet weak var qrCodeImageView: NSImageView!
    @IBOutlet weak var payTypeImageView: NSImageView!
    @IBOutlet weak var successfullyView: NSView!
    @IBOutlet weak var purchasedLabel: NSTextField!
    @IBOutlet weak var successfullyLabel: NSTextField!
    @IBOutlet weak var imageBottomLayout: NSLayoutConstraint!
    @IBOutlet weak var image2BottomLayout: NSLayoutConstraint!

    @IBOutlet weak var cardButtonWidthConst: NSLayoutConstraint!
    
    private var _product_code : String = ""
    private var _product_Info: KMListingProductsModel = KMListingProductsModel(id: "23", productName: "PDF Reader Pro Advanced - Annual Plan", price: "99.99", maxDeviceNum: 4, displayPrice: "0.0", levels: "3", platforms: "Windows,Android,Mac,iOS", productLineId: 1, paymentModel: 1, cycle: 4, cnyPrice: "0.0", displayCnyPrice: "0.0", upgradePrice: "0.0", code: "advanced-annual-subscription-trail")

    private var pdfCount: Int = 1
    private var _paymentMethod: KMPaymentType = .paypal
    private var _productType: ProductType = .ipaConvert
    private var couponCode: String = "" //优惠卷
    private var discountAmount: String = "" // 优惠金额
    private var discountScale: String = "" // 优惠比例
    private var orderID: String = "" // 订单ID
    
    private var timer: Timer?
    private var pollCount = 0
    private let maxPolls = 36
    private let interval: TimeInterval = 5.0

    private var _activityAlertViewController: KMActivityALertViewController?

    private let countryKeys = [
        "Afghanistan", "Aland Islands", "Albania", "Algeria", "American Samoa",
        "Andorra", "Angola", "Anguilla", "Antigua and Barbuda", "Argentina",
        "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas",
        "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize",
        "Benin", "Bermuda", "Bhutan", "Bolivia", "Bonaire, Sint Eustatius and Saba",
        "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil",
        "Brit. Indian Ocean", "British Virgin Islands", "Brunei Darussalam", "Bulgaria",
        "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde",
        "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
        "Christmas Island", "Cocos Islands", "Colombia", "Comoros", "Congo",
        "Cook Islands", "Costa Rica", "Cote D'Ivoire", "Croatia", "Curaçao", "Cyprus",
        "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
        "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
        "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France",
        "French Guiana", "French Polynesia", "French Southern Terr.", "Gabon", "Gambia",
        "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada",
        "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau",
        "Guyana", "Haiti", "Heard/ Mcdonald Islands", "Holy See/ Vatican City", "Honduras",
        "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iraq", "Ireland",
        "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan",
        "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Lao People's DR",
        "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein",
        "Lithuania", "Luxembourg", "Macao", "Macedonia", "Madagascar", "Malawi",
        "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique",
        "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
        "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique",
        "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
        "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
        "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan",
        "Palau", "Palestinian Territory", "Panama", "Papua New Guinea", "Paraguay",
        "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar",
        "Republic of Serbia", "Reunion", "Romania", "Russian Federation", "Rwanda",
        "S. Georgia/ Sandwich Islands", "Saint Helena", "Saint Kitts and Nevis",
        "Saint Lucia", "Saint Martin", "Saint Pierre and Miquelon", "Saint Vincent/ Grenadines",
        "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal",
        "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
        "Somalia", "South Africa", "South Korea", "Spain", "Sri Lanka", "Sudan",
        "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Taiwan",
        "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga",
        "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands",
        "Tuvalu", "U.S. Virgin Islands", "Uganda", "Ukraine", "United Arab Emirates",
        "United Kingdom", "United States", "United States (M.O.I.)", "Uruguay", "Uzbekistan",
        "Vanuatu", "Venezuela", "Viet Nam", "Wallis and Futuna", "Western Sahara", "Yemen",
        "Zambia", "Zimbabwe"
    ]
    private let countryAbbreviationValues = [
        "AF", "AX", "AL", "DZ", "AS", "AD", "AO", "AI", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB",
        "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BQ", "BA", "BW", "BV", "BR", "IO", "VG", "BN", "BG", "BF", "BI", "KH",
        "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CK", "CR", "CI", "HR", "CW", "CY",
        "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF",
        "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM",
        "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI",
        "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT",
        "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL",
        "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PH",
        "PN", "PL", "PT", "PR", "QA", "RS", "RE", "RO", "RU", "RW", "GS", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM",
        "ST", "SA", "SN", "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "KR", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE",
        "CH", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "VI", "UG", "UA", "AE",
        "GB", "US", "UM", "UY", "UZ", "VU", "VE", "VN", "WF", "EH", "YE", "ZM", "ZW"
    ]
    private var handler: ((Int) -> Void)!
    static var currentWindowController: KMPurchaseEmbeddedWindowController!
    private var embeddedPaymentPopWC: KMEmbeddedPaymentPopWC?
    private var successfulPaymentsNumber = 0
    private var license1 = ""
    private var licenseAI1 = ""
    private var isApplyCoupon: Bool = false
    
    private var isWindowDidLoad: Bool = false
    private var isBatchProductPriceGetFinsed: Bool = false
    
    private var discountType_: KMDiscountType = .none
    var discountCodeId: String? {
        didSet { }
    }

    @objc static func currentWC(_ productInfo: KMListingProductsModel) -> KMPurchaseEmbeddedWindowController {
        if currentWindowController != nil {
            currentWindowController.product_Info = productInfo
            currentWindowController.discountCodeId = nil
            return currentWindowController
        } else {
            let configWC: KMPurchaseEmbeddedWindowController = KMPurchaseEmbeddedWindowController.init(windowNibName: "KMPurchaseEmbeddedWindowController")
            currentWindowController = configWC;
            currentWindowController.product_Info = productInfo
            currentWindowController.discountCodeId = nil
            return currentWindowController
        }
     }
    
    @objc static func currentCode(_ productCode: String) -> KMPurchaseEmbeddedWindowController {
        if currentWindowController != nil {
            currentWindowController.product_code = productCode
            return currentWindowController
        } else {
            let configWC: KMPurchaseEmbeddedWindowController = KMPurchaseEmbeddedWindowController.init(windowNibName: "KMPurchaseEmbeddedWindowController")
            currentWindowController = configWC;
            _ = configWC.window
            currentWindowController.product_code = productCode
            return currentWindowController
        }
     }
    

    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.
        window?.title = ""
        window?.makeFirstResponder(nil)
                
        xibInitialization()
        paymentMethod = .paypal
        priceRefresh(productsModel: product_Info)
        
        self.window?.delegate = self;
        
        isWindowDidLoad = true
        _configFirmLabel()
        firmLabel.isHidden = true
        
        couponView.isHidden = false
        couponButton.isHidden = false
        couponBox.isHidden = true
        applyBox.isHidden = true
        
        DistributedNotificationCenter.default.addObserver(self, selector: #selector(themeChanged(_:)), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)

    }
    
    @objc func themeChanged(_ notification: Notification) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self._updateViewColor()
        }
    }
    
    override func close() {
        super.close()
        
        self.clearEventData()
    }
    
    override func showWindow(_ sender: Any?) {
        super.showWindow(sender)
        
        discountType_ = .none
        
        if let data = discountCodeId, _canUseDiscountCode() {
            self._applyDiscount(data) { [weak self] success, result in
                if(success == true) {
                    guard let productResult = result else {
                        return
                    }
                    guard let couponModel = productResult.checkCoupon else {
                        return
                    }
                    
                    let priceString = couponModel.priceString
                    self?.product_Info.priceString = priceString
                    
                    let cnyPriceString = couponModel.cnyPriceString
                    self?.product_Info.cnyPriceString = cnyPriceString //批量时将总价赋给priceString,只显示priceString价格了,其他的置空
                    
                    self?.product_Info.upgradePriceString = couponModel.upgradePriceString
                    self?.product_Info.cnyUpgradePriceString = couponModel.upgradecnyPriceString
                    self?.product_Info.displayPriceString = couponModel.displayPriceString
                    self?.product_Info.displayCnyPriceString = couponModel.displayCnyPriceString
                    
                    self?.product_Info.individualPriceString = couponModel.priceString
                    self?.product_Info.individualCnyPriceString = couponModel.cnyPriceString
                    self?.product_Info.verifyofferCode = data
                    
                    if self?._paymentMethod == .alipay || self?._paymentMethod == .wxpay {
                        self?.updatePrice()
                    }
                    
                    self?.couponButton.isHidden = true
                    
                    self?.priceRefresh(productsModel: self?._product_Info ?? KMListingProductsModel())
                }else {
                    KMPrint("The coupon code is invalid. Please try again.")
                }
            }
        }
    }
    
    public func openWindow(discountType: KMDiscountType) {
        self.showWindow(nil)
        
        discountType_ = discountType
    }
    
    // MARK: DMG Action
    func isOneTimePurchase(_ productinfo: KMListingProductsModel) -> Bool {
        //买断版本才能一次购买多个,并且购买多个时,不会自动绑定,需要在后台给自己绑定才能有会员权益
        if productinfo.paymentModel == 2 {
            return true
        }
        return false
    }
    
    func updateProduct_Info() -> Void { //重新获取产品接口
        if KMMemberInfo.shared.isLogin {
            let model = KMProductModel.shared
            if(pdfCount > 1) {
                model.getDMGBatchProductPriceInfosForMember(productId: _product_Info.id, num: pdfCount) { [weak self] success, result in
                    guard let pricesArrays : KMMemberProductResult = result else {
                        return
                    }
                    guard let batchProductPrice : KMBatchProductPriceModel = pricesArrays.batchProductPrice else {
                        return
                    }
                    //原价更新
                    let priceString = batchProductPrice.totalPrice
                    self?.product_Info.priceString = priceString
                    
                    let cnyPriceString = batchProductPrice.cnyTotalPrice
                    self?.product_Info.cnyPriceString = cnyPriceString //批量时将总价赋给priceString,只显示priceString价格了,其他的置空
                    
                    self?.product_Info.upgradePriceString = nil
                    self?.product_Info.displayPriceString = nil
                    self?.product_Info.displayCnyPriceString = nil
                    self?.product_Info.individualPriceString = batchProductPrice.price
                    self?.product_Info.individualCnyPriceString = batchProductPrice.cnyPrice
                    self?.product_Info.verifyofferCode = ""
                    
                    if self?._paymentMethod == .alipay || self?._paymentMethod == .wxpay {
                        self?.updatePrice()
                    }
                    self?.priceRefresh(productsModel: self?.product_Info ?? KMListingProductsModel())
                }
            } else {
                if _canUseDiscountCode() {
                    self._applyDiscount(discountCodeId ?? "") { [weak self] success, result in
                        if(success == true) {
                            guard let productResult = result else {
                                return
                            }
                            guard let couponModel = productResult.checkCoupon else {
                                return
                            }
                            
                            let priceString = couponModel.priceString
                            self?.product_Info.priceString = priceString
                            
                            let cnyPriceString = couponModel.cnyPriceString
                            self?.product_Info.cnyPriceString = cnyPriceString //批量时将总价赋给priceString,只显示priceString价格了,其他的置空
                            
                            self?.product_Info.upgradePriceString = couponModel.upgradePriceString
                            self?.product_Info.cnyUpgradePriceString = couponModel.upgradecnyPriceString
                            self?.product_Info.displayPriceString = couponModel.displayPriceString
                            self?.product_Info.displayCnyPriceString = couponModel.displayCnyPriceString
                            
                            self?.product_Info.individualPriceString = couponModel.priceString
                            self?.product_Info.individualCnyPriceString = couponModel.cnyPriceString
                            self?.product_Info.verifyofferCode = self?.discountCodeId ?? ""
                            
                            if self?._paymentMethod == .alipay || self?._paymentMethod == .wxpay {
                                self?.updatePrice()
                            }
                            
                            self?.couponButton.isHidden = true
                            
                            self?.priceRefresh(productsModel: self?._product_Info ?? KMListingProductsModel())
                        }else {
                            KMPrint("The coupon code is invalid. Please try again.")
                        }
                    }
                } else {
                    model.getDMGProductPriceInfosForMember(productId: product_Info.id, isEducation: 0) { [weak self] success, result in
                        if success {
                            guard let productResults : KMMemberProductResult = result else {
                                return
                            }
                            guard let products : [KMListingProductsModel] = productResults.listingProducts else {
                                return
                            }
                            guard let product : KMListingProductsModel = products.first else {
                                return
                            }
                            if self?._canUseDiscountCode() == true {
                                return
                            }
                            self?.product_Info = product;
                            for tProduct in products {
                                if tProduct.id == self?.product_Info.id {
                                    self?.product_Info = product;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    // MARK: UI
    
    private func xibInitialization() -> Void {
        prodocumentView.wantsLayer = true
        prodocumentView.layer?.cornerRadius = 5.0
        prodocumentView.layer?.borderWidth = 1.0
        
        _showOrHideCardButton(show: true)

        if pdfCount <= 1 {
            addbox.fillColor = NSColor(hex: "#F1F1F2")
        } else {
            addbox.fillColor = NSColor(named: "0E1114 1") ?? .white
        }
        removebox.fillColor =  NSColor(named: "0E1114 1") ?? .white

        _updateViewColor()

        textbox.fillColor = NSColor(named: "0E1114 2") ?? .white
        yourOrderLabel.stringValue = NSLocalizedString("Your Order", comment: "")
        yourOrderLabel.textColor = NSColor(named: "KMPurchaseTitleColor")
        yourOrderLabel.font = NSFont.SFProTextBoldFont(20.0)
        
        pdfReaderProLabel.textColor = NSColor(named: "KMPurchaseTitleColor")
        pdfReaderProLabel.font = NSFont.SFProTextRegularFont(14.0)
        prmiumLabel.textColor = NSColor(named: "KMPurchaseSubTitleColor")
        prmiumLabel.font = NSFont.SFProTextRegularFont(12.0)
        oneLicenseLabel.textColor = NSColor(named: "KMPurchaseSubTitleColor")
        oneLicenseLabel.font = NSFont.SFProTextRegularFont(12.0)
        originalPriceLabel1.textColor = NSColor(named: "KMPurchaseTitleColor")
        originalPriceLabel1.font = NSFont.SFProTextRegularFont(16.0)
        discountPriceLabel1.textColor = NSColor(named: "KMPurchaseDiscountColor")
        discountPriceLabel1.font = NSFont.SFProTextRegularFont(9.0)
        refreshLicenseCodeView(isReveal: false)
                
        oneLicenseLabel.stringValue = NSLocalizedString("and more offline. It's one time purchase.", comment: "")
        oneLicenseLabel.isHidden = true
        
        refreshLicenseCodeView(isReveal: true)
        refreshLicenseCodeErrorView(isReveal: false)
        
        if pdfCount > 1 {
            removeButton1.isEnabled = true
        } else {
            removeButton1.isEnabled = false
        }
        amountTextField1.delegate = self

        couponButton.title = NSLocalizedString("I have a coupon?", comment: "")
        couponButton.setTitleColor(color: NSColor(named: "KMPurchaseCouponColor")!, font: NSFont.SFProTextRegularFont(14))
        coupomTextField.placeholderString = NSLocalizedString("Please enter a coupon code.", comment: "")
        applyButton.title = NSLocalizedString("Apply", comment: "")
        applyButton.setTitleColor(color: NSColor(named: "KMPurchaseApplyColor") ?? NSColor.black, font: NSFont.SFProTextRegularFont(13))
        couponBox.borderColor = NSColor(named: "KMPurchaseCouponBoxColor") ?? NSColor.gray
        couponBox.fillColor = NSColor(named: "KMPurchaseCouponBoxFillColor") ?? NSColor.gray
        applyBox.borderColor = NSColor(named: "KMPurchaseApplyColor") ?? NSColor.black
        coupomErrorLabel.textColor = NSColor(named: "KMPurchaseErrorColor")
        coupomErrorLabel.font = NSFont.SFProTextRegularFont(11.0)
        refreshCouponError(isReveal: false)
        
        lastPriceLabel.stringValue = NSLocalizedString("List Price", comment: "")
        lastPriceLabel.textColor = NSColor(named: "KMPurchaseListPriceColor")
        lastPriceLabel.font = NSFont.SFProTextRegularFont(16.0)
        discountLabel.stringValue = NSLocalizedString("Discount", comment: "")
        discountLabel.textColor = NSColor(named: "KMPurchaseListPriceColor")
        discountLabel.font = NSFont.SFProTextRegularFont(16.0)
        paySumLabel.stringValue = NSLocalizedString("Pay sum", comment: "")
        paySumLabel.textColor = NSColor(named: "KMPurchaseTitleColor1")
        paySumLabel.font = NSFont.SFProTextBoldFont(24.0)
        paySumLabel1.textColor = NSColor(named: "KMPurchaseCouponColor")
        paySumLabel1.font = NSFont.SFProTextBoldFont(24.0)
        
        privacyLabel.isEditable = false
        privacyLabel.isSelectable = true
        privacyLabel.allowsEditingTextAttributes = true
        privacyLabel.textColor = NSColor.black
        privacyLabel.font = NSFont.SFProTextRegularFont(16.0)
        let tipsString = NSLocalizedString("Are you a student or a professor? %@ / Want a volume purchase? Please %@.", comment: "")
        let specialOffer = NSLocalizedString("Get Special Offer", comment: "")
        let contactsUs = NSLocalizedString("Contact Us", comment: "")
        let fullString = String(format: tipsString, specialOffer, contactsUs)
        let attributedString = NSMutableAttributedString(string: fullString)
        // 定义链接的范围
        let specialOfferRange = (fullString as NSString).range(of: specialOffer)
        let contactsUsRange = (fullString as NSString).range(of: contactsUs)
        let linkColor = NSColor(red: 73/255.0, green: 130/255.0, blue: 230/255.0, alpha: 1.0)
        let font = NSFont.SFProTextRegularFont(16.0) // 与普通文本相同的字体
        attributedString.addAttributes([
            .foregroundColor: NSColor(named: "KMPurchase_99A6B2") as Any,
            .font: font
        ], range: (fullString as NSString).range(of: fullString))
        attributedString.addAttributes([
            .foregroundColor: linkColor,
            .link: NSLocalizedString("https://www.pdfreaderpro.com/store?mode=edu", comment: ""),
            .font: font
        ], range: specialOfferRange)
        attributedString.addAttributes([
            .foregroundColor: linkColor,
            .link: NSLocalizedString("https://www.pdfreaderpro.com/vpp-purchase-program", comment: ""),
            .font: font
        ], range: contactsUsRange)
        privacyLabel.attributedStringValue = attributedString

        billInformationLabel.stringValue = NSLocalizedString("Billing Information", comment: "")
        billInformationLabel.textColor = NSColor(named: "KMPurchaseTitleColor1")
        billInformationLabel.font = NSFont.SFProTextRegularFont(14.0)
        emailLabel.stringValue = NSLocalizedString("You can purchase with the account linked to this email. If the email is not registered, an account will be automatically created for you upon successful purchase.", tableName: "MemberCenterLocalizable", comment: "")
        emailLabel.textColor = NSColor(named: "KMPurchaseTitleColor1")
        emailLabel.font = NSFont.SFProTextRegularFont(14.0)
        emailTextField.placeholderString = NSLocalizedString("Email to receive license code", comment: "")
        emailBox.borderColor = NSColor(named: "KMPurchase_DADBDE")!
//        emailBox.fillColor = NSColor(named: "KMPurchase_FFFFFF")!
        errorLabel.stringValue = NSLocalizedString("Please enter your email for license receiving.", comment: "")
        emailTextField.stringValue = KMMemberInfo.shared.userEmail

        emailTextField.delegate = self
        errorLabel.textColor = NSColor(named: "KMPurchaseErrorColor")
        errorLabel.font = NSFont.SFProTextRegularFont(11.0)

        paymentMethodLabel.stringValue = NSLocalizedString("Payment Method", comment: "")
        paymentMethodLabel.textColor = NSColor(named: "KMPurchaseTitleColor1")
        paymentMethodLabel.font = NSFont.SFProTextRegularFont(14.0)
        wechatPayButton2.isHidden = true
        
        payExplainLabel.isEditable = false
        payExplainLabel.isSelectable = true
        payExplainLabel.allowsEditingTextAttributes = true
        payExplainLabel.textColor = NSColor.black
        payExplainLabel.font = NSFont.SFProTextRegularFont(11.0)
        discountPriceLabel1.isHidden = true

        let localizedString = NSLocalizedString("By submitting this order, I agree to the %@ and %@ for subscription products", comment: "")
        let privacyPolicy = NSLocalizedString("Privacy Policy", comment: "")
        let termsOfService = NSLocalizedString("Terms of Service", comment: "")
        let fullString1 = String(format: localizedString, privacyPolicy, termsOfService)
        let attributedString1 = NSMutableAttributedString(string: fullString1)
        let privacyPolicyRange = (fullString1 as NSString).range(of: privacyPolicy)
        let termsOfServiceRange = (fullString1 as NSString).range(of: termsOfService)
        let linkColor1 = NSColor(red: 73/255.0, green: 130/255.0, blue: 230/255.0, alpha: 1.0)
        let font1 = NSFont.SFProTextRegularFont(11.0) // 与普通文本相同的字体
        attributedString1.addAttributes([
            .foregroundColor: NSColor(named: "KMPurchase_99A6B2") as Any,
            .font: font1
        ], range: (fullString1 as NSString).range(of: fullString1))
        attributedString1.addAttributes([
            .foregroundColor: linkColor1,
            .link: NSLocalizedString("https://www.pdfreaderpro.com/privacy-policy", comment: ""),
            .font: font1
        ], range: privacyPolicyRange)
        attributedString1.addAttributes([
            .foregroundColor: linkColor1,
            .link: NSLocalizedString("https://www.pdfreaderpro.com/terms_of_service", comment: ""),
            .font: font1
        ], range: termsOfServiceRange)
        payExplainLabel.attributedStringValue = attributedString1
        
        paypalBuyNowLabel.stringValue = NSLocalizedString("Buy Now", comment: "")
        paypalBuyNowLabel.textColor = NSColor.white
        paypalBuyNowLabel.font = NSFont.SFProTextBoldFont(16.0)
        
        paddleButton.title = NSLocalizedString("Continue to Pay", comment: "")
        paddleButton.setTitleColor(color: NSColor.white, font: NSFont.SFProTextBoldFont(16))
        paddlePopUpButton.type = .arrowDown
        paddlePopUpButton.removeAllItems()
        paddlePopUpButton.addItems(withTitles: countryKeys)
        let preferredLanguage = Locale.preferredLanguages.first ?? "en"
        if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
            paddlePopUpButton.selectItem(at: 45)
        } else {
            paddlePopUpButton.selectItem(at: 229)
        }
        paddleBox.fillColor = NSColor(named: "KMPurchase_FFFFFF") ?? NSColor.white
        paddleBox.borderColor = NSColor(named: "KMPurchase_DADBDE") ?? NSColor.gray
        paddleTextField.placeholderString = NSLocalizedString("Postcode", comment: "")
        paddleTextField.delegate = self
        
        weChatButton.title = NSLocalizedString("Continue to Pay", comment: "")
        weChatButton.setTitleColor(color: NSColor.white, font: NSFont.SFProTextBoldFont(16))
        
        qrCodeImageView.imageScaling = .scaleProportionallyUpOrDown
        scanLabel.textColor = NSColor(named: "KMPurchase_000000")
        scanLabel.font = NSFont.SFProTextRegularFont(12)
        successfullyView.isHidden = true
        purchasedLabel.stringValue = NSLocalizedString("Purchased", comment: "")
        purchasedLabel.textColor = NSColor(named: "KMPurchase_002143")
        purchasedLabel.font = NSFont(name: "Segoe UI", size: 18.0)
        successfullyLabel.stringValue = NSLocalizedString("Successfully", comment: "")
        successfullyLabel.textColor = NSColor(named: "KMPurchase_002143")
        successfullyLabel.font = NSFont(name: "Segoe UI", size: 18.0)
        
        emailErrorLabel(isReveal: false)
    }
    
    private func _updateViewColor() {
        paddlePopUpButton.wantsLayer = true
        if KMAppearance.isDarkMode() {
            prodocumentView.layer?.borderColor = NSColor(hex: "#E2E3E5").cgColor
            paddlePopUpButton.layer?.backgroundColor = NSColor(hex: "#393C3E").cgColor
        } else {
            prodocumentView.layer?.borderColor = NSColor(hex: "#E2E3E5").cgColor
            paddlePopUpButton.layer?.backgroundColor = NSColor(hex: "#FFFFFF").cgColor
        }
    }
    
    private func priceRefresh(productsModel: KMListingProductsModel) -> Void {
        if productsModel.code == "" {
            return
        }
        var listPrice: Float = 0.0
        var discount: Float = 0.0
        var paySum: Float = 0.0
        var discount1: Float = 0.0
        var original1: Float = 0.0
        var abbreviation = "USD"
        
        if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
            abbreviation = "CNY"
        }
                
        let insting = Float(showSinglePriceString())
        listPrice = Float(String(format: "%.2f", Float((insting ?? 0) * Float(pdfCount)))) ?? 0  //单价*购买个数
        
        if _product_code == KMAdvancedAnnualSubscriptionTrailCodeKey_DMG {
            var tipsString = NSLocalizedString("7-day free trial, then auto-renew at %@/year", tableName: "MemberCenterLocalizable", comment: "")
            let value = String(format: "%@ %.2f", abbreviation, insting ?? 0)
            let fullString = String(format: tipsString, value)
            
            prmiumLabel.stringValue = fullString
            original1 = Float(showOrgPriceString()) ?? 0
            discount1 = Float(showOrgShowPriceString()) ?? 0
            paySum = discount1
            discount = listPrice - paySum
        } else if _product_code == "advanced-annual-subscription-blackFive"   ||
            _product_code == "advanced-permanent-blackFive"   ||
            _product_code == KMAISubscriptionYearTrailCodeKey_DMG {
            // 全平台高级版年订阅             99.9 美金,带免费试用
            // 全平台高级版年订阅             99.9 美金,黑五订单
            // Mac & Win 双平台高级永久      119.99 美金,黑五订单
            // AI 年订阅                    125.99 美金,带免费试用
            
            var tipsString = NSLocalizedString("%.2f/year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            if product_Info.cycle == 4 {
                tipsString = NSLocalizedString("%.2f/year, auto-renewal", tableName: "MemberCenterLocalizable",comment: "")
            }
            if product_Info.cycle == 3 {
                tipsString = NSLocalizedString("%.2f/half a year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 2 {
                tipsString = NSLocalizedString("%.2f/quarter, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 1 {
                tipsString = NSLocalizedString("%.2f/monthly, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 0 {
                tipsString = NSLocalizedString("%.2f/Permanent Plan", tableName: "MemberCenterLocalizable", comment: "")
            }
            
            let fullString = String(format: tipsString, insting ?? 0)
            
            prmiumLabel.stringValue = String(format: "%@ %@", abbreviation, fullString)
            original1 = Float(showOrgPriceString()) ?? 0
            discount1 = Float(showOrgShowPriceString()) ?? 0
            paySum = discount1
            discount = listPrice - paySum
        }
        
        if _product_code == "advanced-annual-subscription"  ||
            _product_code == "standard-annual-subscription"  ||
            _product_code == "ai-subscription-month" {
            // 全平台高级版年订阅             99.9 美金,无试用
            // 全平台标准版年订阅             79.9 美金
            // Mac & Win 双平台高级永久      119.99 美金
            // AI 月订阅                    14.99 美金
            
            var tipsString = NSLocalizedString("%.2f/year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            if product_Info.cycle == 4 {
                tipsString = NSLocalizedString("%.2f/year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 3 {
                tipsString = NSLocalizedString("%.2f/half a year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 2 {
                tipsString = NSLocalizedString("%.2f/quarter, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 1 {
                tipsString = NSLocalizedString("%.2f/monthly, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 0 {
                tipsString = NSLocalizedString("%.2f/Permanent Plan", tableName: "MemberCenterLocalizable", comment: "")
            }
            
            var fullString = String(format: tipsString, insting ?? 0)
            
            let originalStr = showOrgPriceString()
            let discountStr = showOrgShowPriceString()
            if originalStr == discountStr  {
                
            } else {
                if discountStr.isEmpty == false && discountStr != "0" {
                    let data = Float(discountStr) ?? 0
                    fullString = String(format: tipsString, data)
                }
            }

            prmiumLabel.stringValue = String(format: "%@ %@", abbreviation, fullString)
            original1 = Float(showOrgPriceString()) ?? 0
            discount1 = Float(showOrgShowPriceString()) ?? 0
            paySum = discount1
            discount = listPrice - paySum
        }
        
        if _product_code == "advanced-permanent" {
            // Mac & Win 双平台高级永久      119.99 美金
            
            var tipsString = NSLocalizedString("%.2f/year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            if product_Info.cycle == 4 {
                tipsString = NSLocalizedString("%.2f/year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 3 {
                tipsString = NSLocalizedString("%.2f/half a year, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 2 {
                tipsString = NSLocalizedString("%.2f/quarter, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 1 {
                tipsString = NSLocalizedString("%.2f/monthly, auto-renewal", tableName: "MemberCenterLocalizable", comment: "")
            }
            if product_Info.cycle == 0 {
                tipsString = NSLocalizedString("%.2f/Permanent Plan", tableName: "MemberCenterLocalizable", comment: "")
            }
            let fullString = String(format: tipsString, insting ?? 0)

            prmiumLabel.stringValue = String(format: "%@ %@", abbreviation, fullString)
            original1 = Float(showOrgPriceString()) ?? 0
            discount1 = Float(showOrgShowPriceString()) ?? 0
            paySum = discount1
            discount = listPrice - paySum
        }
        
        originalPriceLabel1.stringValue = String(format: "%@ %@", abbreviation, String(format: "%.2f", insting ?? 0))
     
        lastPriceLabel1.stringValue = String(format: "%@ %@", abbreviation, String(format: "%.2f", listPrice))
        discountLabel1.stringValue = String(format: "%@ %@", abbreviation, String(format: "%.2f", discount))
        paySumLabel1.stringValue = String(format: "%@ %@", abbreviation, String(format: "%.2f", paySum))
        discountLayoutConstraint.constant = discountView.isHidden ? -CGRectGetHeight(discountView.bounds) : 8
    }
    
    // MARK: Active

    @IBAction func amountButtonAction(_ sender: NSButton) {
        if sender.tag == 0 || sender.tag == 1 {
            if sender.tag == 0 {
                if pdfCount > 1 {
                    pdfCount -= 1
                }
            }
            if sender.tag == 1 {
                if pdfCount < 9999 {
                    pdfCount += 1
                }
            }
            
            if pdfCount > 1 {
                removeButton1.isEnabled = true
            } else {
                removeButton1.isEnabled = false
            }
            
            if pdfCount > 100 {
                wechatPayButton2.isHidden = false
                cardButton.isHidden = true
                wechatPayButton.isHidden = true
                if _paymentMethod == .paddle {
                    paymentMethod = .paypal
                }
            } else {
                wechatPayButton2.isHidden = true
//                cardButton.isHidden = false
                wechatPayButton.isHidden = false
            }
            amountTextField1.stringValue = String(pdfCount)

            let viewHidden = pdfCount <= 1
            firmLabel.isHidden = viewHidden
            if viewHidden {
                addbox.fillColor = NSColor(hex: "#F1F1F2")
            } else {
                addbox.fillColor = NSColor(named: "0E1114 1") ?? .white
            }
            couponView.isHidden = !viewHidden
        }
        
        // 价格刷新
        priceRefresh(productsModel: _product_Info)
        
        let model = KMProductModel.shared
        isBatchProductPriceGetFinsed = false
        
        updateProduct_Info()

    }
    
    @IBAction func payButtonAction(_ sender: NSButton) {
        emailErrorLabel(isReveal: false)
        paymentMethod = KMPaymentType(rawValue: uint32(sender.tag)) ?? .paypal
        // 价格刷新
        priceRefresh(productsModel: _product_Info)
    }
    
    @IBAction func couponButtonAction(_ sender: NSButton) {
        couponButton.isHidden = true
        couponBox.isHidden = false
        applyBox.isHidden = false
    }
    
    @IBAction func applyButtonAction(_ sender: NSButton) {
        if coupomTextField.stringValue == "" {
            let alert = NSAlert()
            alert.alertStyle = .critical
            alert.messageText = NSLocalizedString("Error Information", comment: "")
            alert.informativeText = NSLocalizedString("Please enter a coupon code.", comment: "")
            alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
            alert.runModal()
            return
        }
        
        if(Int(amountTextField1.stringValue) ?? 0 > 1) { //购买多个不支持优惠卷
            return
        }
        
        if KMMemberCenterManager.manager.isConnectionAvailable() == false {
            let alert = NSAlert()
            alert.alertStyle = .critical
            alert.messageText = NSLocalizedString("Error Information", comment: "")
            alert.informativeText = NSLocalizedString("Please make sure your internet connection is available.", comment: "")
            alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
            alert.runModal()
            return
        }
        
        self.refreshCouponError(isReveal: false)
        applyButton.isEnabled = false
        coupomTextField.isEnabled = false
        
        window?.showWaitingView()
        KMMemberCenterManager.manager.checkCoupon(productId: product_Info.id, userId: KMMemberInfo.shared.userID, code: coupomTextField.stringValue) {[weak self] success, result in
            self?.window?.hideWaitingView()
            
            KMMainThreadExecute {
                if(success == true) {
                    let alert = NSAlert()
                    alert.alertStyle = .critical
                    alert.messageText = NSLocalizedString("Successfully", comment: "")
                    _ = alert.runModal()
                    
                    guard let productResult : KMMemberProductResult = result else {
                        return
                    }
                    guard let couponModel : KMCheckCouponModel = productResult.checkCoupon else {
                        return
                    }
                    
                    let priceString = couponModel.priceString
                    self?.product_Info.priceString = priceString
                    
                    let cnyPriceString = couponModel.cnyPriceString
                    self?.product_Info.cnyPriceString = cnyPriceString //批量时将总价赋给priceString,只显示priceString价格了,其他的置空
                    
                    self?.product_Info.upgradePriceString = couponModel.upgradePriceString
                    self?.product_Info.cnyUpgradePriceString = couponModel.upgradecnyPriceString
                    self?.product_Info.displayPriceString = couponModel.displayPriceString
                    self?.product_Info.displayCnyPriceString = couponModel.displayCnyPriceString
                    
                    self?.product_Info.individualPriceString = couponModel.priceString
                    self?.product_Info.individualCnyPriceString = couponModel.cnyPriceString
                    self?.product_Info.verifyofferCode = self?.coupomTextField.stringValue ?? ""
                    
                    if self?._paymentMethod == .alipay || self?._paymentMethod == .wxpay {
                        self?.updatePrice()
                    }
                    
                    self?.priceRefresh(productsModel: self?._product_Info ?? KMListingProductsModel())
                }else {
                    let alert = NSAlert()
                    alert.alertStyle = .critical
                    alert.messageText = NSLocalizedString("Error Information", comment: "")
                    alert.informativeText = NSLocalizedString("The coupon code is invalid. Please try again.", comment: "")
                    alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
                    let result = alert.runModal()
                    if (result == .alertFirstButtonReturn) {
                    }
                }
            }
            
        }
    }
    
    @IBAction func paddlePopUpAction(_ sender: NSPopUpButton) {
        
    }
    
    @IBAction func couponClearButton(_ sender: NSButton) {
        coupomTextField.stringValue = ""
        couponClearButton.isHidden = true
        applyButton.isEnabled = true
        coupomTextField.isEnabled = true
        refreshCouponError(isReveal: false)
    }
        
    @IBAction func buyAction(_ sender: NSButton) {
        if emailTextField.stringValue == "" {
            emailErrorLabel(isReveal: true)
            return
        }
        if paymentMethod == .paddle {
            if !isNumeric(paddleTextField.stringValue) && paddleTextField.stringValue != "" {
                let alert = NSAlert()
                alert.alertStyle = .critical
                alert.messageText = NSLocalizedString("Error Information", comment: "")
                alert.informativeText = NSLocalizedString("Please enter the correct postcode.", comment: "")
                alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
                alert.runModal()

                return
            }
        }
        if paymentMethod == .paypal {
            paypalBox.fillColor = NSColor(named: "KMPurchaseBoxColor1") ?? NSColor.blue
        } else if paymentMethod == .paddle {
            paddleView.wantsLayer = true
            paddleView.layer?.backgroundColor = NSColor(named: "KMPurchaseBoxColor1")?.cgColor ?? NSColor.blue.cgColor
        } else if paymentMethod == .wxpay {
            weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor1") ?? NSColor.blue
        } else if paymentMethod == .alipay {
            weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor1") ?? NSColor.blue
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            guard let strongSelf = self else { return }
            if strongSelf.paymentMethod == .paypal {
                strongSelf.paypalBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
            } else if strongSelf.paymentMethod == .paddle {
                strongSelf.paddleView.wantsLayer = true
                strongSelf.paddleView.layer?.backgroundColor = NSColor(named: "KMPurchaseBoxColor")?.cgColor ?? NSColor.blue.cgColor
            } else if strongSelf.paymentMethod == .wxpay {
                strongSelf.weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
            } else if strongSelf.paymentMethod == .alipay {
                strongSelf.weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
            }
        }

        var couponCode = ""
        if product_Info.verifyofferCode.isEmpty == false  {
            couponCode = product_Info.verifyofferCode
        }
        
        let model = KMProductModel.shared
        if isOneTimePurchase(_product_Info) {
            let price = showPayPriceString()
            
            model.creatOrder(productId: _product_Info.id,
                             paymentMethod: getPurchasePaymentMethod(),
                             price: price,
                             discountFlag: getOneTimePurchaseDiscountFlag(),
                             couponCode: couponCode,
                             num: pdfCount) { success, result in
                if success {
                    if let dataInfo = result {
                        self.orderID = result?.createOrder?.orderId ?? ""
                        let page_pay_url = result?.createOrder?.payHref ?? ""
                        let qrCode = result?.createOrder?.qrCode ?? ""
                        if self.paymentMethod == .paddle || self.paymentMethod == .paypal {
                            if self.orderID == "" || page_pay_url == "" {
                                DispatchQueue.main.async {
                                    let alert = NSAlert()
                                    alert.alertStyle = .critical
                                    alert.messageText = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
                                    alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
                                    alert.runModal()
                                }
                            } else {
                                self.openWebView(page_pay_url)
                            }
                        } else if self.paymentMethod == .wxpay || self.paymentMethod == .alipay {
                            if self.orderID == "" || qrCode == "" {
                                DispatchQueue.main.async {
                                    let alert = NSAlert()
                                    alert.alertStyle = .critical
                                    alert.messageText = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
                                    alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
                                    alert.runModal()
                                }
                            } else {
                                self.scanCode(qrCode)
                            }
                        }
                    } else {
                        DispatchQueue.main.async {
                            let alert = NSAlert()
                            alert.alertStyle = .critical
                            alert.messageText = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
                            alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
                            alert.runModal()
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        let alert = NSAlert()
                        alert.alertStyle = .critical
                        alert.messageText = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
                        alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
                        alert.runModal()
                    }
                }
            }
        } else {
            var priceString = showPayPriceString()
            model.createSubscriber(productId: _product_Info.id,
                                   paymentMethod: getPurchasePaymentMethod(),
                                   price: priceString,
                                   discountFlag: getOneTimePurchaseDiscountFlag(),
                                   couponCode: couponCode,
                                   num: pdfCount) { success, result in
                if success {
                    if let dataInfo = result {
                        self.orderID = result?.createOrder?.orderId ?? ""
                        let page_pay_url = result?.createOrder?.payHref ?? ""
                        if self.orderID == "" || page_pay_url == "" {
                            DispatchQueue.main.async {
                                let alert = NSAlert()
                                alert.alertStyle = .critical
                                alert.messageText = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
                                alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
                                alert.runModal()
                            }
                        } else {
                            if self.paymentMethod == .paddle || self.paymentMethod == .paypal {
                                self.openWebView(page_pay_url)
                            }
                        }
                    } else {
                        DispatchQueue.main.async {
                            let alert = NSAlert()
                            alert.alertStyle = .critical
                            alert.messageText = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
                            alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
                            alert.runModal()
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        let alert = NSAlert()
                        alert.alertStyle = .critical
                        alert.messageText = NSLocalizedString("Please check if the information is wrong or the network is error.", comment: "")
                        alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
                        alert.runModal()
                    }
                }
            }
        }
    }
    
    func getPurchasePaymentMethod() -> Int {
        switch self.paymentMethod {
        case .paypal:
            return 0;
        case .alipay:
            return 1;
        case .wxpay:
            return 2;
        case .paddle:
            return 3;
        default:
            return 1;
        }
    }
    
    func getOneTimePurchaseDiscountFlag() -> Int {
        if pdfCount > 1 { //批量购买
            return 4
        } else {
            var couponCode = ""
            if _product_Info.verifyofferCode.isEmpty == false {
                couponCode = _product_Info.verifyofferCode
            }
            
            if(couponCode.isEmpty == false) {//判断是否有使用优惠卷
                if _product_code == "advanced-annual-subscription-blackFive" ||
                    _product_code == "advanced-permanent-blackFive" {
                    return 11
                } else {
                    return 1
                }
            } else {
                if _product_code == "advanced-annual-subscription-blackFive"{ //黑五订阅
                    if(_product_Info.upgradePriceString?.isEmpty == false) { //升级
                        return 2
                    } else {
                        return 5
                    }
                } else if _product_code == "advanced-permanent-blackFive" {//黑五买断
                    return 5
                } else if _product_code == "advanced-annual-subscription" { //高级订阅
                    if(_product_Info.upgradePriceString?.isEmpty == false) { //升级
                        return 2
                    } else {
                        return 0
                    }
                } else if _product_code == "advanced-annual-subscription-trail" ||
                          _product_code == "ai-subscription-year-trail" { //试用
                    return 5
                } else {
                    return 0
                }
            }
        }
    }
    
    func getPurchaseDiscountFlag() -> Int {
        var couponCode = ""
        if coupomErrorLabel.isHidden {
            couponCode = coupomTextField.stringValue
        }
        if couponCode == "" {
            if _product_code == "advanced-annual-subscription-blackFive" ||
                _product_code == "advanced-permanent-blackFive" {
                return 5
            }
            if _product_code == "advanced-annual-subscription-trail" ||
                _product_code == "ai-subscription-year-trail" {
                return 5
            }
            return 0
        } else {
            if _product_code == "advanced-annual-subscription-blackFive" ||
                _product_code == "advanced-permanent-blackFive" {
                return 11
            }
            return 1
        }
    }
    
    // MARK: get & set
    
    var product_code : String { //设置code
        get {
            return _product_code
        }
        
        set {
            _product_code = newValue
            
            
            if(isSubscribeCode() == true) {
                addButton1.isEnabled = false
                wechatPayButton.isHidden = true
                alipayButton.isHidden = true
                
                prodocumentView.isHidden = true
            } else {
                addButton1.isEnabled = true
                wechatPayButton.isHidden = false
                alipayButton.isHidden = false
                
                prodocumentView.isHidden = false
            }
            if pdfCount > 1 {
                removeButton1.isEnabled = true
            } else {
                removeButton1.isEnabled = false
            }
            if(newValue == "advanced-annual-subscription-trail" ||
               newValue == "ai-subscription-year-trail") {
                couponView.isHidden = true
            }
            
            let model = KMProductModel.shared
            let products : [KMListingProductsModel] = model.dmgProductDatas?.listingProducts ?? []
            if products.count > 0 {
                for product in products {
                    if product.code == _product_code {
                        self.product_Info = product;
                        self.updateProduct_Info()
                        break
                    }
                }
            } else {
                model.getDMGProductDatas(discountCode: self.discountCodeId ?? "") { [weak self] success, result in
                    let products : [KMListingProductsModel] = model.dmgProductDatas?.listingProducts ?? []
                    if products.count > 0 {
                        for product in products {
                            if product.code == self?.product_code {
                                self?.product_Info = product;
                                //更新价格
                                self?.updateProduct_Info()
                                break
                            }
                        }
                    }
                }
            }
            
        }
    }
    
    var product_Info: KMListingProductsModel { //刷新产品ui+价格
        get {
            return _product_Info
        }
        set {
            _product_Info = newValue
            if isWindowDidLoad {
                
                xibInitialization()
                priceRefresh(productsModel: _product_Info)
                
                func isSubscribeCode()-> Bool {//是否是订阅
                    if(product_code == "standard-annual-subscription" ||
                       product_code == "advanced-annual-subscription-blackFive" ||
                       product_code == "advanced-annual-subscription-trail" ||
                       product_code == "advanced-annual-subscription" ||
                       product_code == "ai-subscription-year-trail" ||
                       product_code == "ai-subscription-month") {
                        return true
                    }
                    return false
                }
                
                func isOneTimePurchaseCode()-> Bool { //是否是一次性购买
                    if(product_code == "advanced-permanent-blackFive" ||
                       product_code == "advanced-permanent") {
                        return true
                    }
                    return false
                }
                if(_product_code == "standard-annual-subscription") {
                    pdfReaderProLabel.stringValue = NSLocalizedString("PDF Reader Pro Standard - Annual Plan", tableName: "MemberCenterLocalizable", comment: "")
                } else if (_product_code == "advanced-annual-subscription-blackFive" ||
                           _product_code == "advanced-annual-subscription-trail" ||
                           _product_code == "advanced-annual-subscription") {
                    pdfReaderProLabel.stringValue = NSLocalizedString("PDF Reader Pro Advanced - Annual Plan", tableName: "MemberCenterLocalizable", comment: "")
                } else if (_product_code == "ai-subscription-year-trail") {
                    pdfReaderProLabel.stringValue = NSLocalizedString("PDF Reader Pro Al - Annual Plan", tableName: "MemberCenterLocalizable", comment: "")
                } else if (_product_code == "ai-subscription-month") {
                    pdfReaderProLabel.stringValue = NSLocalizedString("PDF Reader Pro Al - Monthly Plan", tableName: "MemberCenterLocalizable", comment: "")
                } else if (_product_code == "advanced-permanent-blackFive" ||
                           _product_code == "advanced-permanent") {
                    pdfReaderProLabel.stringValue = NSLocalizedString("PDF Reader Pro Permanent", tableName: "MemberCenterLocalizable", comment: "")
                } else {
                    pdfReaderProLabel.stringValue = product_Info.productName //待区分多语
                }
            }
        }
    }
    
    private var paymentMethod : KMPaymentType {
        get {
           return _paymentMethod
        }
        set {
            _paymentMethod = newValue
            
            paypalButton.image = NSImage(named: "EmbeddedPayment19")
            cardButton.image = NSImage(named: "EmbeddedPayment21")
            wechatPayButton.image = NSImage(named: "EmbeddedPayment23")
            wechatPayButton2.image = NSImage(named: "EmbeddedPayment23")
            alipayButton.image = NSImage(named: "EmbeddedPayment25")
            if _paymentMethod == .paypal {
                paypalButton.image = NSImage(named: "EmbeddedPayment18")
                payBox.contentView = paypalView
                paypalBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
                payBoxHeight.constant = 60.0
            } else if _paymentMethod == .paddle {
                cardButton.image = NSImage(named: "EmbeddedPayment20")
                payBox.contentView = cardView
                paddleView.wantsLayer = true
                paddleView.layer?.backgroundColor = NSColor(named: "KMPurchaseBoxColor")?.cgColor ?? NSColor.blue.cgColor
                payBoxHeight.constant = 150.0
            } else if _paymentMethod == .wxpay {
                wechatPayButton.image = NSImage(named: "EmbeddedPayment22")
                wechatPayButton2.image = NSImage(named: "EmbeddedPayment22")
                payBox.contentView = weChatPayView
                weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
                payBoxHeight.constant = 92.0
            } else if _paymentMethod == .alipay {
                alipayButton.image = NSImage(named: "EmbeddedPayment24")
                payBox.contentView = weChatPayView
                weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
                payBoxHeight.constant = 92.0
            }
        }
    }
    
    private func updatePrice() {
        if _paymentMethod == .wxpay {
            wechatPayButton.image = NSImage(named: "EmbeddedPayment22")
            wechatPayButton2.image = NSImage(named: "EmbeddedPayment22")
            payBox.contentView = weChatPayView
            weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
            payBoxHeight.constant = 92.0
        } else if _paymentMethod == .alipay {
            alipayButton.image = NSImage(named: "EmbeddedPayment24")
            payBox.contentView = weChatPayView
            weChatBox.fillColor = NSColor(named: "KMPurchaseBoxColor") ?? NSColor.blue
            payBoxHeight.constant = 92.0
        }
    }

    
    func isSubscribeCode()-> Bool {//是否是订阅
        if(product_code == "standard-annual-subscription" ||
           product_code == "advanced-annual-subscription-blackFive" ||
           product_code == "advanced-annual-subscription-trail" ||
           product_code == "advanced-annual-subscription" ||
           product_code == "ai-subscription-year-trail" ||
           product_code == "ai-subscription-month") {
            return true
        }
        return false
    }
    
    func isOneTimePurchaseCode()-> Bool { //是否是一次性购买
        if(product_code == "advanced-permanent-blackFive" ||
           product_code == "advanced-permanent") {
            return true
        }
        return false
    }
           
    func isBlackFiveCode()-> Bool { //是否是黑五
        if(product_code == "advanced-permanent-blackFive" ||
           product_code == "advanced-annual-subscription-blackFive") {
            return true
        }
        return false
    }

    func isHaveAvailableCoupon()-> Bool { //是否有优惠卷
        return false
    }
    
    func showPriceString()->String {
        let preferredLanguage = Locale.preferredLanguages.first ?? "en"
        var priceString = product_Info.priceString ?? ""
        if(product_Info.upgradePriceString?.isEmpty == false) {
            priceString = product_Info.upgradePriceString ?? ""
        } else if(product_Info.displayPriceString?.isEmpty == false) {
            if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
                priceString = product_Info.displayCnyPriceString ?? ""
            } else {
                priceString = product_Info.displayPriceString ?? ""
            }
        } else if(product_Info.priceString?.isEmpty == false) {
            if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
                priceString = product_Info.cnyPriceString ?? ""
            } else {
                priceString = product_Info.priceString ?? ""
            }

        }
        return priceString
    }
    
    func showOrgPriceString()->String { //原价
        let preferredLanguage = Locale.preferredLanguages.first ?? "en"
        var priceString = product_Info.priceString ?? ""
        if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
            priceString = product_Info.cnyPriceString ?? ""
        } else {
            priceString = product_Info.priceString ?? ""
        }

        return priceString
    }
    
    func showOrgShowPriceString()->String { //实际购买显示的价格
        let preferredLanguage = Locale.preferredLanguages.first ?? "en"
        var priceString = product_Info.priceString ?? ""
        if(product_Info.upgradePriceString?.isEmpty == false) {
            if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
                priceString = product_Info.cnyUpgradePriceString ?? ""
            } else {
                priceString = product_Info.upgradePriceString ?? ""
            }
        } else if(product_Info.displayPriceString?.isEmpty == false) {
            if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
                priceString = product_Info.displayCnyPriceString ?? ""
            } else {
                priceString = product_Info.displayPriceString ?? ""
            }
        } else if(product_Info.priceString?.isEmpty == false) {
            if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
                priceString = product_Info.cnyPriceString ?? ""
            } else {
                priceString = product_Info.priceString ?? ""

            }
        }
        return priceString
    }
    
    func showSinglePriceString()->String { //单价
        var priceString = product_Info.individualPriceString ?? ""
        if NSLocalizedString("USD", tableName: "MemberCenterLocalizable", comment: "") == "CN" {
            priceString = product_Info.individualCnyPriceString ?? ""
        } else {
            priceString = product_Info.individualPriceString ?? ""
        }

        return priceString
    }
    
    func showPayPriceString()->String { //实际支付的价格
        let iswechatOrAlipayPay = (self.paymentMethod == .wxpay || self.paymentMethod == .alipay)
        var priceString = product_Info.priceString ?? ""
        if(product_Info.upgradePriceString?.isEmpty == false) {
            priceString = product_Info.upgradePriceString ?? ""
        } else if(product_Info.displayPriceString?.isEmpty == false) {
            if(iswechatOrAlipayPay) {
                priceString = product_Info.displayCnyPriceString ?? ""
            } else {
                priceString = product_Info.displayPriceString ?? ""
            }
        } else if(product_Info.priceString?.isEmpty == false) {
            if(iswechatOrAlipayPay) {
                priceString = product_Info.cnyPriceString ?? ""
            } else {
                priceString = product_Info.priceString ?? ""

            }
        }
        return priceString
    }

    
    // MARK: Private
    
    private func _showOrHideCardButton(show: Bool) {
        KMMainThreadExecute { [weak self] in
            self?.cardButton.isHidden = !show
            self?.cardButtonWidthConst.constant = !show ? 0 : 78
        }
    }
    
    private func _configFirmLabel() {
        firmLabel.isEditable = false
        firmLabel.isSelectable = true
        firmLabel.allowsEditingTextAttributes = true
        firmLabel.textColor = NSColor.black
        firmLabel.font = NSFont.SFProTextRegularFont(14.0)
        let firmString = NSLocalizedString("If you need to manage seats in PDF Reader Pro, please purchase the %@.", tableName: "MemberCenterLocalizable", comment: "")
        let enterpriseStr = NSLocalizedString("enterprise version", tableName: "MemberCenterLocalizable", comment: "")
        let fireFullString = String(format: firmString, enterpriseStr)
        let firmLinkColor = NSColor(named: "4982E6") ?? NSColor.blue
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .right // 设置为右对齐
        let attri = NSMutableAttributedString(string: fireFullString, attributes: [.foregroundColor : firmLinkColor, .font : NSFont.SFProTextRegularFont(14.0),.paragraphStyle:paragraphStyle,])
        // 定义链接的范围
        let enterpriseRange = (fireFullString as NSString).range(of: enterpriseStr)
        let firmFont = NSFont.SFProTextRegularFont(14.0) // 与普通文本相同的字体
        attri.addAttributes([
            .foregroundColor: NSColor(named: "0E1114") ?? NSColor.black as Any,
            .underlineStyle: NSUnderlineStyle.single.rawValue,
            .font: firmFont
        ], range: (fireFullString as NSString).range(of: enterpriseStr))
        attri.addAttributes([
            .foregroundColor: firmLinkColor,
            .link: kLynxpdfeditorUrl,
            .font: firmFont
        ], range: enterpriseRange)
        firmLabel.attributedStringValue = attri
    }
    
    private func uuid() -> String {
        return GetHardwareUUID()!
    }
    
    private func _trackEvent_paid() {
        self.trackEvent_dmg(eventName: self.kEventName, params: self.kEventParams, platform: .AppCenter)
    }
    
    private func _trackPurchaseCampaignEvent() {
        if self.discountType_ == .newUserGift {
            self.trackEvent(eventName: "Purchase_Campaign", params: ["Campaign_NewUser":"Tbr_Coupon"], platform: .firebase)
        } else if self.discountType_ == .freeTrail {
            self.trackEvent(eventName: "Purchase_Campaign", params: ["Campaign_NewUser":"Tbr_FreeTrial"], platform: .firebase)
        } else if self.discountType_ == .advancedYearSubscribeTrialingCancel {
            self.trackEvent(eventName: self.kEventName, params: self.kEventParams, platform: .firebase)
        }
    }
    
    private func _canUseDiscountCode() -> Bool {
        guard let data = discountCodeId else {
            return false
        }
        
        if data == kKMNewUserGiftDiscountCodeId || data == kKMAdvancedYearSubscribeDiscountCodeId {
            if product_code != KMStandardAnnualSubscriptionCodeKey_DMG && product_code != KMAdvancedAnnualSubscriptionCodeKey_DMG && product_code != KMAdvancedPermanentCodeKey_DMG {
                 return false
            }
        }
        return true
    }
    
    private func getProductID() -> String {
        return GetHardwareUUID()!
    }
        
    private func isNumeric(_ text: String) -> Bool {
        return !text.isEmpty && text.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
    }
    
    private func openWebView(_ urlPath: String) -> Void {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            
            self.pollCount = 0
            self.startPolling()
            self.embeddedPaymentPopWC = KMEmbeddedPaymentPopWC.currentFirstTrialWC(urlPath)
            if self.paymentMethod == .paddle {
                self.embeddedPaymentPopWC?.isPaddle = true
                self.embeddedPaymentPopWC?.countryCode = self.countryAbbreviationValues[self.paddlePopUpButton.indexOfSelectedItem]
                self.embeddedPaymentPopWC?.postCode = self.paddleTextField.stringValue
            }
            self.embeddedPaymentPopWC?.showWindow(nil)
            self.embeddedPaymentPopWC?.callback = { isClose in
            }
        }
    }
    
    private func convertBase64StringToNSImage(base64String: String) -> NSImage? {
        let sepS = "data:image/png;base64,"
        guard let baseStr = base64String.components(separatedBy: sepS).last else {
            return nil
        }
        if let data = Data(base64Encoded: baseStr) {
            return NSImage(data: data)
        }
        return nil
    }
    
    private func scanCode(_ urlPath: String) -> Void {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.payBox.contentView = self.payResult
            self.payBoxHeight.constant = 262
            if self.paymentMethod == .wxpay {
                self.scanLabel.stringValue = NSLocalizedString("Scan QR Code with WeChat", comment: "")
                self.payTypeImageView.image = NSImage(named: "EmbeddedPayment27")
            } else if self.paymentMethod == .alipay {
                self.scanLabel.stringValue = NSLocalizedString("Scan QR Code with Alipay", comment: "")
                self.payTypeImageView.image = NSImage(named: "EmbeddedPayment28")
            }
            let img = self.convertBase64StringToNSImage(base64String: urlPath)

            self.qrCodeImageView.image = img
            
            self.pollCount = 0
            self.startPolling()
        }
    }
    
    private func pollingResultNew() -> Void { //刷新订单状态
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
            guard let self = self else { return }
            if self.orderID == "" { return }
            KMMemberCenterManager.manager.getStateByOrderId(orderId: self.orderID) { success, info in
                self.startPolling()
                
                if (success) {
                    let dic: NSDictionary = info ?? [:]
                    let requestDic: NSDictionary = dic["result"] as? NSDictionary ?? [:]
                    let status:String = requestDic["status"]  as? String ?? ""
                    if(status.uppercased() == "COMPLETED") {
                        KMUserInfoVCModel().refreshUserInfo { success, msg,dic  in
                            DispatchQueue.main.async {
#if VERSION_DMG
#else
                                KMCheckInManager.default.checkIn(refreshData: true, callback: nil)
#endif
                                NotificationCenter.default.post(name: NSNotification.Name.KMMemberInfoChange, object: self)
                                
                                KMCancelSubscribeSuccessWindowController.shared.saveRecord()
                                
                                self._trackPurchaseCampaignEvent()
                            }
                        }
                        
                        KMMemberCenterManager.judgeTrailCancel { success, resultModel, error in
                            if success {
                                KMCheckInManager.default.trailCancel = resultModel?.result ?? false
                            }
                        }
                        
                        self.stopPolling()
                        
                        self.close()
                        
                        DispatchQueue.main.async {
                            KMPurchaseSuccessWindowController.shared.showWindow(nil)
                            KMPurchaseSuccessWindowController.shared.closeCallback = { [weak self] (isClose: Bool) -> Void in
//                                guard let self = self else { return }
#if VERSION_DMG
                                KMCheckInManager.default.checkIn(refreshData: true, callback: nil)
#else
#endif
                            }
                        }
                    }
                }
            }
        }
    }
    
    private func startPolling() {
        timer = Timer(timeInterval: interval, repeats: false) { [weak self] _ in
            guard let self = self else { return }
            self.performTask()
        }
        RunLoop.main.add(timer!, forMode: .common)
    }

    @objc private func performTask() {
        guard pollCount < maxPolls else {
            timer?.invalidate()
            timer = nil
            return
        }
        
        // 执行你的轮询任务
        print("Performing polling task \(pollCount + 1)/\(maxPolls)")
        
        pollCount += 1
        pollingResultNew()
    }
    
    private func stopPolling() {
        timer?.invalidate()
        timer = nil
        pollCount = 0
    }
    
    private func emailErrorLabel(isReveal: Bool) {
        errorView.isHidden = !isReveal
        errorLabelTopLayout.constant = errorView.isHidden ? -CGRectGetHeight(errorView.bounds) : 4
    }
    
    private func refreshApplyButton(isReveal: Bool) {
        self.applyButton.isEnabled = isReveal
    }
    
    private func refreshLicenseCodeView(isReveal: Bool) {
    }
    
    private func refreshLicenseCodeErrorView(isReveal: Bool) {
    }
    
    private func refreshCouponError(isReveal: Bool) {
        coupomErrorLabel.isHidden = !isReveal
        coupomErrorTopLayout.constant = coupomErrorLabel.isHidden ? -CGRectGetHeight(coupomErrorLabel.bounds) : 8.0
    }
    
    private func _applyDiscount(_ codeId: String, callback:((_ success: Bool, _ result: KMMemberProductResult?)->Void)?) {
        if codeId == "" {
            callback?(false, nil)
            return
        }
        
        if KMMemberCenterManager.manager.isConnectionAvailable() == false {
            callback?(false, nil)
            return
        }
        
        self.refreshCouponError(isReveal: false)
        applyButton.isEnabled = false
        coupomTextField.isEnabled = false
        
        window?.showWaitingView()
        KMMemberCenterManager.manager.checkCoupon(productId: product_Info.id, userId: KMMemberInfo.shared.userID, code: codeId) {[weak self] success, result in
            self?.window?.hideWaitingView()
            
            KMMainThreadExecute {
                callback?(success, result)
            }
        }
    }
    
    var activityAlertViewController: KMActivityALertViewController? {
        if _activityAlertViewController == nil {
            let blockSelf = self
            _activityAlertViewController = KMActivityALertViewController()
            _activityAlertViewController?.callback = {
                blockSelf.close()
            }
        }
        return _activityAlertViewController
    }

}

extension KMPurchaseEmbeddedWindowController: NSTextFieldDelegate {
    func controlTextDidEndEditing(_ obj: Notification) {
        let textField = obj.object as? NSTextField
        if textField == amountTextField1 {
            if !isNumeric(textField!.stringValue) {
                if textField == amountTextField1 { textField?.stringValue = String(pdfCount) }
            } else {
                if textField == amountTextField1 {
                    pdfCount = Int(textField!.stringValue) ?? 1
                    if Int(textField!.stringValue)! > 9999 {
                        pdfCount = 9999
                        textField?.stringValue = String(pdfCount)
                    } else if Int(textField!.stringValue)! < 1 {
                        pdfCount = 1
                        textField?.stringValue = String(pdfCount)
                    }
                }
                if pdfCount > 100 {
                    wechatPayButton2.isHidden = false
                    cardButton.isHidden = true
                    wechatPayButton.isHidden = true
                    if _paymentMethod == .paddle {
                        paymentMethod = .paypal
                    }
                } else {
                    wechatPayButton2.isHidden = true
//                    cardButton.isHidden = false
                    wechatPayButton.isHidden = false
                }
            }
        } else if textField == emailTextField {
            emailErrorLabel(isReveal: false)
        } else if textField == paddleTextField {
            
        }
    }
    
    func controlTextDidChange(_ obj: Notification) {
        let textField = obj.object as? NSTextField
        if textField == amountTextField1 {
            if !isNumeric(textField!.stringValue) {
                if textField == amountTextField1 { textField?.stringValue = String(pdfCount) }
            } else {
                if Int(textField!.stringValue)! > 9999 {
                    textField?.stringValue = String(pdfCount)
                } else if Int(textField!.stringValue)! < 1 {
                    textField?.stringValue = String(pdfCount)
                }
            }
        }
    }
}

extension KMPurchaseEmbeddedWindowController: NSWindowDelegate {
    func windowWillClose(_ notification: Notification) {
        if let data = self.window?.isEqual(to: notification.object), data {
            // 窗口关闭,关闭轮询
            stopPolling()
        }
        if self.embeddedPaymentPopWC != nil {
            self.embeddedPaymentPopWC?.close()
            self.embeddedPaymentPopWC = nil
        }
        KMPurchaseEmbeddedWindowController.currentWindowController = nil
    }
}
#endif