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

import Foundation

class FinishPartsCartVm {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    var datas:[M_FinishFeesCategory.FeeItem] = []
    
    func makeForm() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
        for (i,item) in datas.enumerated() {
            newForms += makeFeesItemCellForm(titleStr: item.subjectName, price: "¥\(item.price)\(isEnglish() ? "" : "元")/\(item.unit)", qty: item.qty, idx: i)
            newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
        }
        forms = newForms
        reloadData?()
    }
    
    func makeLineCellForm(leftW:CGFloat = 0, rightW:CGFloat = 0, bgColor:UIColor = .clear, backGroundColor:UIColor = .clear, corners:(CGFloat, CACornerMask) = (0, []), height:CGFloat = 12, idx:Int = -99) -> [TCCellBaseProtocol] {
        let uiConfigModel = TCFormCellConfigModel.defaultModel()
            .bgColor(backGroundColor)
            .cornerMask(corners.1)
            .cornerRadius(corners.0)
        let rowCell = TCFormCellModel<TCLineCell>.init(data: (leftW, rightW, bgColor), config: uiConfigModel, frameh: height)
        return [rowCell]
    }
    
    func makeFeesItemCellForm(titleStr:String, price:String, qty:Int, idx:Int) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<Cell_FinishPartsCart>.init(data: (titleStr, price, qty), frameh: 72, callBack: {[weak self] back in
            guard let weakSelf = self else { return }
            if let qty = back as? Int {
                if qty < 1 {
                    weakSelf.deleteItem(idx: idx)
                }else{
                    weakSelf.datas[idx].qty = qty
                }
                weakSelf.makeForm()
            }
        })
        return [rowCell]
    }
}

extension FinishPartsCartVm {
    func deleteItem(idx:Int) {
        let alertController = UIAlertController.init(title: "", message: "是否确定删除该产品？".languageString(), preferredStyle: .alert)
        alertController.addAction(UIAlertAction.init(title: "取消".languageString(), style: .cancel))
        alertController.addAction(UIAlertAction.init(title: "确定".languageString(), style: .default, handler: { (action) in
            self.datas.remove(at: idx)
            self.makeForm()
        }))
        CD.present(alertController)
    }
}

