//
//  YHHomeViewCoontroller.swift
//  galaxy
//
//  Created by davidhuangA on 2024/1/3.
//  Copyright © 2024 www.davidhuang.com. All rights reserved.
//

import Foundation
import GKNavigationBarSwift
import JXSegmentedView

class YHHomeViewController: YHBaseViewController {
    
    let sectionHeaderHeight : CGFloat = 40
    let cellHeight : CGFloat = 80
    var arrItemVc : [UIViewController] = []
    var canScroll : Bool = true
    
    
    
    var myCellHeight : CGFloat {
        get {
            return view.bounds.size.height - homeNavBarView.height  - k_TabBar_Height
        }
    }
    
    let cellView: ContentBaseViewController = ContentBaseViewController()
    
    //model 及网络请求
    lazy var homeReqVM : YHHomePageViewModel = {
        return YHHomePageViewModel()
    }()
    
    //头部背景图片
    lazy var headBkgImagV: UIImageView = {
        let imagV = UIImageView()
        imagV.image = UIImage(named: "home_head_bkg")
        imagV.contentMode = .scaleAspectFill
        return imagV
    }()
    
    //自定义导航栏
    lazy var homeNavBarView: UIView = {
        let view1 = UIView()
        view1.backgroundColor = .clear
        view1.isUserInteractionEnabled = true
        
        let icon = UIImageView(image: UIImage(named: "home_nav_icon"))
        icon.contentMode = .scaleAspectFill
        view1.addSubview(icon)
        icon.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(26)
            make.width.equalTo(120)
        }
        
        let btnMsg = UIButton(type: .custom)
        btnMsg.setImage(UIImage(named: "home_nav_msg"), for: .normal)
        view1.addSubview(btnMsg)
        btnMsg.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-16)
            make.height.width.equalTo(34)
        }
        btnMsg.addTarget(self, action: #selector(tapSearch), for: .touchUpInside)
        
        
        let btnSearch = UIButton(type: .custom)
        btnSearch.setImage(UIImage(named: "home_nav_search"), for: .normal)
        btnSearch.addTarget(self, action: #selector(tapSearch), for: .touchUpInside)
        view1.addSubview(btnSearch)
        btnSearch.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(btnMsg.snp.left).offset(-12)
            make.height.width.equalTo(34)
        }
        
        return view1
    }()
    
    
    var homeTableView: YHGestureTableView = {
        let tableView = YHGestureTableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        //        tableView.rowHeight = UITableView.automaticDimension
        //        tableView.estimatedRowHeight = 100
        //        tableView.register(YHHomeCustomCell.self, forCellReuseIdentifier: YHHomeCustomCell.cellReuseIdentifier)
        
        tableView.register(YHDavidCell0.self,forCellReuseIdentifier: YHDavidCell0.cellReuseIdentifier)
        tableView.register(YHDavidCell1.self,forCellReuseIdentifier: YHDavidCell1.cellReuseIdentifier)
        tableView.register(YHDavidCell3.self,forCellReuseIdentifier: YHDavidCell3.cellReuseIdentifier)
        tableView.register(YHDavidCell2.self,forCellReuseIdentifier: YHDavidCell2.cellReuseIdentifier)
        tableView.register(YHDavidCell4.self,forCellReuseIdentifier: YHDavidCell4.cellReuseIdentifier)
        tableView.register(YHDavidCell5.self,forCellReuseIdentifier: YHDavidCell5.cellReuseIdentifier)
        return tableView
    }()
    
    
    let arrItemTitles = ["推荐","子女教育","税务规划","民生医疗","成功案例","我的服务","行业资讯","香港生活","你我他","我是很长的tag呀"]
    let segmentView : JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 40))
    lazy var segmentedDataSource: JXSegmentedBaseDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titles = arrItemTitles
        
        dataSource.titleNormalFont = UIFont.PFSCM(ofSize: 16)
        dataSource.titleNormalColor = .commonColor25
        
        dataSource.titleSelectedFont = UIFont.PFSCM(ofSize: 18)
        dataSource.titleSelectedColor = .commonColor100
        
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = JXSegmentedViewAutomaticDimension
        dataSource.itemSpacing = 24
        return dataSource
    }()
    
    
    // MARK: - 生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(leaveTopOp), name:Notification.Name(rawValue: "leaveTop"), object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(beginDragging), name:Notification.Name(rawValue: "scrollViewWillBeginDragging"), object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(endDragging), name:Notification.Name(rawValue: "scrollViewDidEndDragging"), object: nil)
        
        //1.UI
        initView()
        
        //2.网络请求
        requestData()
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
}

