//
//  SettingVieController.swift
//  PhoneManager
//
//  Created by edy on 2025/3/28.
//

import Foundation

class SettingViewController : BaseViewController , UITableViewDelegate, UITableViewDataSource{
    
    var modelData: [SettingModel]?

    lazy var tableView : UITableView = {
        let cY =  titleView.height + titleView.y
        let tableView:UITableView = UITableView.init(frame: CGRect(x: 0, y: cY, width: view.width, height: view.height - cY) , style: UITableView.Style.grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self

        tableView.register(SettingViewHeaderCell.classForCoder(), forCellReuseIdentifier: "SettingViewHeaderCell")
        tableView.register(SettingNormalCell.classForCoder(), forCellReuseIdentifier: "SettingNormalCell")
        tableView.register(SettingSwitchCell.classForCoder(), forCellReuseIdentifier: "SettingSwitchCell")
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        self.titleView.titleLabel.text = "Settings"
        self.titleView.titleLabel.textAlignment = .left
        self.titleView.titleLabel.font = UIFont(name: "PingFang SC-Bold", size: 20)
        self.titleView.titleLabel.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        modelData = getSettingViewInfo()
        self.view.addSubview(tableView)
        self.tableView.reloadData()
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model : SettingModel = modelData![section]
        return model.rowInfo.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell : SettingViewHeaderCell = tableView.dequeueReusableCell(withIdentifier: "SettingViewHeaderCell",for: indexPath) as! SettingViewHeaderCell
            if IAPManager.share.isSubscribed == false {
//                cell.basic.duration = 1.5
//                cell.preButtonImageView.startAnimating()
            }
            return cell
        }else{
            let model : SettingModel = modelData![indexPath.section]
            let detailModel : RowInfoModel = model.rowInfo[indexPath.row]
            if detailModel.isSwitch {
                let cell : SettingSwitchCell  = tableView.dequeueReusableCell(withIdentifier: "SettingSwitchCell",for: indexPath) as! SettingSwitchCell
                cell.data = detailModel
                DispatchQueue.main.async {
                    let rowNum = tableView.numberOfRows(inSection: indexPath.section)
                    cell.layer.mask = nil
                    cell.lineView.isHidden = false
                    if rowNum == 1 {
                        cell.cornerCut(radius: 12, corner: UIRectCorner(rawValue: (UIRectCorner.bottomLeft.rawValue)|(UIRectCorner.bottomRight.rawValue)|(UIRectCorner.topLeft.rawValue)|(UIRectCorner.topRight.rawValue)))
                        cell.lineView.isHidden = true
                    }else{
                        if indexPath.row == 0 {
                            cell.cornerCut(radius: 12, corner: UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue)|(UIRectCorner.topRight.rawValue)))
                        }
                        if (indexPath.row == rowNum - 1){
                            cell.lineView.isHidden = true
                            cell.cornerCut(radius: 12,corner: UIRectCorner(rawValue: (UIRectCorner.bottomLeft.rawValue)|(UIRectCorner.bottomRight.rawValue)))
                        }
                    }
                }
                return cell
            }else{
                let cell : SettingNormalCell  = tableView.dequeueReusableCell(withIdentifier: "SettingNormalCell",for: indexPath) as! SettingNormalCell
                cell.logoView.image = UIImage(named: detailModel.imageName)
                
                if detailModel.title == settingLabels.Email.rawValue {
                    cell.fLabel.text = PMEmailManager.shareManager.loginUser != nil ? "Sign out" : detailModel.title
                }else{
                    cell.fLabel.text = detailModel.title
                }
                DispatchQueue.main.async {
                    let rowNum = tableView.numberOfRows(inSection: indexPath.section)
                    cell.layer.mask = nil
                    cell.lineView.isHidden = false
                    if rowNum == 1 {
                        cell.cornerCut(radius: 12, corner: UIRectCorner(rawValue: (UIRectCorner.bottomLeft.rawValue)|(UIRectCorner.bottomRight.rawValue)|(UIRectCorner.topLeft.rawValue)|(UIRectCorner.topRight.rawValue)))
                        cell.lineView.isHidden = true
                    }else{
                        if indexPath.row == 0 {
                            cell.cornerCut(radius: 12, corner: UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue)|(UIRectCorner.topRight.rawValue)))
                        }
                        if (indexPath.row == rowNum - 1){
                            cell.lineView.isHidden = true
                            cell.cornerCut(radius: 12,corner: UIRectCorner(rawValue: (UIRectCorner.bottomLeft.rawValue)|(UIRectCorner.bottomRight.rawValue)))
                        }
                    }
                }
                return cell
            }
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return modelData!.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 0
        }
        return 49
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.frame = CGRect(x: 0, y: 0, width: view.width, height: 49)
        view.backgroundColor = .clear
        let titleLabel = UILabel()
        titleLabel.text = modelData![section].sectionTitle
        titleLabel.font = UIFont(name: "PingFang SC-Bold", size: 12)
        titleLabel.textColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
        titleLabel.frame = CGRect(x: 15, y: 20, width: 345, height: 17)
        view.addSubview(titleLabel)
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if IAPManager.share.isSubscribed == false {
                return 385
            }else{
                return 339
            }
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model : SettingModel = modelData![indexPath.section]
        let detailModel : RowInfoModel = model.rowInfo[indexPath.row]
        
        switch detailModel.title {
        case settingLabels.Email.rawValue:
            emailLoginSignOut(indexPath)
            break
        case settingLabels.UsePIN.rawValue:
            
            secretspace()
            vibrate()
            break
        case settingLabels.UseFaceID.rawValue:
            SetFaceID(indexPath)
            vibrate()
            break
        case settingLabels.ChangePIN.rawValue:
            changePIN()
            break
        case settingLabels.RemoveAfterImport.rawValue:
            SettingConfiguration.share.config.removeImg = !SettingConfiguration.share.config.removeImg
            let cell:SettingSwitchCell = tableView.cellForRow(at: indexPath) as? SettingSwitchCell ?? SettingSwitchCell()
            cell.openImageView.isSelected = SettingConfiguration.share.config.removeImg

            vibrate()
            break
        case settingLabels.Widgets.rawValue:
//            let callblock:(()->Void) = {[weak self] in
//                guard let self = self else { return }
//                let widget = WidgetViewController()
//                self.navigationController?.pushViewController(widget, animated: true)
//            }
//            if IAPManager.share.isSubscribed == false {
////                AdvManager.shared.showInterstitialAd(vc: self,from: "Widgets")
////                let widget = WidgetViewController()
////                self.navigationController?.pushViewController(widget, animated: true)
//            }else{
//                callblock()
//            }
//            AdvManager.shared.finisedCallBack = {
//                callblock()
//            }
            if IAPManager.share.isSubscribed == false {
                //AdvManager.shared.showInterstitialAd(vc: self,from: "Widgets")
                ADManager.shared.showInterstitialAd(from: ADShowTypeEnum.Widgets.name) {[weak self] in
                    guard let self = self else { return }
                    let widget = WidgetViewController()
                    self.navigationController?.pushViewController(widget, animated: true)
                } showFailBlock: {[weak self] _ in
                    guard let self = self else { return }
                    let widget = WidgetViewController()
                    self.navigationController?.pushViewController(widget, animated: true)
                }

            }else{
                let widget = WidgetViewController()
                self.navigationController?.pushViewController(widget, animated: true)
            }
            break
        case settingLabels.FollowonInstagram.rawValue:
            guard let url = URL(string: "https://www.instagram.com/phone.manager.app/") else { return }
            UIApplication.shared.open(url)
            break
        case settingLabels.RateUs.rawValue:
            self.review()
            break
        case settingLabels.ShareUs.rawValue:
            self.Share()
            break
        case settingLabels.Hint.rawValue:
            let hint = PMHintsController()
            self.navigationController?.pushViewController(hint, animated: true)
            break
        case settingLabels.KeepList.rawValue:
            let vc = MaintainViewListController()
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case settingLabels.Vibration.rawValue:
            SettingConfiguration.share.config.vibration = !(SettingConfiguration.share.config.vibration ?? false)
            let cell:SettingSwitchCell = tableView.cellForRow(at: indexPath) as? SettingSwitchCell ?? SettingSwitchCell()
            cell.openImageView.isSelected = SettingConfiguration.share.config.vibration ?? false
            vibrate(true)
            break
        case settingLabels.Resumepurchase.rawValue:
            break
            
        case settingLabels.EmailSupport.rawValue:
            let emailSupport = PMEmailSupportController()
            self.navigationController?.pushViewController(emailSupport, animated: true)
            break
            
        case settingLabels.FAQ.rawValue:
            let faq = PMFAQController()
            self.navigationController?.pushViewController(faq, animated: true)
            break
        case settingLabels.AboutUs.rawValue:
            let AboutUs = PMAboutUsController()
            self.navigationController?.pushViewController(AboutUs, animated: true)
            break
        case settingLabels.PrivacyPolicy.rawValue:
            jumpWeb(detailModel.title)
            break
        default:
            break
        }
    }
    
    // MARK: - 隐私空间PIN
    private func secretspace() -> Void {
        let seting = SecretSetViewController()
        if SettingConfiguration.share.config.secret?.count ?? 0 == 4 {
            seting.secretType = .del
            seting.Callback = {[weak self] success in
                guard let self = self else { return }
                if success {
                    self.modelData = getSettingViewInfo()
                    self.tableView.reloadData()
                }
            }
            self.navigationController?.pushViewController(seting, animated: true)
        }else{
            seting.secretType = .create
            seting.Callback = {[weak self] success in
                guard let self = self else { return }
                if success {
                    self.modelData = getSettingViewInfo()
                    self.tableView.reloadData()
                }
            }
            self.navigationController?.pushViewController(seting, animated: true)
        }
    }
    
    // MARK: - 面容
    private func SetFaceID(_ indexPath:IndexPath) -> Void {
        if SettingConfiguration.share.config.faceId == false {
            if PMFaceIDManger.request() {
                PMFaceIDManger.authenticateWithFaceID(reason: "Unlock privacy space") {[weak self] success, error in
                    if success {
                        SettingConfiguration.share.config.faceId = !(SettingConfiguration.share.config.faceId ?? false)
//                        self?.tableView.reloadData()
                        let cell:SettingSwitchCell = self?.tableView.cellForRow(at: indexPath) as? SettingSwitchCell ?? SettingSwitchCell()
                        cell.openImageView.isSelected = SettingConfiguration.share.config.faceId ?? false
                    }
                }
            }
        }else{
            SettingConfiguration.share.config.faceId = false
            let cell:SettingSwitchCell = tableView.cellForRow(at: indexPath) as? SettingSwitchCell ?? SettingSwitchCell()
            cell.openImageView.isSelected = SettingConfiguration.share.config.faceId ?? false
        }
    }
    
    private func changePIN() -> Void {
        let seting = SecretSetViewController()
        seting.secretType = .change
        seting.Callback = { success in

        }
        self.navigationController?.pushViewController(seting, animated: true)
    }
    
    // MARK: - webview
    private func jumpWeb(_ title:String) -> Void {
        let web = BaseWebViewController()
        var url = ""
        if title == settingLabels.PrivacyPolicy.rawValue {
            url = "https://app.intelliadvert.com/privacy"
        }
        web.LoadWithUrl(url: url)
        navigationController?.pushViewController(web, animated: true)
    }
    
    // MARK: - 邮件
    private func emailLoginSignOut(_ indexPath:IndexPath) -> Void {
        if PMEmailManager.shareManager.loginUser != nil {
            self.view.showBlur()
            let alert = EmailContentDelAlert(state: .emailSignOut)
            alert.callblock = { idx in
                self.view.hideBlur()
                if idx == 1 {
                    PMEmailManager.shareManager.signOut {[weak self] success in
                        if success {
                            EmailFilterManager.share.signOut()
                            self?.tableView.reloadRows(at: [indexPath], with: .none)
                        }
                    }
                }
            }
            alert.show()
        }else{
//            let callblock:(()->Void) = { [weak self] in
//                guard let self = self else { return }
//                let vc:EmailLoginController = EmailLoginController()
//                vc.state = .home
//                self.navigationController?.pushViewController(vc, animated: true)
//                self.tableView.reloadData()
//            }
//            if IAPManager.share.isSubscribed == false {
//                AdvManager.shared.showInterstitialAd(vc: self,from: "emailLoginSignOut")
//            }else{
//                callblock()
//            }
//            AdvManager.shared.finisedCallBack = {
//                callblock()
//            }
            if IAPManager.share.isSubscribed == false {
                ADManager.shared.showInterstitialAd(from: "emailLoginSignOut") {
                    let vc:EmailLoginController = EmailLoginController()
                    vc.state = .home
                    self.navigationController?.pushViewController(vc, animated: true)
                    vc.callblock = { [weak self] in
                        self?.tableView.reloadRows(at: [indexPath], with: .none)
                    }
                } showFailBlock: { error in
                    let vc:EmailLoginController = EmailLoginController()
                    vc.state = .home
                    self.navigationController?.pushViewController(vc, animated: true)
                    vc.callblock = { [weak self] in
                        self?.tableView.reloadRows(at: [indexPath], with: .none)
                    }
                }
            }
        }
    }
    
    // MARK: - 评分
    private func review() -> Void {
        let reviewURLString = "itms-apps://itunes.apple.com/app/id1530333201?action=write-review"
        guard let url = URL(string: reviewURLString), UIApplication.shared.canOpenURL(url) else {
            return
        }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:])
        }
    }
    
    // MARK: - 分享
    private func Share() -> Void {
        let items: [Any] = ["Want to organize your photo library and free up storage space? Try our app’s smart cleanup feature now!",URL(string: "https://apps.apple.com/app/id1530333201")! ]
        PhoneShare(items, parent: self)
    }
}

