//
//  OrderPartsPriceCell.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/19.
//

import UIKit

class OrderPartsPriceCell: UITableViewCell, UITextFieldDelegate {
    @IBOutlet weak var btn_sub: UIButton!
    @IBOutlet weak var btn_add: UIButton!
    @IBOutlet weak var tf_qty: UITextField!
    @IBOutlet weak var lab_price: UILabel!
    
    var callBack: TCRowCallBack?
    
    var qty = 1
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        tf_qty.delegate = self
    }

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

        // Configure the view for the selected state
    }
    @IBAction func editingDidEnd(_ sender: UITextField) {
        if sender.text!.intValue() < 1 {
            qty = 1
        }else{
            qty = sender.text!.intValue()
        }
        callBack?(tf_qty.text!)
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        switch sender {
        case btn_add:
            qty += 1
        case btn_sub:
            if qty > 1 {
                qty -= 1
            }else{
                
            }
        default:
            break
        }
        tf_qty.text = "\(qty)"
        callBack?(tf_qty.text!)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.isEmpty {
            return true
        }
        guard checkNum(string) else {
            return false
        }
        return true
    }
    
    func checkNum(_ str:String) -> Bool {
        let regex = "^[0-9]*$"
        let pred = NSPredicate(format: "SELF MATCHES %@", regex)
        if pred.evaluate(with: str) {
            return true
        }else{
            return false
        }
    }
    
    
}
extension OrderPartsPriceCell: TCCell_RowCellUpdateProtocol {
    typealias DataSource = (String, String)
    typealias ConfigModel = Any
    
    func row_update(dataSource data: DataSource) {
        lab_price.cd.text(data.0)
        qty = data.1.intValue() < 1 ? 1 : data.1.intValue()
        tf_qty.cd.text("\(qty)")
    }
    
    func row_update(config data: ConfigModel) {
    }
    
    func row_update(callBack block: TCRowCallBack?) {
        self.callBack = block
    }
}
