//
//  HomePayView.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/20.
//

import UIKit
import StoreKit
import SVProgressHUD



class HomePayViewController:UIViewController {
    
    private var homePayView:HomePayView?
    private var disjunctor = false
    
    private var doneBlock:(()->Void) = {}
    
    var currentProduct:[SKProduct?]? {
        didSet {
            setPrice()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        addViews()
        storeKeD()
        scroll.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
    }

    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
       // homePayView?.playAnimationWithDelay()
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        doneBlock()
    }
    lazy var scroll: UIScrollView = {
        let scroll = UIScrollView()
        scroll.backgroundColor = .clear
        scroll.contentInsetAdjustmentBehavior = .never
        view.addSubview(scroll)
        return scroll
    }()
    
    private func addViews() {
        homePayView = HomePayView(frame: view.bounds)
        scroll.addSubview(homePayView!)
        homePayView?.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.equalTo(scroll.snp.width)
        }
        homePayView?.callBack = {[weak self] status in
            guard let self else {return}
            
            if let operstatus = status as? OperStatus {
                switch operstatus {
                case .close:
                    self.dismiss(animated: true)
//                    doneBlock()
                default:
                    break
                }
            }
            
            if let commonPush = status as? CommonPush {
                switch commonPush {
                case .pp:
                    self.ppClick()
                case .tou:
                    self.touClick()
                case .pay:
                    self.payTouch()
                    break
                case .swit:
                    break
                case .restore:
                    self.restoreClick()
                    break
                case .change:
                    DispatchQueue.main.async {
                        let contentSize = CGRectGetHeight(self.homePayView?.frame ?? CGRect())
                        self.scroll.contentSize = CGSizeMake(0, contentSize + (cWindow?.safeAreaInsets.bottom ?? 20) + 5)
                        if self.homePayView?.privavye_Label.attributedText?.length ?? 0 > 10 {
                            UIView.animate(withDuration: 0.1) {
                                self.scroll.contentOffset = CGPoint(x: 0, y: self.scroll.contentSize.height - self.scroll.height)
                            }
                        }
                    }
                    break
                }
            }
        }
    }
}


extension HomePayViewController {
    
    private func setPrice() -> Void {
//        guard currentProduct != nil ,
//              let p1 = currentProduct?.first,
//              let p2 = currentProduct?.last
//        else { return }
//        homePayView?.reloadSKPorduct(product: p1, product1: p2)
    }
    
    private func storeKeD() -> Void {
//        HomePayModel.share.storeCall = {[weak self] products in
//            guard let self = self else { return }
//            self.currentProduct = products
//        }
        
        IAPManager.share.fetchProducts { [weak self] products in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                if let (weekProduct, lifetimeProduct,_) = products {
                    weakSelf.homePayView?.reloadSKPorduct(week: weekProduct, life: lifetimeProduct)
                }
            }
        }
    }
    
    private func payTouch() -> Void {
        let subscribe:PayState = homePayView?.type == 0 ? .weekSubscribe : .nonConsumable
        IAPManager.share.purchase(subscribe) {[weak self] result in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let success):
                Print("内购成功",success)
                APIReportManager.shared.startReport(type: .apple_billing_success, ext: ["productId":subscribe.productId,"from":IAPManager.share.currentVCName])
                DispatchQueue.main.async {
                    SVProgressHUD.showSuccess(withStatus: "purchase succeeds")
                    weakSelf.dismiss(animated: true)
                }
            case .failure(let failure):
                Print("内购失败",failure)
                APIReportManager.shared.startReport(type: .apple_billing_error, ext: ["productId":subscribe.productId,"info":failure.localizedDescription,"from":IAPManager.share.currentVCName])
                DispatchQueue.main.async {
                    SVProgressHUD.showError(withStatus: failure.localizedDescription)
                }
                
            }
        }
    }
    
    private func ppClick() {
        DispatchQueue.main.async {[weak self] in
            guard let self else {return}
            let vc:PrivacyPolicyWebViewController = PrivacyPolicyWebViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    private func touClick() {
        DispatchQueue.main.async {[weak self] in
            guard let self else {return}
            let vc:TermOfUseWebViewController = TermOfUseWebViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    private func restoreClick() {
      //  HomePayModel.share.restore()
        IAPManager.share.restore { result in
            
        }
    }
    
    class func show( _ compate:@escaping(()->Void)) -> Void {
        let vc:HomePayViewController = HomePayViewController()
        vc.doneBlock = compate
        let nav:BaseNavViewController = BaseNavViewController(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        guard let rt = UIViewController.topMostViewController() else { return }
       // Print(rt.class)
        let className = NSStringFromClass(type(of: rt))
        IAPManager.share.currentVCName = className
        rt.present(nav, animated: true)
    }
    
    
}
