//
//  HomeOrderListVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/8/24.
//

import UIKit
import MJRefresh

class HomeOrderListVc: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var vm = HomeOrderListVm()
    
    var pagenumber = 1
    var pageSize = 20
    var totalpages = 1
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.requestData()
    }
    
    var callback: ((Bool) -> ())? //返回刷新一下
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .groupTableViewBackground
        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
        topBar.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
        }
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBar.snp.bottom).offset(0)
            make.left.bottom.right.equalToSuperview()
        }
        topBar._colorTitle = UIColor.white
        topBar._colorSubTitle = UIColor.white
        topBar.delegate = self
        
        configTableView()
    }
    
    
    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
        vm.callback = {
            self.tableView.reloadData()
        }
        //刷新下面工单
        vm.reloadOrderCallback = {
            self.requstOrdrList()
        }
        //跳转列表
        vm.jumpOrderCallback = {
            self.clickOrderType()
        }
        
        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 = MJRefreshAutoNormalFooter()
//        footer.stateLabel.textColor = UIColor(hexString: "999999")
//        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
//        tableView.mj_footer = footer
    }
    
    func clickOrderType(){
        let vc = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeOrderListSearchVc") as! HomeOrderListSearchVc
        vc.searchType = String(vm.searchType)
        if vm.searchKey != ""{
            vc.bookDate = vm.searchKey
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //跳转工单详情
    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 HomeOrderListVc{
    //mark refresh
    @objc func headerRefresh(){
        self.tableView.mj_header.endRefreshing()
        pagenumber = 1
        requestData()
    }
    
    @objc func footerRefresh(){
        if pagenumber < totalpages{
            pagenumber = pagenumber + 1
            requestData()
        }else{
            self.tableView.mj_footer.endRefreshing()
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }
    }
    
    func requestData(){
        var param = [String:Any]()
        param["pageNumber"] = pagenumber
        param["pageSize"] = pageSize
        SVProgressHUD.show()
        let cNet = TWOCNetwork(url: "/app/v2/order/allOrder",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] {
                let model = HomeModel(json: data,isFirstLoad: true)
                weakSelf.vm.model = model
                weakSelf.vm.makeForms()
                
                //获取工单数据
                weakSelf.requstOrdrList()
            }else{
                hud_error("服务器出错了，请稍后再试~")
            }
        }
        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 requstOrdrList(){
        var param = [String:Any]()
        param["pageNumber"] = pagenumber
        param["pageSize"] = pageSize
        //点击日历
        if vm.searchKey != ""{
            param["bookDate"] = vm.searchKey
        }
       
        param["searchType"] = 4
        
        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]]{
                    weakSelf.vm.orderLists = orderList.compactMap({ r_item in
                        HomeModel.HomeOrder(json: r_item)
                    })
                    
                    weakSelf.vm.makeForms()
                }
            }else{
                hud_error("请求出错了，请稍后再试~")
            }
        }
        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()
    }
}


extension HomeOrderListVc: CD_TopBarProtocol {
    func topBarCustom() {
        topBar._style = "11"
        topBar.cd.background(Config.color.hex("478BFF"))
        topBar._title = "全部工单".languageString()
        topBar._colorTitle = UIColor.white
        topBar._colorSubTitle = UIColor.white
        topBar.bar_navigation.line.cd.isHidden(true)
        
        topBar._rightItemsWidth1 = 80
        topBar.bar_navigation.item_right.btn_1.setImage(UIImage(named: "navbar_home_search"), for: .normal)
    }
    
    func update(withTopBar item: CD_TopNavigationBar.Item) -> [CD_TopNavigationBarItem.Item.Style]? {
        switch item {
        case .leftItem1:
            let color:UIColor = Config.color.hex("f")
            let icon = CD_IconFont.tback_light(22)
            return [.title([(icon.text, icon.font, color, .normal), (icon.text, icon.font, Config.color.hex("f"), .highlighted), (icon.text, icon.font, Config.color.hex("f"), .selected)])]
        default:
            return nil
        }
    }
    
    func didSelect(withTopBar item: CD_TopNavigationBar.Item) {
        super_topBarClick(item)
        switch item {
        case .leftItem1:
            callback?(true)
            break
        case .rightItem1:
           debugPrint("全部搜索")
            let vc = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeOrderListSearchVc") as! HomeOrderListSearchVc
            self.navigationController?.pushViewController(vc, animated: true)
            break
        default:
            break
        }
    }
}


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



