//
//  MPPositive_SearchViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/19.
//

import UIKit

class MPPositive_SearchViewController: MPPositive_BaseViewController {
    //背景图片
    private lazy var bgImageView:UIImageView = {
        let imageView:UIImageView = .init(image: .init(named: "B_Home_BG'bg"))
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    //顶部搜索textField
    private lazy var searchTextField:UITextField = {
        let textField = UITextField()
        textField.delegate = self
        textField.font = .systemFont(ofSize: 14*width, weight: .regular)
        textField.textColor = .white
        //设置一个富文本占位符
        let attributedText = NSAttributedString(string: "Search songs,artists,playlists", attributes: [.font:UIFont.systemFont(ofSize: 14*width, weight: .regular), .foregroundColor:UIColor(hex: "#666666")])
        textField.attributedPlaceholder = attributedText
        return textField
    }()
    //搜索建议tableView
    private lazy var suggestionsTableView:UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .init(hex: "#151718")
        tableView.separatorStyle = .none
        //设置一个边框
        tableView.layer.borderWidth = 1*width
        tableView.layer.borderColor = UIColor(hex: "#FFFFFF", alpha: 0.35).cgColor
        tableView.layer.masksToBounds = true
        tableView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        tableView.layer.cornerRadius = 10*width
        
        tableView.rowHeight = 60*width
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(MPPositive_SearchSuggestionItemTableViewCell.self, forCellReuseIdentifier: MPPositive_SearchSuggestionItemTableViewCellID)
        tableView.register(MPPositive_SearchSuggestionListTableViewCell.self, forCellReuseIdentifier: MPPositive_SearchSuggestionListTableViewCellID)
        return tableView
    }()
    private let MPPositive_SearchSuggestionItemTableViewCellID = "MPPositive_SearchSuggestionItemTableViewCell"
    private let MPPositive_SearchSuggestionListTableViewCellID = "MPPositive_SearchSuggestionListTableViewCell"
    //对用户展示的搜索建议组
    private var suggestions:[[MPPositive_SearchSuggestionItemModel]]!{
        willSet{
            DispatchQueue.main.async {
                [weak self] in
                guard let self = self else {return}
                if newValue != nil {
                    //搜索到了
                    var count:Int = 0
                    newValue.forEach { items in
                        count += items.count
                    }
                    suggestionsTableView.isHidden = false
                    suggestionsTableView.snp.updateConstraints { make in
                        make.height.equalTo(CGFloat(count*60)*width)
                    }
                }else {
                    //没有搜索到
                    suggestionsTableView.isHidden = true
                    suggestionsTableView.snp.updateConstraints { make in
                        make.height.equalTo(0)
                    }
                }
                suggestionsTableView.reloadData()
            }
        }
    }
    //搜索限定计时器
    private var debounceTimer: Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        setTitle("")
        configure()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        searchTextField.text = ""
        suggestionsTableView.isHidden = true
        suggestions = nil
    }
    //配置
    private func configure() {
        let searchView = createSearchView()
        navView.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.width.equalTo(339*width)
            make.height.equalTo(32*width)
            make.center.equalToSuperview()
        }
        view.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            make.height.equalTo(981*width)
        }
        view.addSubview(suggestionsTableView)
        suggestionsTableView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom)
            make.left.equalTo(searchView.snp.left).offset(16*width)
            make.right.equalTo(searchView.snp.right).offset(-16*width)
            make.height.equalTo(240*width)
        }
        suggestionsTableView.isHidden = true
    }
    //生成一个顶部搜索框
    private func createSearchView() -> UIView{
        let searchView:UIView = UIView()
        searchView.backgroundColor = .init(hex: "#212121")
        searchView.isUserInteractionEnabled = true
        searchView.layer.masksToBounds = true
        searchView.layer.cornerRadius = 16*width
        //添加一个icon
        let iconImageView = UIImageView(image: .init(named: "B_Seach"))
        searchView.addSubview(iconImageView)
        iconImageView.snp.makeConstraints { make in
            make.height.width.equalTo(16*width)
            make.left.equalToSuperview().offset(16*width)
            make.centerY.equalToSuperview()
        }
        //添加textField
        searchView.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(iconImageView.snp.right).offset(8*width)
            make.right.equalToSuperview().offset(-16*width)
        }
        return searchView
    }
    
}
//MARK: - textField
extension MPPositive_SearchViewController:UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        guard text.count <= 30 else {
            return false
        }
        if text.isEmpty {
            suggestions = nil
        }else {
            //触发网络请求
            loadSearchSuggestions(text)
        }
        return true
    }
    //避免重复请求
    private func cancelDebounceTimer() {
        debounceTimer?.invalidate()
        debounceTimer = nil
    }
    //当用户输入文本通过后进行检索
    private func loadSearchSuggestions(_ text:String) {
        cancelDebounceTimer()
        //停止输入0.8秒后调用
        debounceTimer = Timer.scheduledTimer(withTimeInterval: 0.8, repeats: false) { [weak self] _ in
            self?.fetchSearchSuggestions(text)
        }
    }
    //获取建议组
    private func fetchSearchSuggestions(_ text:String) {
        MP_NetWorkManager.shared.requestSearchSuggestions(text) { [weak self] (result) in
            self?.suggestions = result
        }
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //判断textField是否存在文本
        if let text = textField.text, text.isEmpty != true {
            //用户输入了文本
            let showVC = MPPositive_SearchResultShowViewController()
            
            navigationController?.pushViewController(showVC, animated: true)
            return true
        }else {
            return false
        }
    }
}
//MARK: - tableView
extension MPPositive_SearchViewController:UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return suggestions != nil ? suggestions.count:0
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return suggestions != nil ? suggestions[section].count:0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if suggestions[indexPath.section][indexPath.row].reviewUrls != nil {
            let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_SearchSuggestionListTableViewCellID, for: indexPath) as! MPPositive_SearchSuggestionListTableViewCell
            cell.item = suggestions[indexPath.section][indexPath.row]
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: MPPositive_SearchSuggestionItemTableViewCellID, for: indexPath) as! MPPositive_SearchSuggestionItemTableViewCell
            cell.item = suggestions[indexPath.section][indexPath.row]
            return cell
        }
    }
}
