//
//  Cell_FinishPartsCart.swift
//  VattiCSS
//
//  Created by WZR on 2024/1/5.
//

import UIKit

class Cell_FinishPartsCart: UITableViewCell {

    @IBOutlet weak var lab_title: UILabel!
    @IBOutlet weak var lab_price: UILabel!
    @IBOutlet weak var view_sub: UIView!
    @IBOutlet weak var view_add: UIView!
    @IBOutlet weak var tf_count: UITextField!
    @IBOutlet weak var btn_sub: UIButton!
    @IBOutlet weak var btn_add: UIButton!
    
    var maxQty = 0
    var qty = 0
    var callBack: TCRowCallBack?
    
    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
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        switch sender {
        case btn_add:
            guard qty < maxQty  || maxQty < 1  else {
                return
            }
            qty += 1
        case btn_sub:
            guard qty > 0 else {
                return
            }
            qty -= 1
        default:
            break
        }
        tf_count.text = "\(qty)"
        callBack?(qty)
    }
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
        if sender.text!.intValue() < 0 {
            qty = 0
        }else if sender.text!.intValue() > maxQty && maxQty > 0 {
            qty = maxQty
        }else{
            qty = sender.text!.intValue()
        }
        tf_count.text = "\(qty)"
        callBack?(qty)
    }
    
    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 Cell_FinishPartsCart: TCCell_RowCellUpdateProtocol {
    typealias DataSource = (String, String, Int)
    typealias ConfigModel = (UIRectCorner, CGFloat)
    
    func row_update(dataSource data: DataSource) {
        lab_title.cd.text(data.0)
        lab_price.cd.text(data.1)
        tf_count.cd.text("\(data.2)")
        qty = data.2
    }
    
    func row_update(config data: ConfigModel) {
        
    }
    
    func row_update(callBack block: TCRowCallBack?) {
        self.callBack = block
    }
}
