//
//  YHHomeViewController.swift
//  galaxy
//
//  Created by EDY on 2023/12/20.
//

import UIKit

//服务中心
class YHServiceCenterMainViewController: YHBaseViewController {
    
    private let serviceCenterMainReqVM : YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    
    private lazy var topBkg : UIView = {
        let imagV = UIImageView()
        imagV.image = UIImage(named: "service_center_head_bkg")
        imagV.contentMode = .scaleAspectFill
        return imagV
        
    }()
    
    private let loginTipsView : YHLoginTipsView = {
        let view = YHLoginTipsView()
        view.viewType = 0
        view.isHidden = true
        return view
    }()
    
    private let noDataView : YHLoginTipsView = {
        let view = YHLoginTipsView()
        view.viewType = 1
        view.isHidden = true
        return view
    }()
    
    private func loginOp() {
        let vc = UINavigationController(rootVC: YHPhoneLoginViewController())
        vc.modalPresentationStyle = .custom
        self.navigationController?.present(vc, animated: true)
    }
    
    
    var homeTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 81.0
        tableView.register(YHContractCell.self,forCellReuseIdentifier: YHContractCell.cellReuseIdentifier)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        handleRightUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        handleRightUI()
        loadData()
    }
}

extension YHServiceCenterMainViewController {
    func loadData() {
        
        if YHLoginManager.shared.isLogin() == false {
            return
        }
        
        serviceCenterMainReqVM.getContactList { success, error in
            if success == true {
                
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "请求出错")
            }
            self.handleRightUI()
        }
    }
    
    func setupUI() {
        gk_navTitle = "服务中心"
        gk_navBarAlpha = 1.0
        
        loginTipsView.clickLoginBtnCallBackBlock = {
            self.loginOp()
        }
        
        view.addSubview(topBkg)
        topBkg.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(216)
        }
        
        view.addSubview(loginTipsView)
        loginTipsView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-64)
            make.width.equalTo(KScreenWidth)
        }
        
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-64)
            make.width.equalTo(KScreenWidth)
        }
        
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview().offset(-k_Height_TabBar)
        }
        homeTableView.delegate = self
        homeTableView.dataSource = self
        
        
        self.homeTableView.isHidden = true
        self.noDataView.isHidden = false
        
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
        
    }
}

// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHServiceCenterMainViewController : UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.serviceCenterMainReqVM.arrContactList.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return kMargin
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: kMargin))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 81
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell0 = tableView.dequeueReusableCell(withClass: YHContractCell.self)
        cell0.selectionStyle = .none
        
        if indexPath.section < self.serviceCenterMainReqVM.arrContactList.count {
            cell0.dataModel = self.serviceCenterMainReqVM.arrContactList[indexPath.section]
        }
        return cell0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        printLog("点击了 tableView Cell \(indexPath.section)")
        
        //获取订单号
        let orderId = serviceCenterMainReqVM.arrContactList[indexPath.section].id
        UserDefaults.standard.set(orderId, forKey: "orderIdForPreview")
        UserDefaults.standard.synchronize()
        
        let vc = YHServiceCenterSecondViewController()
        vc.orderId = orderId
        self.navigationController?.pushViewController(vc)
    }
}



extension YHServiceCenterMainViewController {
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        loadData()
    }
    
    @objc func logoutSuccess() {
        handleRightUI()
    }
    
    private func handleRightUI() {
        if YHLoginManager.shared.isLogin() == false {
            loginTipsView.isHidden = false
            noDataView.isHidden = true
            homeTableView.isHidden = true
        } else {
            loginTipsView.isHidden = true
            
            if serviceCenterMainReqVM.arrContactList.isEmpty {
                homeTableView.isHidden = true
                noDataView.isHidden = false
            } else {
                homeTableView.isHidden = false
                noDataView.isHidden = true
            }
        }
        homeTableView.reloadData()
    }
}
