//
//  HomeMessageListVc.swift
//  Service
//
//  Created by Jan on 2023/7/19.
//  Copyright © 2023 yus. All rights reserved.
//

import UIKit
import MJRefresh
import JXSegmentedView

class HomeMessageListVc: UIViewController {
    
    var vm = HomeMessageListVm()
    lazy var tableView: UITableView = {
        let tab = UITableView()
        return tab
    }()
    
    var currentIndex = 0
    var pagenumber = 1
    var pageSize = 10
    var totalpages = 1
    
    var state = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .groupTableViewBackground
        
        configTableView()
        
        requstMessageList()
    }
    
    
    func configTableView() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
         }
        
        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()
        }
        
        vm.disSelectCallback = { (item) in
            self.showDetailVcWithState(item)
        }
        
        vm.makeForms()
        
        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 showDetailVcWithState(_ item:[String:Any]){
        switch state {
        case 1:
            R_OrderDetailMain.router(item.stringValue(forKey: "relatedBillId")) {[weak self] bool in
            }
        case 2:
            R_PartsApplyDetail.router(item.stringValue(forKey: "relatedBillId")) { num in
                
            }
        case 3:
            R_SettlementDetai.router(["settleId":item.stringValue(forKey: "relatedBillId")]) { bool in
                
            }
        case 4:
            R_SettlementCheckOrderDetail.router(["settleId":item.stringValue(forKey: "relatedBillId")]) { bool in
                
            }
        default:
            break
        }
    }
    
    func showNoMoreData(_ datas:[[String:Any]]){
        if pageSize > datas.count{
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }else{
            self.tableView.mj_footer.resetNoMoreData()
        }
    }
}


//网络请求
extension HomeMessageListVc{
    //mark refresh
    @objc func headerRefresh(){
        self.tableView.mj_header.endRefreshing()
        pagenumber = 1
        requstMessageList()
    }
    
    @objc func footerRefresh(){
        self.tableView.mj_footer.endRefreshing()
        pagenumber = pagenumber + 1
        requstMessageList()
        
//        if pagenumber < totalpages{
//            pagenumber = pagenumber + 1
//            requstMessageList()
//        }else{
//            self.tableView.mj_footer.endRefreshing()
//            self.tableView.mj_footer.endRefreshingWithNoMoreData()
//        }
    }
    
    func requstMessageList(){
        var param = [String:Any]()
        param["pageNumber"] = pagenumber
        param["pageSize"] = pageSize
        param["searchType"] = self.state
        
        let cNet = TWOCNetwork(url: "/app/v2/index/message",andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_header.endRefreshing()
            if let data = result["data"] as? [String:Any] {
                if let dataList = data["unReadMessageList"] as? [[String:Any]]{
                    if weakSelf.pagenumber == 1{
                        weakSelf.vm.dataArray = dataList
                    }else{
                        weakSelf.vm.dataArray.append(contentsOf: dataList)
                    }
       
                    //刷新
                    weakSelf.showNoMoreData(dataList)
                    weakSelf.vm.makeForms()
                }
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_header.endRefreshing()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
}

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


extension HomeMessageListVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}
