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

import UIKit

class PMFAQCell: UITableViewCell {

    static let id = "PMFAQCell"
    var callblock:(()->Void) = {}
    
    @IBOutlet weak var PMFAQOpen: UIButton!
    @IBOutlet weak var problem: UILabel!
    @IBOutlet weak var anwser: UILabel!
    var isOpen:Bool = false
    
    @IBOutlet weak var topContraint: NSLayoutConstraint!
    
    @IBAction func OpenActions(_ sender: Any) {
        callblock()
    }
    
    var data:FAQDataModel? {
        didSet{
            problem.text = data?.problem
            if isOpen {
                self.topContraint.constant = 16;
                PMFAQOpen.isSelected = true
                anwser.attributedText = addattribed()
            }else{
                self.topContraint.constant = 0;
                PMFAQOpen.isSelected = false
                anwser.attributedText = nil
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    private func addattribed() -> NSMutableAttributedString {
        let mutableText = NSMutableAttributedString(string: data?.answer ?? "")
        mutableText.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14, weight: .regular)], range: NSRange(location: 0, length: mutableText.length))
        let rangs = data?.bold ?? []
        let famat = NSSet(array: rangs)
        for text in famat {
            if let rang = mutableText.string.range(of: text as! String) {
                let startIndex = rang.lowerBound
                let endIndex = rang.upperBound
                let start = mutableText.string.distance(from: mutableText.string.startIndex, to: startIndex)
                let end = mutableText.string.distance(from: mutableText.string.startIndex, to: endIndex)
                if end < (data?.answer.count ?? 0) {
                    mutableText.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14, weight: .bold)], range: NSRange(location: start, length: end - start))
                }
            }
        }
        return mutableText
    }
    
    
}
