PhoneContactsVC.swift 8.99 KB
//
//  PhoneContactsVC.swift
//  Twear
//
//  Created by yangbin on 2022/1/15.
//

import UIKit
import Contacts
import SCIndexView
import SnapKit
import MBProgressHUD

class PhoneContactsVC: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var contactClosure: ((_ array: [ContactModel]) -> ())?
    
    var preContacts: [ContactModel] = []
    
    var contacts: [ContactModel] = []
    var contactList: [[ContactModel]] = []
    var titleArray: [String] = []
//    var selectedIndex: [IndexPath] = []
    var selectedContacts: [ContactModel] = []
    
    var maxCount: Int = 8
    
    lazy var addButton: UIButton = {
        let addButton = UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 28))
        addButton.setTitle(LocString("确定"), for: .normal)
        addButton.titleLabel?.contentMode = .right
        addButton.titleLabel?.font = RegularFont(14)
        addButton.setTitleColor(.black, for: .normal)
        addButton.addTarget(self, action: #selector(clickAddButton), for: .touchUpInside)
        return addButton
    }()
    
    lazy var cancelButton: UIButton = {
        let addButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 28))
        addButton.setTitle(LocString("取消"), for: .normal)
        addButton.titleLabel?.font = RegularFont(14)
        addButton.setTitleColor(.black, for: .normal)
        addButton.addTarget(self, action: #selector(clickCancelButton), for: .touchUpInside)
        return addButton
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = LocString("选择联系人")
        
        navigationItem.leftBarButtonItem =  UIBarButtonItem(customView: cancelButton)
        navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: addButton)
        
        
        tableView.register(UINib.init(nibName: "ContactCell", bundle: Bundle.main), forCellReuseIdentifier: "ContactCell")
        tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        //        tableView.style = .grouped
        let indexViewConfiguration = SCIndexViewConfiguration(indexViewStyle: .default)
        indexViewConfiguration?.indexItemSelectedBackgroundColor = .clear
        indexViewConfiguration?.indexItemSelectedTextColor = .darkGray
        //        indexViewConfiguratio
        tableView.sc_indexViewConfiguration = indexViewConfiguration
        tableView.sc_translucentForTableViewInNavigationBar = true
        
        
        
        loadContactsData()
    }
    
    @objc private func clickAddButton() {
//        if selectedContacts.count > 0 {
//            for contact in selectedContacts {
//                contact.isSelected = false
//            }
            contactClosure?(selectedContacts)
//        }
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickCancelButton() {
        navigationController?.popViewController(animated: true)
    }
    
    func loadContactsData() {
        //获取授权状态
        let status = CNContactStore.authorizationStatus(for: .contacts)
        guard status == .authorized else { return }
        
        let store = CNContactStore()
        let keys = [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey]
        let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
        
        do {
            try store.enumerateContacts(with: request) { (contact, _) in
                for phone in contact.phoneNumbers {
                    let model = ContactModel(name: "\(contact.familyName)\(contact.givenName)", number: phone.value.stringValue)
                    for c in self.preContacts {
                        if c.number == phone.value.stringValue {
                            model.isSelected = true
                            model.isSOS = c.isSOS
                            self.selectedContacts.append(c)
                        }
                    }
                    self.contacts.append(model)
                    print("\(model.name)--\(model.number)   ")
                }
                if self.selectedContacts.count == 0 {
                    self.addButton.setTitle("\(LocString("确定"))", for: .normal)
                } else {
                    self.addButton.setTitle("\(LocString("确定"))(\(self.selectedContacts.count))", for: .normal)
                }
                
                self.sortList(self.contacts)
            }
        } catch {
            print(error)
        }
    }
    
    func sortList(_ array: [ContactModel]) {
        BMChineseSort.sortAndGroup(objectArray: array, key: "name") { isSuccess, _, titleArray, objArray in
            self.tableView.sc_indexViewDataSource = titleArray
            self.titleArray = titleArray
            self.contactList = objArray
//            for obj in objArray {
//                for a in obj {
//
//                }
//            }
            self.tableView.reloadData()
        }
    }
    
    
    @IBAction func editingChanged(_ sender: UITextField) {
        let searchText = sender.text
        var list: [ContactModel] = []
        if searchText == "" {
            sortList(contacts)
        } else {
            for contact in contacts {
                if contact.name.contains(searchText!) {
                    list.append(contact)
                } else if contact.number.contains(searchText!) {
                    list.append(contact)
                }
            }
            
            sortList(list)
        }
        //        self.reloadListData()
        //        self.tableView.reloadData()
    }
    
}


extension PhoneContactsVC: UITableViewDelegate, UITableViewDataSource {
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return contactList.count
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.5
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        let view = UIView()
        view.backgroundColor = .clear//UIColor.rgbColorFromHex(0xF2F2F2)
        let label = UILabel()
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(12)
        }
        label.text = titleArray[section]
        label.font = RegularFont(14)
        //            label.textColor = UIColor.rgbColorFromHex(0x98C1D9)
        //            view.backgroundColor = .red
        return view
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return contactList[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) as! ContactCell
        cell.isPhone = true
        cell.contact = contactList[indexPath.section][indexPath.row]
       
        //        cell.alarmClock = alarmClockArray[indexPath.row]
        //        cell.switchClosure = {[weak self] isOn in
        //            self?.switchValueChanged(isOn, index: indexPath.row)
        //        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! ContactCell
        cell.isSelected = false
        let contact = contactList[indexPath.section][indexPath.row]
        let selected = contact.isSelected
        if !selected && selectedContacts.count >= maxCount {
            //        if contacts.count >= 8 {
                        MBProgressHUD.showh(LocString("您最多可以添加8个联系人"))
            //            return
            //        }
            return
        }
        contact.isSelected = !selected
//        if let i = contacts.firstIndex(of:contact) {
//            contacts[i].isSelected = !selected
//        }
        
        if !selected {
            selectedContacts.append(contact)
        } else {
            for (i, c) in selectedContacts.enumerated() {
                if c.number == contact.number && c.name == contact.name {
                    selectedContacts.remove(at: i)
                    break
                }
            }
            
            
//            if let i = selectedContacts.firstIndex(of: contact) {
//                selectedContacts.remove(at: i)
//            }
        }
        if selectedContacts.count == 0 {
            addButton.setTitle("\(LocString("确定"))", for: .normal)
        } else {
            addButton.setTitle("\(LocString("确定"))(\(selectedContacts.count))", for: .normal)
        }
       
        tableView.reloadData()

    }
}