//
//  AllContactViewController.swift
//  PhoneManager
//
//  Created by 赵前 on 2025/4/19.
//

import Foundation
import Contacts
import UIKit

class ContactAllViewController : BaseViewController {
    
    
    var dataSourceModel : [ContactModel]?
    
    lazy var navView : ContactNavView = {
        let view = ContactNavView()
        return view
    }()
    
    lazy var emptyView : ContactNoAllView = {
        let view = ContactNoAllView()
        return view
    }()
    lazy var normalView : ContactAllView = {
        let view = ContactAllView()
        return view
    }()
    
    
    
    
    // 默认页面
    func setDefaultPage(){
        self.normalView.removeFromSuperview()
        self.view.addSubview(self.emptyView)
        
        self.emptyView.snp.makeConstraints { make in
            make.top.equalTo(self.navView.snp.bottom).offset(0)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    func setNormalPage(){
        self.emptyView.removeFromSuperview()
        self.view.addSubview(self.normalView)
        
        self.normalView.snp.makeConstraints { make in
            make.top.equalTo(self.navView.snp.bottom).offset(0)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .white
        
        self.view.addSubview(self.navView)
        self.navView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(statusBarHeight + 44)
        }
        
        self.normalView.dataClearCallBack = {
            self.setDefaultPage()
        }
        
        // 发起通知刷新重复联系人预览页面数据
        let dataUpdateAll = Notification.Name(ContactAllView.CONTACT_ALL)
        NotificationCenter.default.addObserver(self, selector: #selector(handleDataUpdated(_:)), name: dataUpdateAll, object: nil)
    }
    
}

extension ContactAllViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let data = self.dataSourceModel {
            if data.count > 0 {
                self.setNormalPage()
                self.normalView.dataSourceModel = data
                DispatchQueue.main.async {
                    self.normalView.subTitleLabel.text = "\(data.count) Contacts"
                    self.normalView.sortContacts()
                    self.normalView.tableView.reloadData()
                    self.normalView.setupCustomIndexView()
                }
                
            }else{
                self.setDefaultPage()
            }
        }else {
            self.setDefaultPage()
        }
        
    }
    
    @objc func handleDataUpdated(_ notification: Notification) {
        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)
                }
            }
            DispatchQueue.main.async {
                self.normalView.dataSourceModel = allContacts
                if allContacts.count > 0 {
                    self.setNormalPage()
                    self.normalView.subTitleLabel.text = "\(allContacts.count) Contacts"
                    self.normalView.sortContacts()
                    self.normalView.tableView.reloadData()
                    self.normalView.setupCustomIndexView()
                }else{
                    self.setDefaultPage()
                }
            }
        } catch {
            DispatchQueue.main.async {
                print("获取全部联系人信息时发生错误: \(error)")
            }
        }
    }
}
