//
//  CustomSheetController.swift
//  SwiftProject
//
//  Created by aaa on 2024/4/3.
//

import Foundation
import UIKit

typealias CustomSheetControllerSelectCallback = (String?)->Void
class CustomSheetController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    lazy var tableView:UITableView? = {
        let table = UITableView(frame: .zero, style: .insetGrouped)
        table.delegate = self
        table.dataSource = self
        table.isScrollEnabled = false
        table.backgroundColor = .clear
        table.register(CustomSheetCell.classForCoder(), forCellReuseIdentifier: kCellIdentifier)
        return table
    }()
    var dataSource:[[String:String]] = []
    let kCellIdentifier = "kkCustomSheetCell"
    var selectCallback:CustomSheetControllerSelectCallback?
    var selectText = ""
    deinit {
        print("custom sheet controller.....deinit")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(r: 20, g: 20, b: 20, a: 0.2)
        
        let fview = UIView()
        fview.backgroundColor = .clear
        self.view.addSubview(fview)
        fview.snp.makeConstraints { make in
            make.left.top.right.bottom.equalToSuperview()
        }
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapGuester(sender: )))
        fview.addGestureRecognizer(tap)
        
        self.view.addSubview(tableView!)
        tableView?.snp.makeConstraints({ make in
            make.left.right.equalToSuperview()
//            make.height.equalTo(0)
            make.height.equalTo(self.getHeight())
            make.bottom.equalToSuperview().offset(self.getHeight())
        })
        
        
        self.view.layoutIfNeeded()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIView.animate(withDuration: 0.25) {[weak self] in
            self?.tableView?.snp.updateConstraints({ make in
                make.bottom.equalToSuperview().offset(0)
            })
            self?.view.layoutIfNeeded()
        } completion: { finish in
            
        }
        
        tableView?.reloadData()
    }
    
    func setData(data:[[String:String]],callback:CustomSheetControllerSelectCallback?) {
        dataSource.removeAll()
        dataSource.append(contentsOf: data)
        
        selectCallback = callback
    }
    
    func getHeight() -> CGFloat {
        var height:CGFloat = 0.0
        height = CGFloat(dataSource.count) * 56
        height = height + 56 + 10 + 70
        return height
    }
    
    func presentController(vc:UIViewController) {
        vc.modalPresentationStyle = UIModalPresentationStyle.popover
//        vc.modalTransitionStyle = UIModalTransitionStyle.coverVertical
        vc.present(self, animated: false)
    }
    
    @objc func tapGuester(sender:UITapGestureRecognizer){
        self.dismissVC()
    }
    
    func dismissVC() {
        UIView.animate(withDuration: 0.25) {[weak self] in
            if let weakSelf = self {
                weakSelf.view.backgroundColor = UIColor(r: 20, g: 20, b: 20, a: 0)
                if let tb = weakSelf.tableView {
                    tb.snp.updateConstraints{ make in
                        make.bottom.equalToSuperview().offset(tb.bounds.height)
                    }
                }
            }
            self?.view.layoutIfNeeded()
            
        } completion: {[weak self] result in
            self?.dismiss(animated: false)
            if let sc = self?.selectCallback {
                sc(self?.selectText)
            }
        }
    }
    
    
    //MARK: - UITableViewDataSource,UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return dataSource.count
        }
        return 1
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier, for: indexPath) as! CustomSheetCell
        if indexPath.section == 0 {
            let data = dataSource[indexPath.row]
            cell.setCData(data)
        }
        else {
            cell.setCData(["text":NSLocalizedString("取消", comment: "")])
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {//非取消按钮
            let data = dataSource[indexPath.row]
            selectText = data["text"] ?? ""
        }
        
        self.dismissVC()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 8.0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56
    }
}
