//
//  YHSelectCountryViewController.swift
//  galaxy
//
//  Created by EDY on 2024/1/30.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHSelectCountryViewController: YHBaseViewController {
    var searchView: UITextField!
    var flagLabel: UILabel!
    var tableView: UITableView!
    var collectionView: UICollectionView!
    var hotDataSource = ["中国-China","中国香港-Hong Kong","中国澳门-Macau","中国台湾-Taiwan","新加坡-Singapore","澳大利亚-Australia","美国-United States"]
    var searchDataSource: [YHCountryMessage]?
    var viewModel: YHSelectCountryViewModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "国家/地区"
        viewModel = YHSelectCountryViewModel()
        setView()
        getData()
    }
    
    func getData() {
        tableView.reloadData()
        
    }
    
    func setView() {
        view.backgroundColor = .white
        searchView = {
            let searchBar = UITextField()
            searchBar.placeholder = "搜索国家/地区"
            searchBar.backgroundColor = UIColor(hex: 0xf8f9fb)
            searchBar.keyboardType = .default
            searchBar.delegate = self
            searchBar.layer.cornerRadius = 21
            searchBar.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 16, height: 42))
            searchBar.leftViewMode = .always
            return searchBar
        }()
        view.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 16)
            make.height.equalTo(42)
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }
        
        tableView = {
            let tableView = UITableView(frame:.zero, style:.plain)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHCountryTableViewCell.self)
            tableView.isHidden = true
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 78)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.equalTo(view)
        }
        
        flagLabel = {
            let label = UILabel()
            label.text = "热门国家/地区"
            label.textColor = UIColor(hex: 0x222222)
            label.font = kFont(size: 14)
            return label
        }()
        view.addSubview(flagLabel)
        flagLabel.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 78)
            make.left.equalTo(21)
            make.height.equalTo(20)
        }
        
        collectionView = {
            let layout = UICollectionViewFlowLayout()
            layout.minimumInteritemSpacing = 12 // 设置水平间距
            layout.minimumLineSpacing = 16 // 设置垂直间距
            layout.scrollDirection = .vertical
            // 初始化UICollectionView对象
            let collection = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
            collection.dataSource = self
            collection.delegate = self
            
            // 注册自定义单元格类型
            collection.register(cellWithClass: YHCountryCollectionViewCell.self)
            return collection
        }()
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 114)
            make.left.equalTo(21)
            make.right.equalTo(-21)
            make.bottom.equalToSuperview()
        }
    }
}

extension YHSelectCountryViewController: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        if textField.text == "" {
            tableView.isHidden = true
            flagLabel.isHidden = false
            collectionView.isHidden = false
        } else {
            viewModel?.requestCountry(textField.text ?? "") { [weak self] success, error in
                guard let self = self else { return }
                self.searchDataSource = success as? [YHCountryMessage]
                self.tableView.isHidden = false
                self.flagLabel.isHidden = true
                self.collectionView.isHidden = true
                self.tableView.reloadData()
            }
        }
    }
}

extension YHSelectCountryViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchDataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHCountryTableViewCell.self)
        let cn = searchDataSource?[indexPath.row].name_cn ?? ""
        let en = searchDataSource?[indexPath.row].name_en ?? ""
        cell.titleLabel.text = cn + en
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
}

extension YHSelectCountryViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return hotDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let collectionCell = collectionView.dequeueReusableCell(withClass: YHCountryCollectionViewCell.self, for: indexPath)
        collectionCell.label.text = hotDataSource[indexPath.row]
        return collectionCell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let string = hotDataSource[indexPath.row]
        let size = (string as NSString).size(withAttributes: [NSAttributedString.Key.font : kFont(size: 13)])
        return CGSize(width: size.width + 25, height: 32) // 这里可以根据需求设置不同的尺寸
    }
    
}

class YHCountryCollectionViewCell: UICollectionViewCell {
    var label: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpView() {
        label = {
            let view = UILabel()
            view.textAlignment = .center
            view.font = kFont(size: 13)
            view.textColor = UIColor(hex: 0x222222)
            view.backgroundColor = UIColor(hex: 0xf8f9fb)
            view.layer.masksToBounds = true
            view.layer.cornerRadius = 16
            return view
        }()
        contentView.addSubview(label)
        label.snp.makeConstraints { make in
            make.top.bottom.right.left.equalToSuperview()
        }
    }
}

class YHCountryTableViewCell: UITableViewCell {
    var titleLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        titleLabel = {
            let label = UILabel()
            label.font = kFont(size: 13)
            label.textColor = UIColor(hex:0x222222)
            return label
        }()
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.centerY.equalToSuperview()
            make.height.equalTo(20)
        }
    }
}

