//
//  OrderAssignUserVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/8/31.
//

import UIKit
import MJRefresh

public struct R_OrderAssignUser {
    static func router(_ orderid: String, type:Int, callback: ((Bool)->Void)?) {
        let vc = OrderAssignUserVc.cd_storyboard("Order", from: "OrderAssignUserVc") as! OrderAssignUserVc
        vc.orderId = orderid
        vc.type = type
        vc.callBack = callback
        CD.push(vc)
    }
}

class OrderAssignUserVc: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var bottomV: UIView!
    @IBOutlet weak var btn_submit: UIButton!
    lazy var topBar: CD_TopBar = {
        return CD_TopBar()
    }()
    
    var type:Int = 1 //1、选择服务商；2、选择工程师
    var vm = OrderAssignUserVm()
    
    var orderId = ""
    var pageNumber = 1
    var pageSize = 10
    var pageCount = 0
    
    var callBack:((Bool)->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        btn_submit.cd.text("提交".languageString())
        switch type {
        case 1:
            getSiteList()
        case 2:
            getEngineerList()
        default:
            break
        }
        makeUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    }

    func makeUI() {
        self.cd.navigationBar(hidden: true)
        self.view.cd
            .add(topBar)
        topBar.delegate = self
        
        vm.reloadData = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(topBar.snp_bottom)
            make.bottom.equalTo(bottomV.snp_top)
        }
        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
        
        vm.makeForms()
    }
    
    @objc func headerRefresh(){
        self.tableView.mj_header.endRefreshing()
        self.tableView.mj_footer.resetNoMoreData()
        pageNumber = 1
        switch type {
        case 1:
            getSiteList()
        case 2:
            getEngineerList()
        default:
            break
        }
    }
    
    @objc func footerRefresh(){
        if pageCount == pageSize {
            pageNumber = pageNumber + 1
            switch type {
            case 1:
                getSiteList()
            case 2:
                getEngineerList()
            default:
                break
            }
        }else{
            self.tableView.mj_footer.endRefreshing()
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }
    }
    
    @IBAction func submit(_ sender: UIButton) {
        switch type {
        case 1:
            assinSite()
        case 2:
            assinEngineer()
        default:
            break
        }
    }
}
extension OrderAssignUserVc: 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 OrderAssignUserVc: CD_TopBarProtocol {
    func topBarCustom() {
        topBar.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
        }
        topBar._style = "10"
        
        topBar.cd.background(.white)
        switch type {
        case 1:
            topBar._title = "选择服务商".languageString()
        case 2:
            topBar._title = "选择工程师".languageString()
        default:
            break
        }
        topBar.bar_navigation.item_centre._colorTitle = Config.color.hex("3")
        topBar.bar_navigation.item_centre.btn_1.titleLabel?.font = Config.font.fontMedium(18)
        topBar.bar_navigation.line.cd.isHidden(false)
            .background(Config.color.hex("EC"))
    }
    
    func update(withTopBar item: CD_TopNavigationBar.Item) -> [CD_TopNavigationBarItem.Item.Style]? {
        switch item {
        case .leftItem1:
            let color:UIColor = Config.color.hex("6")
            let icon = CD_IconFont.tback_light(22)
            return [.title([(icon.text, icon.font, color, .normal), (icon.text, icon.font, Config.color.hex("6"), .highlighted), (icon.text, icon.font, Config.color.hex("6"), .selected)])]
        default:
            return nil
        }
    }
    
    func didSelect(withTopBar item: CD_TopNavigationBar.Item) {
        super_topBarClick(item)
        switch item {
        case .leftItem1:
            break
        default:
            break
        }
    }
}
