//
//  ContactViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/18.
//

import Foundation
import Contacts
import UIKit

class ContactViewController : BaseViewController {
    
    var dataSourceModel : ContactModuleModel = ContactModuleModel(duplicates: [], incompleteContacts: [], backups: [], allContacts: [])
    
    lazy var navView : ContactNavView = {
        let view = ContactNavView()
        return view
    }()
    
    
    lazy var emptyView:ContactDefaultView = {
        let view = ContactDefaultView()
        return view
    }()
    
    lazy var moduleView:ContactModuleView = {
        let view = ContactModuleView()
        return view
    }()
    
    override func viewDidLoad() {
        APIReportManager.shared.startReport(type: .Contacts_show)
        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)
        }
    }
    
    func setDefaultPage(){
        self.moduleView.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.moduleView)
        self.moduleView.snp.makeConstraints { make in
            make.top.equalTo(self.navView.snp.bottom).offset(0)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 请求联系人权限
        self.setDefaultPage()
        requestContactsPermission { permission in
            DispatchQueue.main.async {
                if permission {
                    // 有权限
                    self.updateModuleData()
                    self.setNormalPage()
                    // 初始化数据
                    self.initContatsInfo()
                }
            }
            
        }
        
    }
}

extension ContactViewController{
    
    /// 更新模块显示的数据
    func updateModuleData() {
        
        var moduleViewData : [ModuleDataModel] = []
        let model1 =  ModuleDataModel.init(titleText: "Duplicates", subTitleText:"\(String(describing: self.dataSourceModel.duplicates.count)) Duplicates")
        let model2 =  ModuleDataModel.init(titleText: "Incomplete Contacts", subTitleText:"\(String(describing: self.dataSourceModel.incompleteContacts.count)) Incomplete Contacts")
        let model3 =  ModuleDataModel.init(titleText: "Backups", subTitleText:"\(String(describing: self.dataSourceModel.backups.count)) Backups")
        let model4 =  ModuleDataModel.init(titleText: "All Contacts", subTitleText:"\(String(describing: self.dataSourceModel.allContacts.count)) Contacts")
        
        moduleViewData.append(model1)
        moduleViewData.append(model2)
        moduleViewData.append(model3)
        moduleViewData.append(model4)
        
        self.moduleView.moduleViewData = moduleViewData
        self.moduleView.dataSourceModel = self.dataSourceModel
    }
    
    
    /// 初始化联系人数据
    func initContatsInfo() {
        DispatchQueue.global(qos: .userInitiated).async {
            let store = CNContactStore()
            let keysToFetch = [
                CNContactGivenNameKey as CNKeyDescriptor,
                CNContactFamilyNameKey as CNKeyDescriptor,
                CNContactPhoneNumbersKey as CNKeyDescriptor
            ]
            do {
                let request = CNContactFetchRequest(keysToFetch: keysToFetch)
                var incompleteContacts: [ContactModel] = []
                var allContacts: [ContactModel] = []
                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 || model.phoneNumber?.count ?? 0 <= 0 {
                            incompleteContacts.append(model)
                        }
                        allContacts.append(model)
                        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 }
                    }
                }
                let dataSource = ContactModuleModel.init(
                    duplicates: self.sortDupDataSource(orgData: duplicates),
                    incompleteContacts: incompleteContacts,
                    backups: [],
                    allContacts: allContacts
                )
                DispatchQueue.main.async {
                    self.dataSourceModel = dataSource
                    self.updateModuleData()
                    self.moduleView.tableView.reloadData()
                }
            } catch {
                DispatchQueue.main.async {
                    print("获取联系人信息时发生错误: \(error)")
                }
            }
            // 获取备份数据
            let vm = BackupViewModel()
            vm.retrieveContactsFromBackup { model, error in
                if let error = error {
                    Print("请求备份数据失败，\(error.localizedDescription)")
                    return
                }
                DispatchQueue.main.async {
                    self.dataSourceModel.backups = model!
                    self.updateModuleData()
                    self.moduleView.tableView.reloadData()
                }
            }
        }
    }
    
    
// MARK: 辅助方法
    
    /// 获取联系人权限
    /// - Parameter completion: 回调
    func requestContactsPermission(completion: @escaping (Bool) -> Void) {
        let store = CNContactStore()
        switch CNContactStore.authorizationStatus(for: .contacts) {
        case .authorized:
            // 已经授权
            completion(true)
        case .denied, .restricted:
            // 被拒绝或受限
            completion(false)
        case .notDetermined:
            // 未确定，请求授权
            store.requestAccess(for: .contacts) { granted, error in
                if let error = error {
                    print("请求联系人权限时发生错误: \(error)")
                }
                completion(granted)
            }
        case .limited:
            // 不分联系人权限
            completion(true)
        @unknown default:
            completion(false)
        }
    }
    
    
    /// 重复项排序-做一个反序操作，让最新添加的联系人显示在最前面
    /// - Parameter orgData: 原始数据
    /// - Returns: 排序后的数据
    func sortDupDataSource(orgData:[[ContactModel]])->[[ContactModel]]{
        return orgData.map { $0.reversed() }
    }
    
}
