//
//  CreatOrderBaseDataVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/8/29.
//

import UIKit
import MJRefresh

class CreatOrderBaseDataVc: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tf_search: UITextField!
    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var height_headerView: NSLayoutConstraint!
    
    @IBOutlet weak var btn_search: UIButton!
    var vm = CreatOrderBaseDataVm()
    //获取数据
    var getDataUrl = "app/v2/basicInformation/getServiceType"
    var orderid = ""
    var faultid = ""
    var servicetypeid = ""
    var superid = ""
    var itemid = ""
    var searchValue = ""
    
    var isShowHeader = false
    
    //增补自定义参数
    var subJoinParam = [String:Any]()
    
    var parentId = ""
    
    var loadMore = false//是否加载更多
    
    var listKey = "serviceTypeList "
    
    var pagenumber = 1
    var pageSize = 10
    var totalpages = 1
    
    var selCallback:(([String:Any])->())?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
        self.configNavBgView()
    }
    
    @IBAction func editingDidEnd(_ sender: UITextField) {
        searchValue = sender.txt
        self.headerRefresh()
    }
    
    @IBAction func searchOrders(_ sender: UIButton) {
        searchValue = tf_search.txt
        self.headerRefresh()
    }
    
    func configNavBgView(){
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.shadowColor = UIColor(hexString: "ffffff")
            appearance.backgroundColor = UIColor(hexString: "ffffff")
            appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(hexString: "#333333"), NSAttributedString.Key.font:UIFont(name: "PingFangSC-Medium", size: 17)!]
            self.navigationController?.navigationBar.standardAppearance = appearance
            self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
            self.navigationController?.navigationBar.tintColor = UIColor(hexString: "ffffff")
         
        } else {
            
            navigationController?.navigationBar.tintColor = UIColor(hexString: "ffffff")
            // 背景
            navigationController?.navigationBar.barTintColor = UIColor(hexString: "ffffff")
            // 标题
            let titleAtt:[NSAttributedString.Key:Any] = [NSAttributedString.Key.font:UIFont(name: "PingFangSC-Medium", size: 17)!,NSAttributedString.Key.foregroundColor:UIColor(hexString: "#333333")]
            navigationController?.navigationBar.titleTextAttributes = titleAtt
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavigationBackButton()
        tf_search.placeholder = "搜索关键字".languageString()
        btn_search.setTitle("搜索".languageString(), for: .normal)
        if isShowHeader {
            headerView.isHidden = false
            height_headerView.constant = 50
        }
        configTableView()
        requestData()
    }
    
    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.selCallback = { (item) in
            self.selCallback?(item)
            self.navigationController?.popViewController(animated: true)
        }
        
        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 showNoMoreData(_ datas:[[String:Any]]){
        if pageSize > datas.count{
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
        }else{
            self.tableView.mj_footer.resetNoMoreData()
        }
    }

}


//网络请求
extension CreatOrderBaseDataVc{
    //mark refresh
    @objc func headerRefresh(){
        pagenumber = 1
        requestData()
    }
    
    @objc func footerRefresh(){
        if loadMore{
            self.tableView.mj_footer.endRefreshing()
            pagenumber = pagenumber + 1
            requestData()
        }
    }
    
    func requestData(){
        var paramDict = [String:Any]()
        paramDict["pageNumber"] = pagenumber
        paramDict["pageSize"] = pageSize
        
        paramDict += subJoinParam
        
        if orderid != "" {
            paramDict["orderid"] = orderid
        }
        if faultid != "" {
            paramDict["faultid"] = faultid
        }
        if superid != "" {
            paramDict["superid"] = superid
        }
        if servicetypeid != "" {
            paramDict["servicetypeid"] = servicetypeid
        }
        if searchValue != "" {
            paramDict["value"] = searchValue
        }
        
        if searchValue != "" {
            paramDict["searchKey"] = searchValue
        }
        
        if itemid != "" {
            paramDict["itemid"] = itemid
        }
        
        if parentId != "" {
            paramDict["parentId"] = parentId
        }
        
        
        let cNet = TWOCNetwork(url: getDataUrl,andParam: paramDict)
        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 datas = data[weakSelf.listKey] as? [[String:Any]]{
                    if weakSelf.pagenumber == 1 {
                        weakSelf.vm.itemArr = datas
                    }else{
                        weakSelf.vm.itemArr.append(contentsOf: datas)
                    }
                    
                    weakSelf.showNoMoreData(datas)
                    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 CreatOrderBaseDataVc: 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?()
    }
}
