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

import Foundation
import UIKit

class ContactsDupPreViewController : BaseViewController {
    
    
    var dataSourceModel : [String:[ContactModel]] = [:]
    
    lazy var navView : ContactNavView = {
        let view = ContactNavView()
        return view
    }()
    
    
    lazy var emptyView:ContactNoDupPreView = {
        let view = ContactNoDupPreView()
        return view
    }()
    lazy var normalView : ContactDupPreNormalView = {
        let view = ContactDupPreNormalView()
        return view
    }()
    
    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.setDefaultPage()
        
        self.normalView.dataChangeCallBack = {[weak self] isClear in
            guard let self else {return}
            if isClear {
                DispatchQueue.main.async {
                    self.setDefaultPage()
                }
            }
        }
        
        let dataUpdatePre = Notification.Name(ContactDupPreNormalView.CONTACT_MERGED_PRE)
        NotificationCenter.default.addObserver(self, selector: #selector(handleDataUpdated(_:)), name: dataUpdatePre, object: nil)
    }
    
    
    // 默认页面
    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()
        }
    }
}

extension ContactsDupPreViewController {
    
    fileprivate func dealWhenSystemDataUpdate() {
        // 这里还需要处理下万一当前用户在外部修改了下联系人
        var changed : Bool = false
        for (_,value) in self.dataSourceModel {
            // 看名字和电话号码是否全部能对上
           
            for contact in value {
                // 从系统取出联系人
                if let sysContact = ContactManager.fetchContactFromStore(model: contact){
                    let fullName = "\(sysContact.familyName)\(sysContact.givenName)"
                    let phoneNumbers = sysContact.phoneNumbers.map { $0.value.stringValue}
                    if let numbers = contact.phoneNumber {
                        // 两个相等
                        if fullName != contact.fullName || phoneNumbers.sorted() != numbers.sorted(){
                            changed = true
                            break
                        }
                    }else {
                        changed = true
                        break
                    }
                }else {
                    changed = true
                    break
                }
            }
            if changed == true {
               break
            }
        }
        // 如果变了
        if changed == true {
            self.dataSourceModel = [:]
            setDefaultPage()
        }else{
            var finallyData : [[ContactModel]] = []
            for (_,value) in self.dataSourceModel {
                finallyData.append(value)
            }
            self.normalView.dataSourceModel = finallyData
            DispatchQueue.main.async {
                self.normalView.subTitleLabel.text = "\(self.dataSourceModel.count) Contacts"
                var count : Int = 0
                for item in finallyData {
                    count += item.count
                }
                self.normalView.mergeButtonView.mergeButton.setTitle("Merge \(count) Contacts", for: .normal)
                self.normalView.tableView.reloadData()
            }
        }
        
        
    }
    
    fileprivate func dealDataToNoEmpty() {
        var tempArray : [String:[ContactModel]] = [:]
        for (key,value) in self.dataSourceModel {
            if value.count > 0 {
                tempArray[key] = value
            }
        }
        self.dataSourceModel = tempArray
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        dealDataToNoEmpty()
        
        if self.dataSourceModel.count > 0 {
            self.setNormalPage()
            var finallyData : [[ContactModel]] = []
            for (_,value) in self.dataSourceModel {
                finallyData.append(value)
            }
            self.normalView.dataSourceModel = finallyData
            DispatchQueue.main.async {
                self.normalView.subTitleLabel.text = "\(self.dataSourceModel.count) Contacts"
                var count : Int = 0
                for item in finallyData {
                    count += item.count
                }
                self.normalView.mergeButtonView.mergeButton.setTitle("Merge \(count) Contacts", for: .normal)
                self.normalView.tableView.reloadData()
            }
            
        }else{
            self.setDefaultPage()
        }
    }
    
    
    @objc func handleDataUpdated(_ notification: Notification) {
        dealWhenSystemDataUpdate()
    }
}
