//
//  ServiceFaultListVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/10/10.
//

import UIKit
import MJRefresh

public struct R_ServiceFaultList {
    static func router() {
        let vc = ServiceFaultListVc.cd_storyboard("Service", from: "ServiceFaultListVc") as! ServiceFaultListVc
        CD.push(vc)
    }
}

class ServiceFaultListVc: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tf_search: UITextField!
    @IBOutlet weak var lab_category: UILabel!
    
    var vm = ServiceFaultListVm()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNavigationBackButton()
        self.title = "故障库".languageString()
        lab_category.text = "分类".languageString()
        tf_search.placeholder = "输入关键词搜索".languageString()
        
        makeUI()
        vm.makeForms()
        vm.requestData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }

    func makeUI() {
        tf_search.delegate = self
        
        vm.reloadData = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
            if weakSelf.vm.pageCount < weakSelf.vm.pageSize{
                weakSelf.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        let header = MJRefreshNormalHeader()
        header.stateLabel.textColor = UIColor(hexString: "999999")
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        tableView.mj_header = header
        
        let footer = MJRefreshAutoNormalFooter()
        footer.stateLabel.textColor = UIColor(hexString: "999999")
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        footer.isOnlyRefreshPerDrag = true
        tableView.mj_footer = footer
    }
    
    @objc func headerRefresh(){
        tableView.mj_header.endRefreshing()
        tableView.mj_footer.resetNoMoreData()
        vm.pageNumber = 1
        vm.requestData()
    }
    
    @objc func footerRefresh(){
        self.tableView.mj_footer.endRefreshing()
        if vm.pageCount < vm.pageSize{
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }else{
            vm.pageNumber = vm.pageNumber + 1
            vm.requestData()
        }
    }
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
        vm.searchKey = sender.text!
        headerRefresh()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    @IBAction func selectCategory(_ sender: UIButton) {
        getItemCat()
    }
}

extension ServiceFaultListVc {
    func getItemCat() {
        var par:[String:Any] = [:]
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/basicInformation/getItemCat",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_hidden()
            if let data = result["data"] as? [String:Any] {
                var itemCatList = data.arrayValue(forKey: "itemCatList")
                if !itemCatList.isEmpty {
                    itemCatList.insert(["categoryName":"全部分类".languageString()], at: 0)
                    weakSelf.selectDictItems(itemCatList)
                }else{
                    hud_info("无产品分类数据".languageString())
                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func selectDictItems(_ datas:[[String:Any]]) {
        guard !datas.isEmpty else {
            hud_info("没有产品分类数据".languageString())
            return
        }
        let pickerDataArr = datas.compactMap {
            ($0.stringValue(forKey: "categoryName"),"")
        }
        TWSheetPicker.showActionSheet(titleStr: "请选择分类".languageString(), singleType: true, dataArr: pickerDataArr) {  [weak self] (indexArr) in
            guard let weakSelf = self else { return }
            guard let index = indexArr.first else { return }
            let dic = datas[index]
            let categoryId = dic.stringValue(forKey: "itemCatId")
            let categoryCode = dic.stringValue(forKey: "categoryCode")
            let categoryName = dic.stringValue(forKey: "categoryName")
            if categoryId != weakSelf.vm.categoryId {
                if categoryName == "全部分类".languageString() {
                    weakSelf.lab_category.cd.text("分类".languageString())
                }else{
                    weakSelf.lab_category.cd.text(categoryName)
                }
                weakSelf.vm.categoryId = categoryId
                weakSelf.vm.categoryCode = categoryCode
                weakSelf.vm.categoryName = categoryName
                weakSelf.headerRefresh()
            }
        }.show(self)
    }
}

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

