//
//  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 - k_Height_NavigationtBarAndStatuBar - cellHeight * 2
        }
    }
    
    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 = .yellow//for test hjl
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 100
        tableView.register(YHHomeCustomCell.self, forCellReuseIdentifier: YHHomeCustomCell.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)
        
        //1.UI
        initView()
        
        //2.网络请求
        requestData()
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
}

// MARK: - 私有方法
extension YHHomeViewController {
    
    @objc func leaveTopOp() {
        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(5)
            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 2
        }
        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 {
            return cellHeight
        }
        return CGRectGetHeight(self.view.bounds)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            if indexPath.row == 0 {
                cell.contentView.backgroundColor = .systemPink
            } else {
                cell.contentView.backgroundColor = .brown
            }
            cell.textLabel?.text = "第\(indexPath.section)个section - 第\(indexPath.row) 行"
            return cell
        }
        
        
        
        let cell = UITableViewCell()
        view.backgroundColor = .blue //for test hjl
        tableView.backgroundColor = .yellow//for test hjl
        cellView.view.frame = CGRect(x: 0, y: 0, width: cell.contentView.bounds.size.width, height: KScreenHeight - 64)
        cell.contentView.addSubview(cellView.view)
        
//        cell.contentView.backgroundColor = .red for test hjl
//        cellView.view.backgroundColor = .systemPink //for test hjl
        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
        printLog("Main scrollView.contentOffset.y = \(scrollView.contentOffset.y)    bottomCellOffset= \(bottomCellOffset)")
        
        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 = canScroll ? true : false
    }
    
}
