//
//  ContactBackUpView.swift
//  PhoneManager
//
//  Created by 赵前 on 2025/4/20.
//

import Foundation
import UIKit

class ContactBackUpNormalView : UIView {
    
    var isClearAllCallBack : ()->Void = {}
    
    var dataSourceModel :  [BackupInfoModel] = []
    
    var dataSourceAllModel : [ContactModel]?
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "Backups"
        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
    }()
    
    private lazy var addButon: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(addBackupAction), for: .touchUpInside)
        button.backgroundColor = .clear
        button.setImage(UIImage(named: "btn_add_contact"), for: .normal)
        return button
    }()
    
    // 懒加载 tableView
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(ContactBackupCell.self, forCellReuseIdentifier: ContactBackupCell.identifier)
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        return tableView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        self.addSubview(self.titleLabel)
        self.addSubview(self.addButon)
        self.addSubview(self.tableView)
        
        
        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.addButon.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15 * RScreenW())
            make.centerY.equalTo(self.titleLabel.snp.centerY)
            make.width.equalTo(28)
            make.height.equalTo(28)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.addButon.snp.bottom).offset(16)
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.right.equalToSuperview().offset(-15 * RScreenW())
            make.bottom.equalToSuperview().offset(-safeHeight)
        }
    }
}


extension ContactBackUpNormalView : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSourceModel.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 74
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 12
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ContactBackupCell.identifier, for: indexPath) as! ContactBackupCell
        let backupInfo = dataSourceModel[indexPath.section]
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd MMM yyyy"
        let dateString = dateFormatter.string(from: backupInfo.backupTime)
        dateFormatter.dateFormat = "HH:mm"
        let timeString = dateFormatter.string(from: backupInfo.backupTime)
        cell.configure(title: dateString, subtitle: "\(backupInfo.contactCount) Contacts", time: timeString)
        return cell
    }
    
    
    func deleteBackupDataFromMemory(){
        let vm = BackupViewModel()
        vm.saveModel(model: self.dataSourceModel) { finished, error in
            if let error = error {
                Print("删除失败，\(error.localizedDescription)")
            }
            DispatchQueue.main.async {
                // 弹框提示成功
                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()
                    }
                }
                // 成功之后给上游发消息
                if self.dataSourceModel.count <= 0 {
                    self.isClearAllCallBack()
                }
                
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = ContactBackupDetailViewController()
        vc.dataSourceModel = self.dataSourceModel[indexPath.section].contacts
        vc.subTitleLabel.text = "\(self.dataSourceModel[indexPath.section].contacts.count) Contacts"
        vc.sortContacts()
        vc.setupCustomIndexView()
        self.responderViewController()?.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc(tableView:trailingSwipeActionsConfigurationForRowAtIndexPath:) func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .destructive, title: nil) { [weak self] (action, view, completionHandler) in
            
            let alertVc = ContactDeleteAlertView()
            alertVc.frame = (self?.responderViewController()?.view.bounds)!
            self?.responderViewController()?.view.addSubview(alertVc)
            alertVc.alpha = 0
            UIView.animate(withDuration: AniDuration - 0.2) {
                alertVc.alpha = 1
            }
            alertVc.sureCallBack = { isSure in
                self?.dataSourceModel.remove(at: indexPath.section)
                // 删除整个部分而不是特定行
                self?.tableView.deleteSections(IndexSet(integer: indexPath.section), with: .automatic)
                // 删除存储的数据
                self?.deleteBackupDataFromMemory()
            }
            completionHandler(true)
        }
        deleteAction.backgroundColor = UIColor(red: 0.92, green: 0.27, blue: 0.27, alpha: 1)
        deleteAction.image = UIImage(named: "ic_delete_email")
        let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
        return configuration
    }
    
    @objc func addBackupAction() {
        let vm = BackupViewModel()
        
        // 判断当前是否有可用的备份数据
        if let data = self.dataSourceAllModel {
            if data.count > 0 {
                vm.backupAllContacts(self.dataSourceAllModel ?? []) { finished, error in
                    DispatchQueue.main.async {
                        let buAlertVc = ContactBackUpCompletedAlertView(frame: (cWindow?.bounds)!)
                        cWindow?.addSubview(buAlertVc)
                        buAlertVc.alpha = 0
                        UIView.animate(withDuration: AniDuration-0.2) {
                            buAlertVc.alpha = 1
                        }
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            UIView.animate(withDuration: AniDuration-0.2) {
                                buAlertVc.alpha = 0
                            } completion: { su in
                                buAlertVc.removeFromSuperview()
                            }
                        }
                        // 再次请求数据 重新刷新页面
                        self.updateData()
                    }
                }
            }else {
                let buAlertVc = ContactBackUpNoDataAlertView(frame: (cWindow?.bounds)!)
                cWindow?.addSubview(buAlertVc)
                buAlertVc.alpha = 0
                UIView.animate(withDuration: AniDuration-0.2) {
                    buAlertVc.alpha = 1
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    UIView.animate(withDuration: AniDuration-0.2) {
                        buAlertVc.alpha = 0
                    } completion: { su in
                        buAlertVc.removeFromSuperview()
                    }
                }
            }
        }else {
            let buAlertVc = ContactBackUpNoDataAlertView(frame: (cWindow?.bounds)!)
            cWindow?.addSubview(buAlertVc)
            buAlertVc.alpha = 0
            UIView.animate(withDuration: AniDuration-0.2) {
                buAlertVc.alpha = 1
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                UIView.animate(withDuration: AniDuration-0.2) {
                    buAlertVc.alpha = 0
                } completion: { su in
                    buAlertVc.removeFromSuperview()
                }
            }
        }
    }
    
    
    func updateData(){
        let vm = BackupViewModel()
        vm.retrieveContactsFromBackup { model, error in
            if let error = error {
                Print("更新数据失败\(error.localizedDescription)")
            }
            DispatchQueue.main.async {
                self.dataSourceModel = model!
                self.tableView.reloadData()
            }
        }
    }
}




class ContactBackupCell: UITableViewCell {
    static let identifier = "ContactBackupCell"
    
    // 懒加载 UI 元素
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 16)
        label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        return label
    }()
    
    private lazy var subtitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        label.textColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
        return label
    }()
    
    private lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12, weight: .regular)
        label.textColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
        label.textAlignment = .right
        return label
    }()
    
    lazy var moreImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_left_setting_grey")
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 0.99, alpha: 1)
        self.clipsToBounds = true
        self.layer.cornerRadius = 12
        self.selectionStyle = .none
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(titleLabel)
        contentView.addSubview(subtitleLabel)
        contentView.addSubview(timeLabel)
        contentView.addSubview(moreImageView)
        
        titleLabel.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(16)
            make.width.equalTo(200)
            make.height.equalTo(22)
        }
        
        subtitleLabel.snp.makeConstraints { make in
            make.top.equalTo(self.titleLabel.snp.bottom).offset(0)
            make.left.equalToSuperview().offset(16)
            make.width.equalTo(200)
            make.height.equalTo(22)
        }
        
        moreImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.width.equalTo(40)
            make.height.equalTo(17)
            make.centerY.equalTo(self.subtitleLabel.snp.centerY)
        }
    }
    
    func configure(title: String, subtitle: String, time: String) {
        titleLabel.text = title
        subtitleLabel.text = subtitle
        timeLabel.text = time
    }
}
