//
//  FinishOrderSelectPartVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/9/11.
//

import UIKit
import MJRefresh

class FinishOrderSelectPartVc: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tf_search: UITextField!
    @IBOutlet weak var btn_code: UIButton!
    @IBOutlet weak var btn_next: UIButton!
    
    @IBOutlet weak var tf_partCode: UITextField!
    @IBOutlet weak var tf_itemCode: UITextField!
    @IBOutlet weak var btn_itemCode: UIButton!
    
    
    lazy var showExoloreButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("爆炸图".languageString(), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor(hexString: "#478BFF"), for: .normal)
        btn.addTarget(self, action: #selector(showExplodedView(sender: )), for: .touchUpInside)
        return btn
    }()
    
    var vm = FinishOrderSelectPartVm()
    //获取数据
    var getDataUrl = "app/v2/orderFinishDo/searchParts"
    var orderId = ""
    var itemId = ""
    var pagenumber = 1
    var pageSize = 10
    var totalpages = 1
    
    //搜索参数
    var barcode = "" //产品关联条码
    var searchType = "0" //0:新件查询 1:旧件查询
    var partsBarcode = "" //配件条码
    var partsCode = "" //配件编码
    
    var code1 = ""//完工条码一
    
    var isSelectedOld = false
    
    var didSelCallback:((M_FinishOrder.M_Part)->())?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        btn_next.setTitle("确定".languageString(), for: .normal)
        btn_code.setTitle("扫码".languageString(), for: .normal)
        btn_itemCode.setTitle("扫码".languageString(), for: .normal)
        
        tf_search.placeholder = "根据配件编码或名称查询".languageString()
        tf_itemCode.placeholder = "根据配件条码查询".languageString()
        tf_partCode.placeholder = "根据产品条码查询".languageString()
    }
    
    
    //配件条码
    @IBAction func editingDidEnd(_ sender: UITextField) {
        partsBarcode = sender.txt
        self.headerRefresh()
    }
    
    //配件条码
    @IBAction func partCodeEditingDidEnd(_ sender: UITextField) {
        partsCode = sender.txt
        self.headerRefresh()
    }
    
    //产品条码
    @IBAction func itemCodeEditingDidEnd(_ sender: UITextField) {
        barcode = sender.txt
        self.headerRefresh()
    }
    
    @IBAction func itemCodeScanAction(_ sender: UIButton) {
        let qrVC = QRViewController()
        qrVC.configResultCall { code, errorStr in
            if errorStr != "" {
                CD.visibleVC?.promptInformation(errorStr ?? "扫码出错了~".languageString())
                return
            }
            self.barcode = code ?? ""
            self.tf_itemCode.text = self.barcode
            self.headerRefresh()
        }
        let qrNavigationC = TWNavigationVc(rootViewController: qrVC)
        qrNavigationC.modalPresentationStyle = .overFullScreen
        qrNavigationC.modalTransitionStyle = .crossDissolve
        CD.visibleVC?.present(qrNavigationC, animated: true, completion: nil)
    }
    
    
    @IBAction func nextAction(_ sender: UIButton) {
        let selPartArr = self.vm.itemArr.filter({$0.selected == true})
        if selPartArr.count == 0{
            SVProgressHUD.showError(withStatus: "请选择".languageString()+"配件".languageString())
            return
        }
        self.didSelCallback?(selPartArr[0])
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func showExoloreButtonAction(){
        var paramDict = [String:Any]()
  
        paramDict["barcode"] = partsBarcode
        paramDict["orderId"] = orderId
        paramDict["itemId"] = itemId
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/getExplodedView",andParam: paramDict)
        cNet.successCall = { [weak self] (result) in
            SVProgressHUD.dismiss()
            guard let weakSelf = self else { return }
            
            if let data = result["data"] as? [String:Any] {
                let explodedViewUrl = kGetServerPicUrl(data.stringValue(forKey: "ExplodedView"))
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    let showWeb = PartExplodedFileWebVc()
//                    showWeb.showPath = explodedViewUrl
                    showWeb.showPath = "https://css-new-uat.vatti.com.cn/admin/sys-file/download?bucketname=local&filename=upload/20231115/154859261e874865a0ff01ecd108eaf5.jpg"
                    showWeb.navigationItem.title = "爆炸图".languageString()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                        self?.navigationController?.pushViewController(showWeb, animated: true)
                    }
                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            SVProgressHUD.dismiss()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    @IBAction func searchOrders(_ sender: UIButton) {
        let qrVC = QRViewController()
        qrVC.configResultCall { code, errorStr in
            if errorStr != "" {
                CD.visibleVC?.promptInformation(errorStr ?? "扫码出错了~".languageString())
                return
            }
            self.partsBarcode = code ?? ""
            self.tf_search.text = self.partsBarcode
            self.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()+"配件".languageString()
        setNavigationBackButton()
        
        vm.isSelectedOld = self.isSelectedOld
        configTableView()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.showExoloreButton)
        
        self.requestData()
    }

    @objc func showExplodedView(sender:UIButton) {
        var paramDict = [String:Any]()
        
        if code1 != ""{
            paramDict["barcode"] = code1
        }
      
        paramDict["orderId"] = orderId
        paramDict["itemId"] = itemId
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/getExplodedView",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] {
                let explodedViewUrl = kGetServerPicUrl(data.stringValue(forKey: "ExplodedView"))
                let web = Vc_Web()
                web.title = "爆炸图".languageString()
                web.webType = .http(explodedViewUrl)
                CD.push(web)
            }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()
    }
    
    func configTableView() {
        self.btn_code.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0)
        self.btn_itemCode.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0)
        self.tableView.backgroundColor = UIColor(hexString: "f8f8f8")
        self.btn_next.isEnabled = false
        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()
        }
        
        vm.didSelCallback = { (selItem) in
            let selPartArr = self.vm.itemArr.filter({$0.selected == true})
            self.btn_next.isEnabled = selPartArr.count != 0
        }
        
        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()
        }
    }

}


//网络请求
extension FinishOrderSelectPartVc{
    //mark refresh
    @objc func headerRefresh(){
        pagenumber = 1
        requestData()
    }
    
    @objc func footerRefresh(){
        self.tableView.mj_footer.endRefreshing()
        pagenumber = pagenumber + 1
        requestData()
        
//        if pagenumber < totalpages{
//            pagenumber = pagenumber + 1
//            requestData()
//        }else{
//            self.tableView.mj_footer.endRefreshing()
//            self.tableView.mj_footer.endRefreshingWithNoMoreData()
//        }
    }
    
    
    func requestData(){
        
        var paramDict = [String:Any]()
       
        if barcode != "" {
            paramDict["barcode"] = barcode
        }
        if partsCode != "" {
            paramDict["partsCode"] = partsCode
        }
        if partsBarcode != "" {
            paramDict["partsBarcode"] = partsBarcode
        }
        if searchType != "" {
            paramDict["searchType"] = searchType
        }
        paramDict["orderId"] = orderId
        paramDict["itemId"] = itemId
        
        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_FinishOrder.M_Part(json: item,isSeleted: true,isSelectedOld: weakSelf.isSelectedOld)
                    }
                    if weakSelf.pagenumber == 1 {
                        weakSelf.vm.itemArr = ms
                    }else{
                        weakSelf.vm.itemArr.append(contentsOf: ms)
                    }
                    
                    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 FinishOrderSelectPartVc: 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?()
    }
}
