//
//  ContactDupNormalView.swift
//  PhoneManager
//
//  Created by edy on 2025/5/6.
//

import Foundation
import SnapKit

class ContactDupNormalView : UIView {
    
    var dataSourceModel : [[ContactModel]] = [] 
    
    var preButtonShowStatus : Bool = false
    
    var selectData: [String : [ContactModel]] = [:] {
        didSet {
            // 是否更新底部合并预览按钮
            showPreMergeButton()
            self.dataChangeCallBack(isAllData())
        }
    }
    
    var dataChangeCallBack:(Bool)->Void = {changed in}
    
    private var bottomConstraint: Constraint?
    
    private var tabBottomConstraint: Constraint?
    
    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(CustomContactDupTableViewCell.self, forCellReuseIdentifier: "CustomContactDupTableViewCell")
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        return tableView
    }()
    
    lazy var preButtonView : MergePreButtonView = {
       let view = MergePreButtonView()
        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.preButtonView)
        
        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.preButtonView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            self.bottomConstraint = make.bottom.equalToSuperview().offset(68).constraint
            make.height.equalTo(68)
        }
        
        self.preButtonView.mergePreCallBack = {
            let vc = ContactsDupPreViewController()
            
            // 对data 做下处理 当里面只有一个元素的时候实际是不能合并的
            vc.dataSourceModel = self.removeSingalDataInDataSource()
            self.responderViewController()?.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension ContactDupNormalView : UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSourceModel.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSourceModel[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomContactDupTableViewCell", for: indexPath) as! CustomContactDupTableViewCell
        cell.indexPath = indexPath
        cell.model = self.dataSourceModel[indexPath.section][indexPath.row]
        cell.cellSelectCallCack = {[weak self]index,choose in
            guard let self else {return}
            self.vibrate()
            if choose {
                self.saveSelectModel(index: index)
            }else {
                self.removeSelectModel(index: index)
            }
        }
        // 如果有选中的更新
        if let tempArray = self.selectData[String(indexPath.section)] {
            if tempArray.contains(where: {$0.identifier == self.dataSourceModel[indexPath.section][indexPath.row].identifier}) {
                cell.selectButton.isSelected = true
            }else{
                cell.selectButton.isSelected = false
            }
        }else {
            cell.selectButton.isSelected = false
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 77 + 8 * RScreenH()
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = CustomDupHeaderView(frame: CGRect(x: 0 , y: 0, width: self.tableView.width, height: 22))
        view.model = self.dataSourceModel[section]
        
        // UI判断
        changeHeaderSelectButton(section: section, view: view)
        view.headerCallback = {[weak self]data in
            guard let self else {return}
            if let tempData = self.selectData[String(section)] {
                // 如果是数量和元数据数量一样表示已经是选择了全部的状态，则清空下
                if tempData.count > 0 && tempData.count == self.dataSourceModel[section].count {
                    self.selectData[String(section)] = []
                }else{
                    self.selectData[String(section)] = data
                }
            }else{
                self.selectData[String(section)] = data
            }
            DispatchQueue.main.async {
                self.dataChangeCallBack(self.isAllData())
                tableView.reloadSections(IndexSet(integer: section), with: .automatic)
            }
        }
        return view
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 34
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 调起系统弹窗
        let cell = tableView.cellForRow(at: indexPath) as! CustomContactDupTableViewCell
        if let model = cell.model {
            if let vc = self.responderViewController() {
                ContactManager.callContactWithIdentifier(model, viewController: vc)
            }
        }
    }
    
    
    
    // MARK: 辅助方法
    func changeHeaderSelectButton(section:Int,view:CustomDupHeaderView){
        DispatchQueue.main.async {
            if let tempData = self.selectData[String(section)] {
                if tempData.count == self.dataSourceModel[section].count{
                    // 改变UI
                    view.subLabel.text = "Deselect all"
                }else {
                    view.subLabel.text = "Select All"
                }
            }else {
                view.subLabel.text = "Select All"
            }
        }
    }
    
    func saveSelectModel(index:IndexPath){
        let tempModel = self.dataSourceModel[index.section][index.row]
        if var array = self.selectData[String(index.section)] {
            array.append(tempModel)
            self.selectData[String(index.section)] = array
        }else{
            self.selectData[String(index.section)] = [tempModel]
        }
        
        if let header = self.tableView.headerView(forSection: index.section) {
            changeHeaderSelectButton(section: index.section, view: header as! CustomDupHeaderView)
        }
        // 改变导航栏的选择按钮状态
        self.dataChangeCallBack(isAllData())
    }
    
    func removeSelectModel(index:IndexPath){
        let tempModel = self.dataSourceModel[index.section][index.row]
        if var array = self.selectData[String(index.section)] {
            if array.contains(tempModel){
                array.removeAll(where: {$0.identifier == tempModel.identifier})
            }
            self.selectData[String(index.section)] = array
        }
        if let header = self.tableView.headerView(forSection: index.section) {
            changeHeaderSelectButton(section: index.section, view: header as! CustomDupHeaderView)
        }
        // 改变导航栏的选择按钮状态
        self.dataChangeCallBack(isAllData())
    }
    // 判断当前数量是不是全部
    func isAllData()->Bool{
        var selectCount = 0
        for (_,value) in self.selectData {
            selectCount += value.count
        }
        
        var allDataCount = 0
        for item in self.dataSourceModel {
            allDataCount += item.count
        }
        if selectCount == allDataCount {
            return true
        }
        return false
    }
    
    // 是否显示预览按钮
    func showPreMergeButton(){
        var show : Bool = false
        for(_,value) in self.selectData {
            // 判断至少有一组且大于2的开始合并
            if value.count >= 2{
                show = true
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            // 如果有且当前是显示的
            if show {
                if self.preButtonShowStatus == false {
                    self.preButtonShowStatus = true
                    UIView.animate(withDuration: 0.1) {
                        // 更新约束
                        self.bottomConstraint?.update(offset: -safeHeight)
                        self.tabBottomConstraint?.update(offset: -safeHeight - 68)
                        self.layoutIfNeeded()
                    }
                }
            }else {
                if self.preButtonShowStatus == true {
                    self.preButtonShowStatus = false
                    UIView.animate(withDuration: 0.1) {
                        // 更新约束
                        self.bottomConstraint?.update(offset: 68)
                        self.tabBottomConstraint?.update(offset: -safeHeight)
                        self.layoutIfNeeded()
                    }
                }
            }
        }
    }
    
    private func removeSingalDataInDataSource()-> [String : [ContactModel]]{
        var tempDic : [String : [ContactModel]] = [:]
        for (key,value) in self.selectData {
            if value.count >= 2{
                tempDic[key] = value
            }
        }
        return tempDic
    }
 
    
}
