//
//  PMFAQController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/16.
//

import UIKit

class PMFAQController: BaseViewController {

    @IBOutlet weak var TableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.TableView.delegate = self
        self.TableView.dataSource = self
        self.TableView.showsVerticalScrollIndicator = false
        self.TableView.showsHorizontalScrollIndicator = false
        self.titleView.model.title = "FAQ"
        self.TableView.register(UINib(nibName: PMFAQCell.id, bundle: nil), forCellReuseIdentifier: PMFAQCell.id)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let file = Bundle.main.bundleURL.appendingPathComponent("PMFAQData.json")
        do{
            let dictData = try Data(contentsOf: file)
            dataSource = try JSONDecoder().decode([FAQDataModel].self, from: dictData)
        }catch{ }
        self.TableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(15)
            make.bottom.equalToSuperview()
            make.top.equalTo(self.titleView.snp.bottom).offset(10)
        }
    }
    
    @IBAction func BackToAction(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    var openSet = -1
    
    var dataSource:[FAQDataModel] = [] {
        didSet {
            self.TableView.reloadData()
        }
    }
}

extension PMFAQController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PMFAQCell.id, for: indexPath) as! PMFAQCell
        cell.isOpen = openSet == indexPath.row
        cell.data = dataSource[indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var indexpaths:[IndexPath] = []
        if openSet == indexPath.row {
            openSet = -1
            indexpaths = [indexPath]
        }else{
            let current = openSet
            openSet = indexPath.row
            indexpaths = [indexPath]
            if current >= 0 {
                indexpaths.append(IndexPath(row: current, section: 0))
            }
        }
        tableView.reloadRows(at: indexpaths, with: .automatic)
    }
}

struct FAQDataModel : Codable {
    var problem:String
    var answer:String
    var bold:[String]?
    init(problem: String, answer: String) {
        self.problem = problem
        self.answer = answer
    }
}
