//
//  Cell_FinishFeesItem.swift
//  VattiCSS
//
//  Created by WZR on 2024/1/4.
//

import UIKit

class Cell_FinishFeesItem: UITableViewCell {
    @IBOutlet weak var lab_title: UILabel!
    @IBOutlet weak var lab_detail: 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!
    @IBOutlet weak var width_qtyView: NSLayoutConstraint!
    
    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_FinishFeesItem: TCCell_RowCellUpdateProtocol {
    typealias DataSource = (String, String, String, Int)
    typealias ConfigModel = (UIRectCorner, CGFloat)
    
    func row_update(dataSource data: DataSource) {
        lab_title.cd.text(data.0)
        lab_detail.cd.text("\("规格：".languageString())" + data.1)
        lab_price.cd.text(data.2)
        tf_count.cd.text("\(data.3)")
            .isHidden(data.3 < 1)
        view_sub.cd.isHidden(data.3 < 1)
        qty = data.3
        width_qtyView.constant = data.3 < 1 ? 24 : 80
    }
    
    func row_update(config data: ConfigModel) {
        
    }
    
    func row_update(callBack block: TCRowCallBack?) {
        self.callBack = block
    }
}
