//
//  OrderApplyPartsVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/18.
//

import UIKit

public struct R_OrderApplyParts {
    static func router(_ orderid: String,_ applyId:String = "", itemId:String, applyPartsMode:String = "1", waitApplyPartsList:[M_OrderPartsInfo.WaitApplyParts] = [], callBack:((Bool)->Void)?) {
        let vc = OrderApplyPartsVc.cd_storyboard("Order", from: "OrderApplyPartsVc") as! OrderApplyPartsVc
        vc.vm.orderId = orderid
        vc.vm.applyId = applyId
        vc.vm.itemId = itemId
        vc.vm.applyPartsMode = applyPartsMode
        vc.vm.model.waitApplyPartsList = waitApplyPartsList
        vc.vm.callBack = callBack
        CD.push(vc)
    }
}

class OrderApplyPartsVc: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var btn_bottom: UIButton!
    @IBOutlet weak var view_btns: UIView!
    @IBOutlet weak var lab_nil: UILabel!
    
    var vm = OrderApplyPartsVm()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        lab_nil.text = "无配件申请记录".languageString()
        btn_bottom.cd.text("保存".languageString())
        makeUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setNavigationBackButton()
        self.title = "申领配件".languageString()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }

    func makeUI() {
        vm.reloadData = {[weak self] in
            guard let weakSelf = self else { return }
//            weakSelf.tableView.cd.isHidden(weakSelf.vm.data.count <= 3)
            weakSelf.tableView.reloadData()
        }

        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        
        if vm.applyPartsMode == "2" {
            setNavigationRightBarutton()
        }else{
            vm.requestData()
        }
        vm.makeForms()
    }
    
    func setNavigationRightBarutton(){
        let rightBtn = UIButton.init(type: .custom)
        rightBtn.setTitle("新增".languageString(), for: .normal)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        rightBtn.addTarget(self, action: #selector(rightBtnAction), for: .touchDown)
        rightBtn.setTitleColor(Config.color.hex("3"), for: .normal)
        rightBtn.titleLabel?.font = Config.font.font(14)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBtn)
    }
    
    @objc func rightBtnAction() {
        R_OrderSelectPart.router(vm.orderId, itemId: vm.itemId, outwarehouseId: "", applyPartsMode: vm.applyPartsMode) { [weak self] (selItes) in
            guard let weakSelf = self else { return }
            let partsIdArr = weakSelf.vm.model.waitApplyPartsList.compactMap({$0.partsId})
            for item in selItes {
                if !partsIdArr.contains(item.partsId) {
                    var m = M_OrderPartsInfo.WaitApplyParts(item.jsonValue())
                    m.pic = item.partsPic
                    m.userPrice = item.userPrice
                    m.qty = item.applyQty
                    weakSelf.vm.model.waitApplyPartsList.append(m)
                }else{
                    for (j, it) in weakSelf.vm.model.waitApplyPartsList.enumerated(){
                        if it.partsId == item.partsId {
                            weakSelf.vm.model.waitApplyPartsList[j].qty = "\(weakSelf.vm.model.waitApplyPartsList[j].qty.intValue() + item.applyQty.intValue())"
                        }
                    }
                }
            }
            weakSelf.vm.makeForms()
        }
    }
    
    @IBAction func clickbutton(_ sender: UIButton) {
        switch vm.applyPartsMode {
        case "1":
            vm.checkData()
        case "2":
            vm.saveWaitPartsApply()
        default:
            vm.checkData()
            break
        }
    }
}

extension OrderApplyPartsVc: 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?()
    }
}