// MARK: - 私有方法
extension YHHomeViewController {
    
    @objc func leaveTopOp() {
        canScroll = true
    }
    
    @objc func beginDragging() {
        homeTableView.isScrollEnabled = false
        canScroll = false
    }
    
    @objc func endDragging() {
        homeTableView.isScrollEnabled = true
        canScroll = true
    }
    
    private func requestData() {
        self.homeReqVM.getHomeConfig { flag, error in
            if flag == true {
                //1. 调用model 刷新界面
                YHHUD.flash(message: "数据已更新")
            } else {
                //2. 给出 错误提示
                if let error = error {
                    YHHUD.flash(.error(message: error.errorMsg))
                }
            }
        }
    }
    
    private func initView()->Void {
        gk_navigationBar.isHidden = true
        
        view.addSubview(headBkgImagV)
        headBkgImagV.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(307)
        }
        
        
        view.addSubview(homeNavBarView)
        homeNavBarView.layer.zPosition = 1
        homeNavBarView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_safeAreaInsetsTop())
            make.left.right.equalToSuperview()
            make.height.equalTo(48)
        }
        
        homeTableView.delegate = self
        homeTableView.dataSource = self
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.top.equalTo(homeNavBarView.snp.bottom).offset(0)
            make.left.right.bottom.equalToSuperview()
        }
        
        
        
        self.homeTableView.es.addPullToRefresh {
            self.loadFirstItem()
        }
        self.homeTableView.es.startPullToRefresh()
        self.homeTableView.es.addInfiniteScrolling {
            self.loadFakeData()
        }
    }
    
    private func loadFirstItem() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.homeTableView.es.stopPullToRefresh(ignoreDate: true,ignoreFooter: false)
            self.homeTableView.reloadData()
        }
    }
    
    private func loadFakeData() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.homeTableView.es.stopLoadingMore()
            self.homeTableView.reloadData()
        }
    }
    
    
    @objc func tapSearch() {
        printLog("*")
        navigationController?.pushViewController(YHDavidTestViewController())
    }
}

// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHHomeViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 6
        }
        return 1
    }
    
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            return UIView()
        }
        
        return UIView()
    }
    
    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 {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return 136
            } else if indexPath.row == 1 {
                return 194
            } else if indexPath.row == 2 {
                return 113
            } else if indexPath.row == 3 {
                return 138 + 15
            } else if indexPath.row == 4 {
                return YHDavidCell4.cellHeight
            } else if indexPath.row == 5 {
                return YHDavidCell5.cellHeight
            }
            
            return 100
        }
        return CGRectGetHeight(self.view.bounds)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            
            if indexPath.row == 0 {
                
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDavidCell0.cellReuseIdentifier, for: indexPath) as! YHDavidCell0
                return cell
            } else if indexPath.row == 1 {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDavidCell1.cellReuseIdentifier, for: indexPath) as! YHDavidCell1
                return cell
            } else if indexPath.row == 2 {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDavidCell2.cellReuseIdentifier, for: indexPath) as! YHDavidCell2
                return cell
            } else if indexPath.row == 3 {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDavidCell3.cellReuseIdentifier, for: indexPath) as! YHDavidCell3
                return cell
            } else if indexPath.row == 4 {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDavidCell4.cellReuseIdentifier, for: indexPath) as! YHDavidCell4
                return cell
            } else if indexPath.row == 5 {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDavidCell5.cellReuseIdentifier, for: indexPath) as! YHDavidCell5
                return cell
            }
            
            let cell = tableView.dequeueReusableCell(withIdentifier: YHDavidCell0.cellReuseIdentifier, for: indexPath) as! YHDavidCell0
            return cell
        }
        let cell = UITableViewCell()
        cellView.view.frame = CGRect(x: 0, y: 0, width: cell.contentView.bounds.size.width, height: myCellHeight)
        cell.contentView.addSubview(cellView.view)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        printLog("点击了 tableView Cell \(indexPath.row)")
    }
}

extension YHHomeViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let bottomCellOffset: CGFloat = homeTableView.rect(forSection: 1).origin.y - 64 + 80 - 12 //48
        if (scrollView.contentOffset.y >= bottomCellOffset) {
            scrollView.contentOffset = CGPointMake(0, bottomCellOffset)
            if canScroll == true {
                canScroll = false
                //传递参数到 子VC
                cellView.canScroll = true
                
            }
        }else{
            if canScroll == false {
                scrollView.contentOffset = CGPoint(x: 0, y: bottomCellOffset)
            }
        }
        self.homeTableView.showsVerticalScrollIndicator = false
    }
}

