//
//  ContactNormalIncomView.swift
//  PhoneManager
//
//  Created by edy on 2025/4/21.
//

import Foundation
import SnapKit

class ContactNormalIncomView : UIView {
    
    static let CONTACT_INCOM = "contact_incom"
    
    
    
    private var bottomConstraint: Constraint?
    
    private var tabBottomConstraint: Constraint?
    
    var dataSourceModel : [ContactModel] = []
    
    var dataClearCallBack : ()->Void = {}
    
    var selectDataChangeCallBack: (Bool)->Void = {show in}
    
    
    
    /// 选择的联系人
    var selectedContacts: [ContactModel] = [] {
        didSet{
            
        }
    }
    
    var selectedIndex = 0
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "Incomplete Contacts"
        label.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        label.textAlignment = .left
        return label
    }()
    
    lazy var subTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "\(self.dataSourceModel.count) Contacts"
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        label.textAlignment = .left
        return label
    }()
    
    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 12), style: UITableView.Style.plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(CustomContactAllViewTableViewCell.self, forCellReuseIdentifier: "CustomContactAllViewTableViewCell")
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        return tableView
    }()
    
    lazy var deleteButton : DeleteButtonView = {
        let deleteButton = DeleteButtonView()
        return deleteButton
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.titleLabel)
        self.addSubview(self.subTitleLabel)
        self.addSubview(self.tableView)
        self.addSubview(self.deleteButton)
        
        self.titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.top.equalToSuperview().offset(14 * RScreenH())
            make.width.equalTo(345 * RScreenW())
            make.height.equalTo(32)
        }
        
        self.subTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.top.equalTo(self.titleLabel.snp.bottom).offset(2 * RScreenH())
            make.width.equalTo(345 * RScreenW())
            make.height.equalTo(20)
        }
        
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.subTitleLabel.snp.bottom).offset(16 * RScreenH())
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.right.equalToSuperview().offset(-15 * RScreenW())
            self.tabBottomConstraint = make.bottom.equalToSuperview().offset(-safeHeight).constraint
        }
        self.deleteButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            self.bottomConstraint = make.bottom.equalToSuperview().offset(68).constraint
            make.height.equalTo(68)
        }
        self.deleteButton.submitCallBack = {
            self.alertWhenDeleteSomeOne()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension ContactNormalIncomView : UITableViewDataSource,UITableViewDelegate {

    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.dataSourceModel.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 调起系统弹窗
        let cell = tableView.cellForRow(at: indexPath) as! CustomContactAllViewTableViewCell
        if let model = cell.model {
            if let vc = self.responderViewController() {
                ContactManager.callContactWithIdentifier(model, viewController: vc)
            }
        }
    }
    
    func updateDeleteButtonStatus() {
        DispatchQueue.main.async {
            // 判断button是否显示
            if self.selectedContacts.count > 0 {
                // 设置button的title
                self.deleteButton.deleteButton.setTitle("Delete \(self.selectedContacts.count) Contact", for: .normal)
                UIView.animate(withDuration: 0.1) {
                    // 更新约束
                    self.bottomConstraint?.update(offset: -safeHeight)
                    self.tabBottomConstraint?.update(offset: -safeHeight - 68)
                    self.layoutIfNeeded()
                }
            }else{
                UIView.animate(withDuration: 0.1) {
                    // 更新约束
                    self.bottomConstraint?.update(offset: 68)
                    self.tabBottomConstraint?.update(offset: -safeHeight)
                    self.layoutIfNeeded()
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomContactAllViewTableViewCell", for: indexPath) as! CustomContactAllViewTableViewCell
        let contact = self.dataSourceModel[indexPath.row]
        cell.model = contact
        cell.nameLabel.text = contact.fullName.count > 0 ? contact.fullName : "Untitled contact person"
        if self.selectedContacts.contains(where: { $0.identifier == contact.identifier }) {
            cell.selectButton.isSelected = true
        }else {
            cell.selectButton.isSelected = false
        }
        cell.buttonSelectCallBack = {[weak self] model,selected in
            guard let self else {return}
            self.vibrate()
            if selected {
                self.selectedContacts.append(model)
            }else{
                self.selectedContacts.removeAll(where: { $0.identifier == model.identifier })
            }
            updateDeleteButtonStatus()
            changeHeaderSelectButtonStatus()
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 77 + 8 * RScreenH()
    }

    func alertWhenDeleteSomeOne() {
        // 删除之前弹出是否真的需要删除
        let alertVc = ContactDeleteAlertView()
        alertVc.frame = (self.responderViewController()?.view.bounds)!
        cWindow?.addSubview(alertVc)
        alertVc.alpha = 0
        UIView.animate(withDuration: AniDuration - 0.2) {
            alertVc.alpha = 1
        }
        alertVc.sureCallBack = {[weak self] isSure in
            guard let self else {return}
            if isSure {
                self.deleteContacts()
            }
        }
    }
    
    func deleteContacts(){
        // 删除逻辑
        for contact in selectedContacts {
            if let index = self.dataSourceModel.firstIndex(of: contact) {
                self.dataSourceModel.remove(at: index)
            }
        }
        ContactManager.batchDeleteContacts(self.selectedContacts) { result in
            switch result {
            case .success(let deletedContacts):
                print("成功删除 \(deletedContacts.count) 个联系人")
                self.selectedContacts.removeAll()
                self.subTitleLabel.text = "\(self.dataSourceModel.count) Contacts"
                self.updateDeleteButtonStatus()
                self.tableView.reloadData()
                
                if self.dataSourceModel.count <= 0 {
                    self.dataClearCallBack()
                }
                
                // 删除完成 弹窗
                let buAlertVc = ContactBackUpDeleteCompletedAlertView(frame: (cWindow?.bounds)!)
                cWindow?.addSubview(buAlertVc)
                buAlertVc.alpha = 0
                UIView.animate(withDuration: AniDuration - 0.2) {
                    buAlertVc.alpha = 1
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    UIView.animate(withDuration: AniDuration-0.2) {
                        buAlertVc.alpha = 0
                    } completion: { su in
                        buAlertVc.removeFromSuperview()
                    }
                }
                break
            case .failure(.contactNotFound(let missing)):
                print("操作终止：未找到联系人 \(missing.identifier)")
            case .failure(.unauthorized):
                print("无通讯录访问权限")
            case .failure(.executionFailed(let error)):
                print("操作失败：\(error.localizedDescription)")
            }
        }
        
    }
    
    func changeHeaderSelectButtonStatus(){
        if self.dataSourceModel.count != self.selectedContacts.count {
            self.selectDataChangeCallBack(true)
        }else {
            self.selectDataChangeCallBack(false)
        }
    }
}
