//
//  OrderSelectPartVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/20.
//

import UIKit
import MJRefresh

public struct R_OrderSelectPart {
    static func router(_ orderid: String, itemId:String, outwarehouseId:String, applyPartsMode:String = "", callBack:(([M_OrderPartsInfo.Parts])->())?) {
        let vc = OrderSelectPartVc.cd_storyboard("Order", from: "OrderSelectPartVc") as! OrderSelectPartVc
        vc.orderId = orderid
        vc.itemId = itemId
        vc.outwarehouseId = outwarehouseId
        vc.vm.applyPartsMode = applyPartsMode
        vc.didSelCallback = callBack
        CD.push(vc)
    }
}

class OrderSelectPartVc: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tf_search: UITextField!
    @IBOutlet weak var btn_code: UIButton!
    @IBOutlet weak var tf_search2: UITextField!
    @IBOutlet weak var btn_code2: UIButton!
    @IBOutlet weak var tf_search3: UITextField!
    @IBOutlet weak var btn_code3: UIButton!
    @IBOutlet weak var btn_submit: UIButton!
    var vm = OrderSelectPartVm()
    //获取数据
    var getDataUrl = "/app/v2/partsDo/searchParts"
//    var searchValue = ""
    var orderId = ""
    var itemId = ""
    var pagenumber = 1
    var pageSize = 10
    var totalpages = 1
    var pagesCount = 0
    var outwarehouseId = ""
    var didSelCallback:(([M_OrderPartsInfo.Parts])->())?
    
    var partsCode = ""
    var partsBarcode = ""
    var prudctBarcode = ""
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
//        searchValue = sender.txt
        switch sender {
        case tf_search:
            partsCode = sender.txt
        case tf_search2:
            partsBarcode = sender.txt
        case tf_search3:
            prudctBarcode = sender.txt
        default:
            break
        }
        self.headerRefresh()
    }
    
    @IBAction func searchOrders(_ sender: UIButton) {
        if tf_search.becomeFirstResponder() {
            tf_search.resignFirstResponder()
        }
        if tf_search2.becomeFirstResponder() {
            tf_search2.resignFirstResponder()
        }
        if tf_search3.becomeFirstResponder() {
            tf_search3.resignFirstResponder()
        }
        let qrVC = QRViewController()
        qrVC.configResultCall {[weak self] code, errorStr in
            guard let weakSelf = self else { return }
            if errorStr != "" {
                CD.visibleVC?.promptInformation(errorStr ?? "扫码出错了~".languageString())
                return
            }
//            self.searchValue = code ?? ""
            let result = code ?? ""
            switch sender {
            case weakSelf.btn_code2:
                weakSelf.tf_search2.text = result
                weakSelf.partsBarcode = result
            case weakSelf.btn_code3:
                weakSelf.tf_search3.text = result
                weakSelf.prudctBarcode = result
            default:
                break
            }
            weakSelf.headerRefresh()
        }
        let qrNavigationC = TWNavigationVc(rootViewController: qrVC)
        qrNavigationC.modalPresentationStyle = .overFullScreen
        qrNavigationC.modalTransitionStyle = .crossDissolve
        CD.visibleVC?.present(qrNavigationC, animated: true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "选择配件".languageString()
        tf_search.placeholder = "根据配件编码或名称查询".languageString()
        tf_search2.placeholder = "根据配件条码查询".languageString()
        tf_search3.placeholder = "根据产品条码查询".languageString()
        btn_code2.cd.text(" " + "扫码".languageString())
        btn_code3.cd.text(" " + "扫码".languageString())
        btn_submit.cd.text("确定".languageString())
        setNavigationBackButton()
        configTableView()
        
        self.requestData()
    }
    
    func configTableView() {
        self.btn_code.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0)
        self.tableView.backgroundColor = UIColor(hexString: "f8f8f8")
        self.view.backgroundColor = UIColor(hexString: "f8f8f8")
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        vm.callback = {
            self.tableView.reloadData()
        }
        
        let header = MJRefreshNormalHeader()
        header.stateLabel.textColor = UIColor(hexString: "999999")
        let footer = MJRefreshAutoNormalFooter()
        footer.stateLabel.textColor = UIColor(hexString: "999999")
        footer.isOnlyRefreshPerDrag = true
        
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        tableView.mj_header = header
        tableView.mj_footer = footer
    }
    
    func showNoMoreData(_ datas:[[String:Any]]){
        if pageSize > datas.count{
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }else{
            self.tableView.mj_footer.resetNoMoreData()
        }
    }

    @IBAction func sureSelect(_ sender: UIButton) {
        let selArr = vm.itemArr.filter({$0.selected})
        guard !selArr.isEmpty else {
            hud_info("请至少选择一个配件！".languageString())
            return
        }
        didSelCallback?(selArr)
        self.navigationController?.popViewController(animated: true)
    }
}


//网络请求
extension OrderSelectPartVc{
    //mark refresh
    @objc func headerRefresh(){
        pagenumber = 1
        requestData()
    }
    
    @objc func footerRefresh(){
        if pagesCount == pageSize{
            pagenumber = pagenumber + 1
            requestData()
        }else{
            self.tableView.mj_footer.endRefreshing()
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }
    }
    
    
    func requestData(){
        
        var paramDict = [String:Any]()
//        if searchValue != "" {
//            paramDict["searchKey"] = searchValue
//        }
        paramDict["partsCode"] = partsCode
        paramDict["partsBarcode"] = partsBarcode
        paramDict["barcode"] = prudctBarcode
        paramDict["orderId"] = orderId
        paramDict["itemId"] = itemId
        if !outwarehouseId.isEmpty {
            paramDict["outwarehouseId"] = outwarehouseId
        }
        paramDict["pageNumber"] = pagenumber
        paramDict["pageSize"] = pageSize
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: getDataUrl,andParam: paramDict)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_header.endRefreshing()
            
            if let data = result["data"] as? [String:Any] {
                if let datas = data["partsList"] as? [[String:Any]] {
                    let ms = datas.compactMap { item in
                        M_OrderPartsInfo.Parts(josn: item)
                    }
                    if weakSelf.pagenumber == 1 {
                        weakSelf.vm.itemArr = ms
                    }else{
                        weakSelf.vm.itemArr.append(contentsOf: ms)
                    }
                    weakSelf.pagesCount = ms.count
                    weakSelf.showNoMoreData(datas)
                    weakSelf.vm.makeForms()
                }
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {[weak self] (errorTag,errorStr) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_header.endRefreshing()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
}

// MARK: - Table view data source
extension OrderSelectPartVc: 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?()
    }
}
