//
//  MergeButtonView.swift
//  PhoneManager
//
//  Created by edy on 2025/5/8.
//

import Foundation
import Contacts
class MergeButtonView : UIView {
    
    
    
    var mergeCallBack : ()->Void = {}
    
    
    lazy var mergeButton : UIButton = {
        let view = UIButton(type: .custom)
        view.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        view.setTitleColor(.white, for: .normal)
        view.clipsToBounds = true
        view.layer.cornerRadius = 23
        view.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        view.setTitle("Merge 0 Contacts", for: .normal)
        view.setImage(UIImage(named: "ic_hebing"), for: .normal)
        
        // 设置间距为 8
        let spacing: CGFloat = 8
        // 获取图片和文字的大小
        let imageSize = view.imageView?.image?.size ?? .zero
        let titleSize = view.titleLabel?.intrinsicContentSize ?? .zero
        // 计算 imageEdgeInsets 和 titleEdgeInsets
        view.imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2, bottom: 0, right: spacing / 2)
        view.titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: -spacing / 2)
        
        view.addTarget(self, action: #selector(merge), for: .touchUpInside)
        return view
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        self.addSubview(self.mergeButton)
        
        self.mergeButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(46)
            make.top.equalToSuperview().offset(16)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension MergeButtonView {
    
    @objc func merge (){
       // self.alertWhenMergeContact()
        if IAPManager.share.isSubscribed == false {
            // 添加的时候需要先弹出广告
            ADManager.shared.showRewardedInterstitialAd(from: ADShowTypeEnum.Merge.name) {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.alertWhenMergeContact()
            } showFailBlock: { _ in
                self.alertWhenMergeContact()
                ADManager.shared.failShowErrMessage()
            }

        }else {
            self.alertWhenMergeContact()
        }
    }
    
    fileprivate func showMeegeAlert(_ self: MergeButtonView) {
        // 直接合并
        let mergeAlertView : ContactMergeAlertView = ContactMergeAlertView()
        mergeAlertView.frame = (self.responderViewController()?.view.bounds)!
        cWindow?.addSubview(mergeAlertView)
        mergeAlertView.alpha = 0
        UIView.animate(withDuration: AniDuration-0.2) {
            mergeAlertView.alpha = 1
        }
        mergeAlertView.sureCallBack = {
            self.mergeCallBack()
        }
    }
    
    func alertWhenMergeContact() {
        // 删除之前弹出是否需要备份
        let alertVc = ContactBackupAlertView()
       
        alertVc.frame = CGRectMake(0, ScreenH, ScreenW, ScreenH)//(self.responderViewController()?.view.bounds)!
        self.responderViewController()?.view.showBlur()
        self.responderViewController()?.view.addSubview(alertVc)
        UIView.animate(withDuration: AniDuration) {
            alertVc.frame = CGRectMake(0, 0, ScreenW, ScreenH)
        }
        
        alertVc.sureCallBack = {[weak self] isSure in
            guard let self else {return}
            self.responderViewController()?.view.hideBlur()
            DispatchQueue.main.asyncAfter(deadline: .now()+AniDuration) {
                if isSure {
                    self.backupContactsByselect {
                        // 备份完成后开始合并
                        self.showMeegeAlert(self)
                    }
                }else{
                    self.showMeegeAlert(self)
                }
            }
        }
    }
    
    func backupContactsByselect(success:@escaping()->Void){
        // 直接备份所有联系人
        let vm = BackupViewModel()
        // 获取所有联系人
        let store = CNContactStore()
        let keysToFetch = [
            CNContactGivenNameKey as CNKeyDescriptor,
            CNContactFamilyNameKey as CNKeyDescriptor,
            CNContactPhoneNumbersKey as CNKeyDescriptor
        ]
        
        do {
            let request = CNContactFetchRequest(keysToFetch: keysToFetch)
            var allContacts : [ContactModel] = []
            try store.enumerateContacts(with: request) { contact, stop in
                if let model = ContactModel.init(contact: contact) {
                    allContacts.append(model)
                }
            }
            vm.backupPartialContacts(allContacts) { finised, error in
                if finised {
                    // 备份成功
                    DispatchQueue.main.async {
                        let buAlertVc = ContactBackUpCompletedAlertView(frame: (cWindow?.bounds)!)
                        cWindow?.addSubview(buAlertVc)
                        buAlertVc.alpha = 0
                        UIView.animate(withDuration: AniDuration-0.2) {
                            buAlertVc.alpha = 1
                        }
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            UIView.animate(withDuration: AniDuration-0.2) {
                                buAlertVc.alpha = 0
                            } completion: { su in
                                buAlertVc.removeFromSuperview()
                                success()
                            }
                        }
                    }
                }else{
                    Print("备份失败")
                }
            }
        } catch {
            DispatchQueue.main.async {
                print("获取联系人信息时发生错误: \(error)")
            }
        }
    }
}
