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

import Foundation
import SnapKit
import Contacts
import UIKit

class ContactIncompleteViewController : BaseViewController {
    
//    private var widthConstraint: Constraint?
    
    var dataSourceModel : [ContactModel]?
    
    lazy var navView : ContactNavView = {
        let view = ContactNavView()
        return view
    }()
    
    lazy var selectAllButton : SelectAllButton = {
        let view = SelectAllButton()
        view.clipsToBounds = true
        view.layer.cornerRadius = 16
        return view
    }()
    
    lazy var emptyView : ContactNoIncomView = {
        let view = ContactNoIncomView()
        return view
    }()
    
    lazy var normalView : ContactNormalIncomView = {
        let view = ContactNormalIncomView()
        return view
    }()
    
    
    // 默认页面
    func setDefaultPage(){
        self.normalView.removeFromSuperview()
        self.selectAllButton.isHidden = true
        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.selectAllButton.isHidden = false
        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.navView.addSubview(self.selectAllButton)
        self.selectAllButton.snp.makeConstraints { make in
            make.right.equalTo(-15 * RScreenW())
            make.centerY.equalTo(self.navView.backButton.snp.centerY)
//            widthConstraint =  make.width.equalTo(115).constraint
            make.height.equalTo(32)
        }
        
        self.selectAllButton.tapCallback = { isSelected in
            // 选择之后，更新宽度约束的常量值
            if isSelected {
                self.normalView.selectedContacts = self.normalView.dataSourceModel
//                self.widthConstraint?.update(offset: 131)
            }else {
                self.normalView.selectedContacts.removeAll()
//                self.widthConstraint?.update(offset: 115)
            }
            self.normalView.updateDeleteButtonStatus()
            // 强制重新布局
//            UIView.animate(withDuration: 0.3) {
//                self.selectAllButton.setNeedsLayout()
//                self.selectAllButton.layoutIfNeeded()
//            }
            self.normalView.tableView.reloadData()
        }
        self.normalView.dataClearCallBack = {
            self.setDefaultPage()
        }
        self.normalView.selectDataChangeCallBack = {[weak self]show in
            guard let self else {return}
            if show {
                self.selectAllButton.isSelected = false
            }else {
                self.selectAllButton.isSelected = true
            }
        }
        self.setDefaultPage()
        
        
        
        // 发起通知刷新重复联系人预览页面数据
        let dataUpdateInc = Notification.Name(ContactNormalIncomView.CONTACT_INCOM)
        NotificationCenter.default.addObserver(self, selector: #selector(handleDataUpdated(_:)), name: dataUpdateInc, object: nil)
    }
}

extension ContactIncompleteViewController {
    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.tableView.reloadData()
                }
                
            }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 incompleteContacts : [ContactModel] = []
            
            try store.enumerateContacts(with: request) { contact, stop in
                if let model = ContactModel.init(contact: contact){
                    if model.fullName.isEmpty ||  model.phoneNumber?.count ?? 0 <= 0 {
                        incompleteContacts.append(model)
                    }
                }
                
            }
            DispatchQueue.main.async {
                self.normalView.dataSourceModel = incompleteContacts
                if incompleteContacts.count > 0 {
                    self.setNormalPage()
                    self.normalView.subTitleLabel.text = "\(incompleteContacts.count) Contacts"
                    self.normalView.tableView.reloadData()
                }else{
                    self.setDefaultPage()
                }
            }
        } catch {
            DispatchQueue.main.async {
                print("获取不完整联系人信息时发生错误: \(error)")
            }
        }
    }
}
