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

import ContactsUI

// 步骤1: 创建子类继承 CNContactViewController
class CustomContactViewController: CNContactViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.allowsEditing = false
        setupCancelButton()
    }

    // 自定义取消按钮
    private func setupCancelButton() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "Cancel",
            style: .plain,
            target: self,
            action: #selector(dismissEditor))
    }
}
extension CustomContactViewController {
    
    @objc private func dismissEditor() {
//        // 发起通知刷新重复联系人页面数据
//        let dataUpdated = Notification.Name(ContactDupPreNormalView.CONTACT_MERGED)
//        NotificationCenter.default.post(name: dataUpdated, object: nil, userInfo: nil)
//        
//        // 发起通知刷新重复联系人预览页面数据
//        let dataUpdatePre = Notification.Name(ContactDupPreNormalView.CONTACT_MERGED_PRE)
//        NotificationCenter.default.post(name: dataUpdatePre, object: nil, userInfo: nil)
        dismiss(animated: true, completion: nil)
    }
    
    
    // 使用自定义视图控制器
    func presentCustomContactEditor(with identifier: String , viewController: UIViewController) {
        let contactStore = CNContactStore()
        let keys = [CNContactViewController.descriptorForRequiredKeys()]
        
        do {
            let contact = try contactStore.unifiedContact(withIdentifier: identifier, keysToFetch: keys)
            let mutableContact = contact.mutableCopy() as! CNMutableContact
            
            // 步骤4: 使用自定义子类初始化
            let editVC = CustomContactViewController(for: mutableContact)
            editVC.contactStore = contactStore
            
            let navController = UINavigationController(rootViewController: editVC)
            viewController.present(navController, animated: true)
            
        } catch {
            print("获取联系人失败: \(error)")
        }
    }
}


