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

import Foundation
import GKNavigationBarSwift
import JXSegmentedView
import SafariServices

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: YHMainContentBaseViewController = YHMainContentBaseViewController()
    
    //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.PFSC_M(ofSize: 16)
        dataSource.titleNormalColor = UIColor(hexString: "#888F98")
        
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 18)
        dataSource.titleSelectedColor = .brandMainColor
        
        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()
//        testModelParse()//for test hjl  添加 数据类型 转换
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
}

// MARK: - 私有方法
extension YHHomeViewController {
    
    func testModelParse() {
        
//        SmartConfig.debugMode = .verbose
        
        let json = """
        {
            "data": "balabala Team",
            "errorCode": 0,
            "errorMessage": "操作成功",
            "success":true,
            "test": {
                "test1": "test1-value",
                "test2": "test2-value",
                "test333": "test3-value",
            },
            "testArr":[
                {
                    "test1": "test1-value",
                    "test2": "test2-value",
                    "test333": "test3-value",
                },
                {
                    "test1": "test1-value",
                    "test2": "test2-value",
                    "test333": "test3-value",
                },
                {
                    "test1": "test1-value",
                    "test2": "test2-value",
                    "test333": "test3-value",
                }
            ]
        }
        """
        
        
        //1. json字符串 转 对象
        guard let model = NetBaseModel.deserialize(json: json) else { return }
        print("model 是 ==>",model)
        print(model)
        
        //2. 对象 转 dictionary
        let dic = model.toDictionary()
        print("dic 是 ==>",dic as Any)
        
        //3. dictionary 转 string
        let jsonString = dic?.jsonString()
        print("jsonString 是 ==>",jsonString ?? "")
        
        //4.model 转 string
        let jsonString2 = model.toJSONString()
        print("jsonString2 是 ==>",jsonString2 ?? "")
        
        //5. dic 转 model
        guard let model1 = NetBaseModel.deserialize(dict: dic) else { return }
        print("model1 是 ==>",model1)
        
    }
    
    @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(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)")
//        let vc = YHWebViewViewController()
//        vc.url = "https://auth.qiyuesuo.cn?ticket=bQngrvjj1TPHPnaOt91wKNtzO5iBNDfcwtMtgZdpdZxKIiDgW914qVqxQfloCUVT&channel=OPEN_V2"
        
        
        let url = URL(string: "https://auth.qiyuesuo.cn?ticket=mw5mqO2qx5y%2F%2BqZuOKet7ct3JhAtlFkH4ar9JyyMas0gQ4YYg28iV43Cs8QqqvN8&channel=OPEN_V2")!
               // 创建SFSafariViewController
        let safariViewController = SFSafariViewController(url: url)
        safariViewController.dismissButtonStyle = .close
       // 设置代理
        safariViewController.delegate = self
       // 显示
//       present(safariViewController, animated: true, completion: nil)
        
        self.navigationController?.pushViewController(safariViewController)
//    https://cloudapi.qiyuesuo.cn/contract/share/3202449385770287813?openPageToken=d004e5af-aab9-43e4-b813-c5a6a8c16497
    }
}

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
    }
}

extension YHHomeViewController: SFSafariViewControllerDelegate {
    // MARK: 点击左上角的完成
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        print(#function)
    }

    // MARK: 加载完成
    func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
        print(#function)
    }
    
    // MARK: 点击右下角调用Safari浏览器打开
    func safariViewControllerWillOpenInBrowser(_ controller: SFSafariViewController) {
        print(#function)
    }
}

