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

import UIKit

public struct R_FinishPartsCart {
    static func router(datas:[M_FinishFeesCategory.FeeItem], callBack:(([M_FinishFeesCategory.FeeItem], Bool)->Void)?) {
        let vc = FinishPartsCartVc.cd_storyboard("FinishOrder", from: "FinishPartsCartVc") as! FinishPartsCartVc
        vc.modalTransitionStyle = .crossDissolve
        vc.modalPresentationStyle = .custom
        vc.vm.datas = datas
        vc.callBack = callBack
        CD.present(vc, animated: false)
    }
}

class FinishPartsCartVc: UIViewController {

    @IBOutlet weak var btn_sure: UIButton!
    @IBOutlet weak var lab_clean: UILabel!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var height_table: NSLayoutConstraint!
    @IBOutlet weak var lab_price: UILabel!
    @IBOutlet weak var lab_price_d: UILabel!
    @IBOutlet weak var lab_title: UILabel!
    
    @IBOutlet weak var lab_totalTitle: UILabel!
    var callBack:(([M_FinishFeesCategory.FeeItem], Bool)->Void)?
    var vm = FinishPartsCartVm()
    override func viewDidLoad() {
        super.viewDidLoad()

        btn_sure.setTitle("确认".languageString(), for: .normal)
        lab_clean.text = "清空".languageString()
        lab_totalTitle.text = "合计".languageString()+":"
        btn_sure.setTitle("确认".languageString(), for: .normal)
        makeUI()
    }
    

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        bgView.addCorner(conrners: [.topLeft, .topRight], radius: 8)
    }
    
    func makeUI() {
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        
        vm.reloadData = {[weak self] in
            guard let weakSelf = self else { return }
            let hh = CGFloat(weakSelf.vm.datas.count * 80 + 8)
            if weakSelf.vm.datas.count < 3 {
                weakSelf.height_table.constant = 168
            }else if hh <= CD.screenH - 200 {
                weakSelf.height_table.constant = hh
            }else{
                weakSelf.height_table.constant = CD.screenH - 200
            }
            weakSelf.tableView.reloadData()
            weakSelf.setBottomData()
        }
        vm.makeForm()
        setBottomData()
    }
    
    @IBAction func close(_ sender: UIButton) {
        self.dismiss(animated: false)
    }

    @IBAction func clearCart(_ sender: UIButton) {
        guard !vm.datas.isEmpty else {
            return
        }
        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.vm.datas.removeAll()
            self.vm.makeForm()
            self.setBottomData()
        }))
        CD.present(alertController)
    }
    
    @IBAction func sure(_ sender: UIButton) {
        self.dismiss(animated: false) {
            if !self.vm.datas.isEmpty {
                self.callBack?(self.vm.datas, true)
            }
        }
    }
    
    func setBottomData() {
        var count = 0
        var amount:CGFloat = 0
        for item in vm.datas {
            count += item.qty
            amount += item.price.floatValue() * CGFloat(item.qty)
        }
        let amountStr = String(format: "%.2f", amount)
        let arr = amountStr.components(separatedBy: ".")
        lab_price.cd.text("\(arr.first!).")
        lab_price_d.cd.text(arr.last)
        
        lab_title.cd.text("已选产品".languageString()+"（\(count)）")
        
        callBack?(self.vm.datas, false)
    }
}
extension FinishPartsCartVc: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.forms.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellVM = vm.forms[indexPath.row]
        let cellIdentifier = cellVM.cellId.isEmpty ? String(describing: cellVM.cellClass) : cellVM.cellId
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            let bundle = Bundle.main.path(forResource:cellIdentifier, ofType: "nib")
            if bundle == nil{
                tableView.register(cellVM.cellClass, forCellReuseIdentifier: cellIdentifier)
            }else{
                let cellNib = UINib(nibName:cellIdentifier, bundle: nil)
                tableView.register(cellNib, forCellReuseIdentifier: cellIdentifier)
            }
            cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        }
        
        guard let endCell = cell else {
            fatalError("没有找到标识为：\(cellIdentifier)的Cell")
        }
        cellVM.bind(endCell)
        return endCell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.init(hexString: "f8f8f8")
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellVM = vm.forms[indexPath.row]
        return cellVM.frameH
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellVM = vm.forms[indexPath.row]
        cellVM.tapBlock?()
    }
}
