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

import Foundation
class ContactDupPreNormalView : UIView {
    
    static let CONTACT_MERGED = "contact_merged"
    
    static let CONTACT_MERGED_PRE = "contact_merged_pre"
    
    var dataSourceModel : [[ContactModel]] = []
    
    var preButtonShowStatus : Bool = false
    
    // 如果将不想合并的重复联系人删除完了，就显示没有预览可用页面
    var dataChangeCallBack : (Bool)->Void = {isClear in}
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "Duplicates"
        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.grouped)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(CustomContactDupPreTableViewCell.self, forCellReuseIdentifier: "CustomContactDupPreTableViewCell")
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        return tableView
    }()
    
    lazy var mergeButtonView : MergeButtonView = {
        let view = MergeButtonView()
        return view
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.titleLabel)
        self.addSubview(self.subTitleLabel)
        self.addSubview(self.tableView)
        self.addSubview(self.mergeButtonView)
        
        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())
            make.bottom.equalToSuperview().offset(-safeHeight - 68)
        }
        
        self.mergeButtonView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-safeHeight)
            make.height.equalTo(68)
        }
        
        
        self.mergeButtonView.mergeCallBack = {
            ContactManager.mergeContacts(groups: self.dataSourceModel) { result in
                switch result {
                case .success(let newIDs):
                    print("新联系人ID: \(newIDs)")
                    DispatchQueue.main.async {
                        
                        self.removeData()
                        
                        // 弹框提示成功
                        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()
                            }
                            // 返回重复项
                        }
                        self.responderViewController()?.navigationController?.popViewController(animated: true)
                    }
                    break
                case .failure(let error):
                    print("合并失败: \(error.localizedDescription)")
                }
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /// 合并成功后移除数据源
    func removeData(){
        self.dataSourceModel.removeAll()
        self.tableView.reloadData()
        // 更新下头部数据
        self.subTitleLabel.text = "\(self.dataSourceModel.count) Contacts"
        
        self.dataChangeCallBack(true)
        
        // 发起通知
        let dataUpdated = Notification.Name(ContactDupPreNormalView.CONTACT_MERGED)
        NotificationCenter.default.post(name: dataUpdated, object: nil, userInfo: nil)
    }
}

extension ContactDupPreNormalView : UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSourceModel.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 调起系统弹窗
        let cell = tableView.cellForRow(at: indexPath) as! CustomContactDupPreTableViewCell
        if let model = cell.model.first {
            if let vc = self.responderViewController() {
                ContactManager.callContactWithIdentifier(model, viewController: vc)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomContactDupPreTableViewCell", for: indexPath) as! CustomContactDupPreTableViewCell
        cell.indexPath = indexPath
        cell.model = self.dataSourceModel[indexPath.section]
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 77 + 8 * RScreenH()
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = CustomDupPreHeaderView(frame: CGRect(x: 0 , y: 0, width: self.tableView.width, height: 22))
        view.model = self.dataSourceModel[section]
        view.currentSection = section
        view.headerCallback = { array, currentSection in
            self.dataSourceModel.remove(at: currentSection)
            DispatchQueue.main.async {
                self.tableView.reloadData()
                self.subTitleLabel.text = "\(self.dataSourceModel.count) Contacts"
                if self.dataSourceModel.count == 0 {
                    self.dataChangeCallBack(true)
                }
            }
        }
        
        return view
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 34
    }
    
    
}
