//
//  HomePagingListOrderBaseView.swift
//  VattiCSS
//
//  Created by Jan on 2023/10/13.
//

import UIKit
import Foundation
import MJRefresh

@objc public class HomePagingListOrderBaseView: UIView {
    @objc public var tableView: UITableView!
    @objc public var dataSource: [String]?
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    var didSeletedCallback: ((String) -> ())? //点击工单
    var didClickButtonCallback: ((String,HomeModel.HomeOrder) -> ())? //点击工单按钮
    
    var searchType = 1
    var pagenumber = 1
    var pageSize = 10
    
    var hasBottomCellHeight: CGFloat = 244
    var cellHeight: CGFloat = 200
    
    var orderLists = [HomeModel.HomeOrder]()
    private var isHeaderRefreshed: Bool = false
    deinit {
        listViewDidScrollCallback = nil
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        tableView = UITableView(frame: frame, style: .plain)
        tableView.backgroundColor = UIColor(hexString: "f8f8f8")
        tableView.tableFooterView = UIView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UINib(nibName: "HomePagingListOrderCell", bundle: nil), forCellReuseIdentifier: "cell")
        addSubview(tableView)
        
        let footer = MJRefreshAutoNormalFooter()
        footer.isOnlyRefreshPerDrag = true
        footer.stateLabel.textColor = UIColor(hexString: "999999")
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        tableView.mj_footer = footer
    }

    func beginFirstRefresh() {
        pagenumber = 1
        requstOrdrList()
    }

    @objc func footerRefresh(){
        pagenumber = pagenumber + 1
        requstOrdrList()
    }
    
    func showNoMoreData(_ datas:[[String:Any]]){
        if pageSize > datas.count{
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }else{
            self.tableView.mj_footer.resetNoMoreData()
        }
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override public func layoutSubviews() {
        super.layoutSubviews()

        tableView.frame = self.bounds
        tableView.separatorStyle = .none
        self.backgroundColor = UIColor(hexString: "f8f8f8")
        tableView.backgroundColor = UIColor(hexString: "f8f8f8")
    }

}

extension HomePagingListOrderBaseView{
    func requstOrdrList(){
        var param = [String:Any]()
        param["pageNumber"] = pagenumber
        param["pageSize"] = pageSize
        param["searchType"] = searchType
        
        let cNet = TWOCNetwork(url: "/app/v2/order/search",andParam: param)
        cNet.successCall = { [weak self] (result) in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_footer.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.orderLists = modelArr
                    }else{
                        weakSelf.orderLists.append(contentsOf: modelArr)
                    }
                    weakSelf.showNoMoreData(orderList)
                    weakSelf.tableView.reloadData()
                }
            }else{
                SVProgressHUD.showError(withStatus: "请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = { [weak self](errorTag,errorStr) in
            self?.tableView.mj_footer.endRefreshing()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                SVProgressHUD.showError(withStatus: errorStr)
            }
        }
        cNet.postRequest()
    }

}

extension HomePagingListOrderBaseView: UITableViewDataSource, UITableViewDelegate {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return orderLists.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomePagingListOrderCell
        let model = orderLists[indexPath.row]
        cell.searchType = searchType
        cell.setData(model)
        cell.didClickButtonCallback = {[weak self] (actionStr) in
            self?.didClickButtonCallback?(actionStr,model)
        }
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = orderLists[indexPath.row]
        didSeletedCallback?(model.orderId)
    }

    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if [1,3,41].contains(searchType){
            return hasBottomCellHeight
        }
        return cellHeight
    }

    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
}

extension HomePagingListOrderBaseView: JXPagingViewListViewDelegate {
    public func listView() -> UIView {
        return self
    }
    
    public func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    public func listScrollView() -> UIScrollView {
        return self.tableView
    }
}
