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

import Foundation
import SnapKit
import Contacts
import UIKit
class ContactsDupViewController : BaseViewController {
    
    var dataSourceModel : [[ContactModel]]?
    
    private var widthConstraint: Constraint?
    
    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 : ContactNoDupView = {
        let view = ContactNoDupView()
        return view
    }()
    lazy var normalView : ContactDupNormalView = {
        let view = ContactDupNormalView()
        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.view.addSubview(self.normalView)
        self.selectAllButton.isHidden = false
        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.equalToSuperview().offset(-15)
            make.centerY.equalTo(self.navView.backButton.snp.centerY)
//            widthConstraint =  make.width.equalTo(115).constraint
            make.height.equalTo(32)
        }
        
        self.setDefaultPage()
        
        
        self.selectAllButton.tapCallback = {[weak self] isSelected in
            guard let self else {return}
            DispatchQueue.main.async {
                // 选择之后，更新宽度约束的常量值
                if isSelected {
//                    self.widthConstraint?.update(offset: 131)
                    if let data = self.dataSourceModel {
                        for(index,item) in data.enumerated(){
                            self.normalView.selectData[String(index)] = item
                        }
                    }
                }else {
//                    self.widthConstraint?.update(offset: 115)
                    self.normalView.selectData = [:]
                }
                // 强制重新布局
//                UIView.animate(withDuration: 0.3) {
//                    self.selectAllButton.setNeedsLayout()
//                    self.selectAllButton.layoutIfNeeded()
//                }
                self.normalView.tableView.reloadData()
            }
        }
        self.normalView.dataChangeCallBack = {[weak self]changed in
            guard let self else {return}
            DispatchQueue.main.async {
                // 选择之后，更新宽度约束的常量值
                if changed {
//                    self.widthConstraint?.update(offset: 131)
                    self.selectAllButton.isSelected = true
                }else {
                    self.widthConstraint?.update(offset: 115)
//                    self.selectAllButton.isSelected = false
                }
            }
        }
        
        let dataUpdated = Notification.Name(ContactDupPreNormalView.CONTACT_MERGED)
        NotificationCenter.default.addObserver(self, selector: #selector(handleDataUpdated(_:)), name: dataUpdated, object: nil)
    }
}

extension ContactsDupViewController {
    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 = "\(self.getCountFromDataSource(data:data)) Contacts"
                    self.normalView.tableView.reloadData()
                }
                
            }else{
                self.setDefaultPage()
            }
        }else {
            self.setDefaultPage()
        }
    }
    func getCountFromDataSource(data:[[ContactModel]]) -> Int{
        var totalElementCount = 0
        for subArray in data {
            totalElementCount += subArray.count
        }
        return totalElementCount
    }
    
    
    func reGetCurrentPageData() {
        // 重新获取下重复项的数据
        let store = CNContactStore()
        let keysToFetch = [
            CNContactGivenNameKey as CNKeyDescriptor,
            CNContactFamilyNameKey as CNKeyDescriptor,
            CNContactPhoneNumbersKey as CNKeyDescriptor
        ]
        
        do {
            let request = CNContactFetchRequest(keysToFetch: keysToFetch)
            // 创建数组
            var duplicates : [[ContactModel]] = []
            
            var contactsByName: [String: [ContactModel]] = [:]
            
            try store.enumerateContacts(with: request) { contact, stop in
                if let model = ContactModel.init(contact: contact) {
                    if !model.fullName.isEmpty {
                        if contactsByName[model.fullName] == nil {
                            contactsByName[model.fullName] = [model]
                        } else {
                            contactsByName[model.fullName]?.append(model)
                        }
                    }
                    duplicates = contactsByName.values.filter { $0.count > 1 }
                }
            }
            DispatchQueue.main.async {
                self.dataSourceModel = duplicates
                self.normalView.dataSourceModel = duplicates
                self.normalView.subTitleLabel.text = "\(self.getCountFromDataSource(data:duplicates)) Contacts"
                self.normalView.selectData = [:]
                if duplicates.count > 0 {
                    self.setNormalPage()
                    self.normalView.tableView.reloadData()
                }else{
                    self.setDefaultPage()
                }
            }
        } catch {
            DispatchQueue.main.async {
                print("获取联系人信息时发生错误: \(error)")
            }
        }
    }
    
    @objc func handleDataUpdated(_ notification: Notification) {
        reGetCurrentPageData()
    }
}

