//
//  FinishFeesCategoryVc.swift
//  VattiCSS
//
//  Created by WZR on 2024/1/3.
//

import UIKit

public struct R_FeesCategory {
    static func router(_ orderid: String, feeType:Int, guaranteeType:String, itemCategoryId:String, serviceTypeId:String, itemId:String, callback: (([[String:Any]])->Void)?) {
        let vc = FinishFeesCategoryVc.cd_storyboard("FinishOrder", from: "FinishFeesCategoryVc") as! FinishFeesCategoryVc
        vc.vm.orderId = orderid
        vc.vm.feeType = feeType
        vc.vm.guaranteeType = guaranteeType
        vc.vm.itemCategoryId = itemCategoryId
        vc.vm.serviceTypeId = serviceTypeId
        vc.vm.itemId = itemId
        vc.callback = callback
        CD.push(vc)
    }
}

class FinishFeesCategoryVc: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var view_top: UIView!
    @IBOutlet weak var stack_table: UIStackView!
    @IBOutlet weak var view_bottom: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tf_search: UITextField!
    @IBOutlet weak var btn_showCart: UIButton!
    @IBOutlet weak var view_num: UIView!
    @IBOutlet weak var lab_num: UILabel!
    @IBOutlet weak var lab_amount: UILabel!
    @IBOutlet weak var lab_amount2: UILabel!
    @IBOutlet weak var btn_ok: UIButton!
    @IBOutlet weak var feesTableView: UITableView!
    
    @IBOutlet weak var lab_totalTitle: UILabel!
    
    var vm = FinishFeesCategoryVm()
    var delegateData:CD_TableViewDelegateDataSource?
    var callback: (([[String:Any]])->Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "收费项目".languageString()
        setNavigationBackButton()
        
        btn_ok.setTitle("确认".languageString(), for: .normal)
        tf_search.placeholder = "请输入项目名称".languageString()
        lab_totalTitle.text = "合计".languageString()+":"
        
        makeUI()
        makeRefresh()
    }
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
        if vm.searchKey != sender.text! {
            vm.searchKey = sender.text!
            vm.refreshFeeSubject()
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        tf_search.resignFirstResponder()
        return true
    }
    
    @IBAction func clickButton(_ sender: UIButton) {
        switch sender {
        case btn_showCart:
            R_FinishPartsCart.router(datas: vm.selFeesList) {[weak self] (list,isBack)  in
                guard let weakSelf = self else {return}
                weakSelf.vm.selFeesList = list
                weakSelf.vm.reloadFeesList()
                if isBack {
                    let arr = weakSelf.vm.selFeesList.compactMap({$0.jsonValue()})
                    weakSelf.callback?(arr)
                    CD.pop()
                }
            }
        case btn_ok:
            guard !vm.selFeesList.isEmpty else {
                hud_info("请至少选择一个项目！".languageString())
                return
            }
            let arr = vm.selFeesList.compactMap({$0.jsonValue()})
            callback?(arr)
            CD.pop()
        default:
            break
        }
    }
    
    
}

extension FinishFeesCategoryVc {
    func makeUI() {
        tf_search.delegate = self
        tf_search.cd.tint(UIColor.cd_hex("#478BFF"))
        
        self.view.bringSubviewToFront(tableView)
        self.view.bringSubviewToFront(view_top)
        self.view.bringSubviewToFront(view_bottom)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.estimatedRowHeight = 44
            tableView.estimatedSectionHeaderHeight = 0
            tableView.estimatedSectionFooterHeight = 0
        } else {
            
        }
        delegateData = CD_TableViewDelegateDataSource(vm)
        tableView.cd
            .delegate(delegateData)
            .dataSource(delegateData)
            .shadow(Config.color.line_1)
            .shadow(CGSize(w: 0, h: 0))
            .shadow(CGFloat(4.0))
            .shadow(Float(1))
            .clips(false)
        
        if #available(iOS 11.0, *) {
            feesTableView.contentInsetAdjustmentBehavior = .never
            feesTableView.estimatedRowHeight = 44
            feesTableView.estimatedSectionHeaderHeight = 0
            feesTableView.estimatedSectionFooterHeight = 0
        } else {
            
        }
        feesTableView.cd.background(.white)
    }

    func makeRefresh() {
        vm.reloadData = { [weak self] in
            self?.tableView.reloadData()
        }
        vm.reloadFeesData = { [weak self] in
            self?.feesTableView.reloadData()
            self?.setBottomData()
        }
        vm.requestList()
    }
    
    func setBottomData() {
        view_num.cd.isHidden(vm.selFeesList.isEmpty)
        var count = 0
        var amount:CGFloat = 0
        for item in vm.selFeesList {
            count += item.qty
            amount += item.price.floatValue() * CGFloat(item.qty)
        }
        lab_num.cd.text("\(count)")
        let amountStr = String(format: "%.2f", amount)
        let arr = amountStr.components(separatedBy: ".")
        lab_amount.cd.text("\(arr.first!).")
        lab_amount2.cd.text(arr.last)
    }
    
}

extension FinishFeesCategoryVc: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.cellForms.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellVM = vm.cellForms[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.cellForms[indexPath.row]
        return cellVM.frameH
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellVM = vm.cellForms[indexPath.row]
        cellVM.tapBlock?()
    }
}
