//
//  HomeNoAdsViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/7.
//

import UIKit
import StoreKit

class HomeNoAdsViewController: UIViewController, NoAdsStackDataSource {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        HomePayModel.share.storeCall = {[weak self] products in
            guard let self = self ,
                    let p1 = products.first,
                    let p2 = products.last
            else { return }
            self.yearNorBtn.setTitles(["\(p1!.localizedPrice)/year, cancel anytime" , "3-day FREE TRIAL"])
            self.forever.setTitles(["\(p2!.localizedPrice), Lifetime"])
        }
    }
    
    private var doneBlock:(()->Void) = {}
    
    var type = 0 {
        didSet {
            setIsSelect()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        HomePayModel.share.fetchProducts()
        setUI()
    }
    
    
    private lazy var stack:NoAdsStackView  = {
        let s = NoAdsStackView(3)
        contentScroll.addSubview(s)
        s.spacing = 3
        s.dataSource = self
        return s
    }()
    
    private lazy var scroll: UIScrollView = {
        let scroll = UIScrollView()
        contentScroll.addSubview(scroll)
        scroll.delegate = self;
        scroll.backgroundColor = .colorWithHex(hexStr: "#F2F6FC")
        scroll.layer.cornerRadius = 12
        scroll.showsHorizontalScrollIndicator = false
        scroll.isPagingEnabled = true
        scroll.clipsToBounds = true
        return scroll
    }()
    
    private lazy var stack1:NoAdsStackView  = {
        let s = NoAdsStackView(descp.count)
        scroll.addSubview(s)
        s.axis = .horizontal
        s.spacing = 0
        s.distribution = .fillEqually
        s.dataSource = self
        return s
    }()
    
    private lazy var NoAdTitle: UILabel = {
        let no = UILabel()
        no.text = "Unlock all usage permissions"
        no.font = UIFont.boldSystemFont(ofSize: 18)
        no.textAlignment = .center
        no.numberOfLines = 0
        no.textColor = .white
        view.addSubview(no)
        return no
    }()
    
    private lazy var info: UIImageView = {
        let info = UIImageView(image: UIImage(named: "img_pro_quanxian"))
        info.contentMode = .scaleToFill
        view.addSubview(info)
        return info
    }()
    
    private lazy var topBackimg: UIImageView = {
        let img = UIImageView(image: UIImage(named: "img_bj_quanxian"))
        img.contentMode = .scaleToFill
        view.addSubview(img)
        return img
    }()
    
    private lazy var closeBtn: UIButton = {
        let close = UIButton(type: .custom)
        close.setImage(UIImage(named: "icon_close__pingfen_pop"), for: .normal)
        view.addSubview(close)
        close.addTarget(self, action: #selector(closeTouch), for: .touchUpInside)
        return close
    }()
    
    private lazy var pageCtrol: PMPageControl = {
        let page = PMPageControl()
        page.currentPageIndicatorTintColor = .colorWithHex(hexStr: "#0082FF")
        page.pageIndicatorTintColor = .colorWithHex(hexStr: "#C6CEE0")
        page.numberOfPages = 3
        contentScroll.addSubview(page)
        return page
    }()
    
    private lazy var contentScroll: UIScrollView = {
        let scroll = UIScrollView()
        scroll.backgroundColor = .clear
        scroll.showsHorizontalScrollIndicator = false
        scroll.showsVerticalScrollIndicator = false
        scroll.clipsToBounds = true
        view.addSubview(scroll)
        return scroll
    }()
    
    
    private lazy var buybut: UIButton = {
        let buy = UIButton(type: .custom)
        buy.backgroundColor = UIColor.colorWithHex(hexStr: "#0082FF")
        buy.setTitle("Start my 3-day free trial", for: .normal)
        contentScroll.addSubview(buy)
        buy.addTarget(self, action: #selector(paypuase), for: .touchUpInside)
        return buy
    }()
    
    private lazy var yearNorBtn: PMButton = {
        let btn = PMButton(type: .custom)
        btn.buttonStyleType = .ButtonStyleTypeDiamond
        btn.backgroundColor = .colorWithHex(hexStr: "#F2F6FC")
        btn.setTitles(["3 days free trial",""])
        btn.addTarget(self, action: #selector(TheFrial), for: .touchUpInside)
        contentScroll.addSubview(btn)
        return btn
    }()
    
    private lazy var forever: PMButton = {
        let fever = PMButton(type: .custom)
        fever.setTitles([""])
        fever.backgroundColor = .colorWithHex(hexStr: "#F2F6FC")
        fever.addTarget(self, action: #selector(FreeTrial), for: .touchUpInside)
        contentScroll.addSubview(fever)
        return fever
    }()
    
    private lazy var ppBtn:UIButton = {
        
        let sview:UIButton = UIButton()
        let content:String = "Terms"
        let font = UIFont.systemFont(ofSize: 12.RW(), weight: .medium)
        let color = UIColor.colorWithHex(hexStr: black6Color)
        
        sview.setTitle(content, for: .normal)
        sview.setTitleColor(color, for: .normal)
        sview.titleLabel?.font = font
        sview.isSelected = false;
        sview.sizeToFit()
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .foregroundColor: color,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
        let attributedString = NSAttributedString(string: content, attributes: attributes)
        sview.setAttributedTitle(attributedString, for: .normal)
        sview.addTarget(self, action: #selector(terms(_:)), for: .touchUpInside)
        sview.sizeToFit()
        contentScroll.addSubview(sview)
        return sview
    }()
    
    private lazy var restoreBtn:UIButton = {
        
        let sview:UIButton = UIButton()
        let content:String = "Restore"
        let font = UIFont.systemFont(ofSize: 12.RW(), weight: .medium)
        let color = UIColor.colorWithHex(hexStr: black6Color)
        
        sview.setTitle(content, for: .normal)
        sview.setTitleColor(color, for: .normal)
        sview.titleLabel?.font = font
        sview.sizeToFit()
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font,
            .foregroundColor: color,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
        let attributedString = NSAttributedString(string: content, attributes: attributes)
        sview.setAttributedTitle(attributedString, for: .normal)
        sview.addTarget(self, action: #selector(restore), for: .touchUpInside)
        sview.sizeToFit()
        contentScroll.addSubview(sview)
        return sview
    }()
    
    private lazy var privavye_Label: UILabel = {
        let priva = UILabel()
        priva.font = UIFont.systemFont(ofSize: 14)
        priva.textColor = .gray
        priva.text = ""
        priva.numberOfLines = 0
        priva.clipsToBounds = true
        priva.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(labelTapped(_:)))
        priva.addGestureRecognizer(tap)
        contentScroll.addSubview(priva)
        return priva
    }()
    
    
    @objc private func labelTapped(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: privavye_Label)
        let strs:NSString = "privacy policy"
        let frssss = strs.boundingRect(with: CGSizeMake(.infinity, .infinity), options: .truncatesLastVisibleLine, attributes: [NSAttributedString.Key.font : privavye_Label.font], context: nil)
        let frame1 = CGRectMake(0, privavye_Label.height-25, CGRectGetWidth(frssss), 25)
        let frame2 = CGRectMake(CGRectGetWidth(frssss)+20, privavye_Label.height-25, 90, 25)
        if frame1.contains(location) {
            Print("点击了隐私")
            let vc:PrivacyPolicyWebViewController = PrivacyPolicyWebViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }else if frame2.contains(location){
            Print("点击了terms")
            let vc:TermOfUseWebViewController = TermOfUseWebViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }

    
    private let data:[[String:String]] = [
        ["icon":"ic_unsel_com","t":"Intelligent cleaning of similar photos"],
        ["icon":"ic_unsel_com","t":"Unlimited usage times"],
        ["icon":"ic_unsel_com","t":"A more private space"],
    ]
    
    private var descp:[ReviewModel] {
        get {
            let dict = [
                ["descp":"That is great! Scan, remove similar photos, and compress videos. Simple and effective. Don't worry about the storage space decreasing",
                 "name":"Angelina",
                 "review":(4),
                 "title":"Just use it to clean your phone!"
                ],
                ["descp":"I have tried so many times to clean up storage on myphone but it always takes forever and never seems to beenough. This app has made it so much easier and faster",
                 "name":"Forever",
                 "review":(5),
                 "title":"Very practical!"
                ],["descp":"Thank goodness, all the storage space I use is slow.. I'm afraid of browsing and deleting unusable videos and photos, which makes things so simple",
                   "name":"Mary",
                   "review":(5),
                   "title":"I love it!"]]
            do{
                let data = try JSONSerialization.data(withJSONObject: dict)
                return try JSONDecoder().decode([ReviewModel].self, from: data)
            }catch{
                return []
            }
            
        }
    }
}

struct ReviewModel:Codable {
    let title:String
    let name:String
    let review:Int
    let descp:String
}

extension HomeNoAdsViewController : UIScrollViewDelegate {
    
    private func setIsSelect() -> Void {
        yearNorBtn.isSelect = type == 0
        forever.isSelect = type == 1
        buybut.setTitle(type == 0 ? "Start my 3-day free trial" : "Start Planning", for: .normal)
    }
    
    /** 包年 */
    @objc func TheFrial() -> Void {
        type = 0
    }
    
    /** 终身会员 */
    @objc func FreeTrial() -> Void {
        type = 1
    }
    
    @objc func paypuase() -> Void {
        HomePayModel.share.purchase((type == 0) ? .Subscribe : .NonConsum )
    }
    
    @objc func restore() -> Void {
        HomePayModel.share.restore()
    }
    
    @objc func terms(_ sender:UIButton) -> Void {
        DispatchQueue.main.async {[weak self] in
            guard let self else {return}
            sender.isSelected = !sender.isSelected
            
            let strs:NSString = sender.isSelected ? "We offer 1-year and lifetime subscriptions. The price is clearly displayed within the application.\n\n·After the purchase confirmation, your iTunes account will be charged.\n\n·Unless the automatic update is turned off at least 24 hours before the end of the current cycle, the subscription will be automatically updated.\n\n·Your account will be renewed within 24 hours before the end of the current cycle cost.\n\n·You can go to the \"Account Settings\" in the iTunes store to manage your subscriptions and turn off auto renewal.\n\n·If provided, if you choose to use our free trial version, any unused portion during the free trial period will become invalid when you purchase a publication subscription, if applicable.\n\n·If you choose not to purchase the AI PhoneManager Pro version, you can continue to use it for free and enjoy PhoneManager.\n\nYour personal data is securely stored in PhoneManager, please make sure to read our \nprivacy policy and terms of use." : ""
            
            let attribtit = NSMutableAttributedString(string:strs as String , attributes: [:])
            if strs.length > 3 {
                let rang = strs.range(of: "privacy policy")
                attribtit.addAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14),NSAttributedString.Key.underlineStyle:NSUnderlineStyle.single.rawValue,.link:"appscheme://private"], range: rang)
                let rang1 = strs.range(of: "terms of use")
                attribtit.addAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14),NSAttributedString.Key.underlineStyle:NSUnderlineStyle.single.rawValue,.link:"appscheme://terms"], range: rang1)
            }
            
            privavye_Label.attributedText = attribtit
            self.view.layoutIfNeeded()
            DispatchQueue.main.async {
                let height = CGRectGetMaxY(self.privavye_Label.frame)
                self.contentScroll.contentSize = CGSize(width: 0, height: height + 30)
                if self.privavye_Label.attributedText?.length ?? 0 > 10 {
                    UIView.animate(withDuration: 0.1) {
                        self.contentScroll.contentOffset = CGPoint(x: 0, y: self.contentScroll.contentSize.height - self.contentScroll.height)
                    }
                }
            }
        }
    }
    
    func NoAdsStactChildView(_ content: NoAdsStackView, _ idx: Int) -> UIView {
        if content == stack {
            let stackview = UIStackView()
            stackview.axis = .horizontal
            stackview.spacing = 10
            stackview.alignment = .center
            stackview.distribution = .fillProportionally
            let dict = data[idx]
            let icon = UIImageView(image: UIImage(named: dict["icon"] ?? ""))
            stackview.addArrangedSubview(icon)
            icon.snp.makeConstraints { make in
                make.height.equalTo(36)
                make.width.equalTo(icon.snp.height)
            }
            let descp = UILabel()
            descp.text = dict["t"]
            descp.textColor = .black
            descp.font = UIFont.boldSystemFont(ofSize: 16)
            stackview.addArrangedSubview(descp)
            return stackview
        }else if content == stack1 {
            let content = UIView()
            content.backgroundColor = .clear
            
            let t = UILabel()
            t.text = descp[idx].title
            t.textColor = .colorWithHex(hexStr: "#333333")
            t.font = UIFont.boldSystemFont(ofSize: 14)
            content.addSubview(t)
            t.snp.makeConstraints { make in
                make.left.top.equalToSuperview().inset(16)
            }
            let r = UILabel()
            r.text = descp[idx].name
            r.textColor = .colorWithHex(hexStr: "#666666")
            r.font = UIFont.systemFont(ofSize: 14)
            content.addSubview(r)
            r.snp.makeConstraints { make in
                make.right.top.equalToSuperview().inset(16)
            }
            
            let staridx = descp[idx].review
            let star = yQzSnStarView()
            star.currentStar = staridx
            content.addSubview(star)
            star.snp.makeConstraints { make in
                make.left.equalTo(t)
                make.top.equalTo(t.snp.bottom).offset(5)
            }
            
            let label = UILabel()
            label.text = descp[idx].descp
            label.textAlignment = .left
            label.numberOfLines = 2
            label.textColor = .colorWithHex(hexStr: "#333333")
            label.font = UIFont.systemFont(ofSize: 12)
            content.addSubview(label)
            label.snp.makeConstraints { make in
                make.top.equalTo(star.snp.bottom).offset(5)
                make.left.right.bottom.equalToSuperview().inset(16)
            }
            return content
        }else{
            return UIView()
        }
    }
    
    private func setUI() -> Void {
        topBackimg.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(topBackimg.snp.width).multipliedBy(182.0/375.0)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.left.equalTo(view).inset(UIEdgeInsets(top: 35, left: 13, bottom: 0, right: 0))
            make.top.equalTo(view.snp.topMargin).offset(15)
        }
        NoAdTitle.snp.makeConstraints { make in
            make.centerX.equalToSuperview().inset(20)
            make.centerY.equalTo(closeBtn.snp.centerY)
        }
        
        info.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(topBackimg.snp.bottom).offset(-30)
        }
        
        contentScroll.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(info.snp.bottom).offset(7)
        }
        
        stack.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(36)
            make.width.equalTo(contentScroll.snp.width).offset(-36*2.0)
            make.top.equalTo(contentScroll.snp.top)
        }
        
        scroll.snp.makeConstraints { make in
            make.left.right.equalTo(stack)
            make.top.equalTo(stack.snp.bottom).offset(25)
            make.height.equalTo(110)
        }
        stack1.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.height.equalTo(scroll.snp.height)
            make.width.equalTo(scroll.snp.width).multipliedBy(3.0)
        }
        pageCtrol.snp.makeConstraints { make in
            make.centerX.equalTo(stack)
            make.top.equalTo(stack1.snp.bottom).offset(15)
        }
        
        yearNorBtn.snp.makeConstraints { make in
            make.left.right.equalTo(stack)
            make.top.equalTo(pageCtrol.snp.bottom).offset(10)
            make.height.equalTo(65)
        }
       
        forever.snp.makeConstraints { make in
            make.left.right.equalTo(stack)
            make.top.equalTo(yearNorBtn.snp.bottom).offset(10)
            make.height.equalTo(65)
        }
        buybut.snp.makeConstraints { make in
            make.left.right.equalTo(stack)
            make.top.equalTo(forever.snp.bottom).offset(20)
            make.height.equalTo(65)
        }
        ppBtn.snp.makeConstraints { make in
            make.top.equalTo(buybut.snp.bottom).offset(10)
            make.left.equalTo(buybut)
        }
        restoreBtn.snp.makeConstraints { make in
            make.centerY.equalTo(ppBtn)
            make.right.equalTo(buybut.snp.right)
        }
        privavye_Label.snp.makeConstraints { make in
            make.left.equalTo(ppBtn.snp.left)
            make.right.equalTo(restoreBtn.snp.right)
            make.top.equalTo(ppBtn.snp.bottom).offset(15)
        }

        self.type = 0
        self.view.layoutIfNeeded()
        DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
            self.buybut.layer.cornerRadius = CGRectGetHeight(self.buybut.frame) / 2.0
            self.scroll.contentSize = CGSize(width: CGRectGetWidth(self.scroll.frame) * 3.0, height: 0)
            let height = CGRectGetMaxY(self.privavye_Label.frame)
            self.contentScroll.contentSize = CGSize(width: 0, height: height + 30)
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let width = scrollView.width
        let offset = scrollView.contentOffset.x
        let idx = ceil(offset / width)
        self.pageCtrol.currentPage = Int(idx)
    }
    
    @objc private func closeTouch() -> Void {
        self.dismiss(animated: true)
        doneBlock()
    }
    
    class func show(_ compate:@escaping(()->Void) ) -> Void {
        let vc = HomeNoAdsViewController()
        vc.doneBlock = compate
        let nav:BaseNavViewController = BaseNavViewController(rootViewController: vc)
        nav.modalPresentationStyle = .overFullScreen
        guard let root = UIViewController.topMostViewController() else { return }
        root.present(nav, animated: true)
    }
}


class BackgroundTaskManager {
    
    static let share = BackgroundTaskManager()
    
    private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid
    
    func startTask() {
        backgroundTaskID = UIApplication.shared.beginBackgroundTask { [weak self] in
            self?.endTask() // 超时强制终止
        }
    }
    
    func endTask() {
        guard backgroundTaskID != .invalid else { return }
        UIApplication.shared.endBackgroundTask(backgroundTaskID)
        backgroundTaskID = .invalid
    }
}
