//
//  PartsApplyOperationQuantityCell.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/23.
//

import UIKit

class PartsApplyOperationQuantityCell: UITableViewCell, UITextFieldDelegate {
    @IBOutlet weak var bgView: UIView!
    
    @IBOutlet weak var btn_sub: UIButton!
    @IBOutlet weak var btn_add: UIButton!
    @IBOutlet weak var tf_qty: UITextField!
    @IBOutlet weak var lab_txt: UILabel!
    
    var callBack: TCRowCallBack?
    var corner:(CGFloat, UIRectCorner) = (0,[])
    
    var maxQty = 0
    var qty = 0
    
    var txt = ""
    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
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        bgView.makeRadius(value: corner.0, type: corner.1)
    }
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
        if sender.text!.intValue() < 0 {
            qty = 0
        }else if sender.text!.intValue() > maxQty{
            qty = maxQty
        }else{
            qty = sender.text!.intValue()
        }
        tf_qty.text = "\(qty)"
        callBack?(qty)
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        switch sender {
        case btn_add:
            guard qty < maxQty else {
                return
            }
            qty += 1
        case btn_sub:
            guard qty > 0 else {
                return
            }
            qty -= 1
        default:
            break
        }
        tf_qty.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 PartsApplyOperationQuantityCell: TCCell_RowCellUpdateProtocol {
    typealias DataSource = (String, Int, Int)
    typealias ConfigModel = (CGFloat, UIRectCorner)
    
    func row_update(dataSource data: DataSource) {
        lab_txt.cd.text(data.0)
        qty = data.1
        tf_qty.cd.text("\(qty)")
        maxQty = data.2
    }
    
    func row_update(config data: ConfigModel) {
        corner = data
        bgView.makeRadius(value: data.0, type: data.1)
    }
    
    func row_update(callBack block: TCRowCallBack?) {
        self.callBack = block
    }
}
