//
//  HomeOrderListSearchVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/8/28.
//

import UIKit
import MJRefresh

class HomeOrderListSearchVc: UIViewController {
    @IBOutlet weak var headView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var lab_num: UILabel!

    @IBOutlet weak var tf_search: UITextField!
    @IBOutlet weak var titlebgView: UIView!
    
    var vm = HomeOrderListSearchVm()
    
    var pagenumber = 1
    var pageSize = 10
    var totalpages = 1
    var searchKey = ""
    var searchType = ""
    var bookDate = ""
    
    var callback: ((Bool) -> ())? //返回刷新一下
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requstOrdrList()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "搜索".languageString()
        let searchPlaceholder = "请输入用户名联系电话地址等关键字".languageString()
        self.tf_search.placeholder = searchPlaceholder
        self.setNavigationBackButton()
        self.view.backgroundColor = .groupTableViewBackground
        self.cd.navigationBar(hidden: false)
        
        let image = UIImage(named: "header_title_bg")
        titlebgView.layer.contents = image?.cgImage
        
        configTableView()
    }
    
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
        searchKey = sender.txt
        self.headerRefresh()
    }
    
    
    func configTableView() {
        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
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.estimatedRowHeight = 64
            tableView.estimatedSectionHeaderHeight = 0
            tableView.estimatedSectionFooterHeight = 0
        } else {
            
        }
        
        vm.callback = {
            self.tableView.reloadData()
        }
    
        vm.disSelectOrderCallback = { (orderId) in
            debugPrint(orderId)
            self.toOrderDetailVc(orderId)
        }
        
        vm.makeForms()
        
        let header = MJRefreshNormalHeader()
        header.stateLabel.textColor = UIColor(hexString: "999999")
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        tableView.mj_header = header

        let footer = MJRefreshAutoStateFooter()
        footer.isOnlyRefreshPerDrag = true
        footer.stateLabel.textColor = UIColor(hexString: "999999")
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        tableView.mj_footer = footer
    }
    
    //跳转工单详情
    func toOrderDetailVc(_ orderid:String){
        R_OrderDetailMain.router(orderid) {[weak self] bool in
            guard let weakSelf = self else { return }
            if bool {
                weakSelf.headerRefresh()
            }
        }
    }
    
    func showNoMoreData(_ datas:[[String:Any]]){
        if pageSize > datas.count{
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }else{
            self.tableView.mj_footer.resetNoMoreData()
        }
    }
}


//网络请求
extension HomeOrderListSearchVc{
    //mark refresh
    @objc func headerRefresh(){
        pagenumber = 1
        requstOrdrList()
        self.tableView.mj_header.endRefreshing()
    }
    
    @objc func footerRefresh(){
        pagenumber = pagenumber + 1
        requstOrdrList()
        self.tableView.mj_footer.endRefreshing()
        
//        if pagenumber < totalpages{
//            pagenumber = pagenumber + 1
//            requstOrdrList()
//        }else{
//            self.tableView.mj_footer.endRefreshing()
//            self.tableView.mj_footer.endRefreshingWithNoMoreData()
//        }
    }
   
    func requstOrdrList(){
        var param = [String:Any]()
        param["pageNumber"] = pagenumber
        param["pageSize"] = pageSize
        //关键字
        if self.searchKey != ""{
            param["searchKey"] = self.searchKey
        }
        if searchType != "" {
            param["searchType"] = searchType
        }
        if bookDate != "" {
            param["bookDate"] = bookDate
        }
        
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/order/search",andParam: param)
        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 orderList = data["orderList"] as? [[String:Any]]{
                    
                    let modelArr = orderList.compactMap({ r_item in
                        HomeModel.HomeOrder(json: r_item)
                    })
                    if weakSelf.pagenumber == 1{
                        weakSelf.vm.orderLists = modelArr
                    }else{
                        weakSelf.vm.orderLists.append(contentsOf: modelArr)
                    }
                    
                    weakSelf.totalpages = data.intForKey("totalpages")
                    var numStr = data.stringValue(forKey: "total")
                    if numStr == "" {numStr = "0"}
                    weakSelf.lab_num.text = "共".languageString()+numStr+"个结果".languageString()
                    weakSelf.showNoMoreData(orderList)
                    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 HomeOrderListSearchVc: 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?()
    }
}




