//
//  YHHKEventCenterViewController.swift
//  galaxy
//
//  Created by EDY on 2024/6/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHHKEventCenterViewController: YHBaseViewController {
    let homeViewModel: YHHomePageViewModel = YHHomePageViewModel()
    
    var myDefaultNavItemIndex: Int = 0 {
        didSet {
            self.segmentedView.selectItemAt(index: self.myDefaultNavItemIndex)
        }
    }
    var hkList: [YHHKEventModel] = []

    var arrItemTitles: [String] = []
    var arrItemVCs: [YHHKEventWebViewController] = []
    var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: KScreenWidth, height: 55))
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = arrItemTitles
        
        dataSource.titleNormalFont = UIFont.PFSC_R(ofSize: 14)
        dataSource.titleSelectedColor = UIColor.labelTextColor2
        
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 14)
        dataSource.titleSelectedColor = UIColor.white
        dataSource.isTitleMaskEnabled = true
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = JXSegmentedViewAutomaticDimension
        dataSource.itemSpacing = 24
        return dataSource
    }()
    
    // 分类title 所对应的VC
    lazy var listContainerView: JXSegmentedListContainerView! = {
        return JXSegmentedListContainerView(dataSource: self, type: .collectionView)
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
        // segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
        segmentedView.dataSource = segmentedDataSource
        segmentedView.delegate = self
        view.addSubview(segmentedView)

        segmentedView.listContainer = listContainerView
        view.addSubview(listContainerView)
        
        // 分类Title
        segmentedView.dataSource = segmentedDataSource
        segmentedView.delegate = self
        
        // 配置指示器
        let indicator = JXSegmentedIndicatorBackgroundView()
        indicator.indicatorColor = UIColor.brandMainColor
        indicator.indicatorHeight = 32
        segmentedView.indicators = [indicator]
        segmentedView.defaultSelectedIndex = self.myDefaultNavItemIndex
        
        getData()
    }

    func getData() {
        gk_navTitle = "香港办事"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        homeViewModel.getHKEvent {[weak self] _, _ in
            guard let self = self else { return }
            self.hkList = self.homeViewModel.hkList ?? []
            self.arrItemTitles.removeAll()
            for item in self.hkList {
                self.arrItemTitles.append(item.tag)
                let vc = YHHKEventWebViewController()
                vc.model = item
                arrItemVCs.append(vc)
            }
            self.segmentedDataSource.titles = arrItemTitles
            self.segmentedView.dataSource = segmentedDataSource
            self.segmentedView.reloadData()
        }
    }
    
    func updateViews() {
        if arrItemTitles.count != 1 {
            segmentedView.frame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: view.bounds.size.width, height: 55)
            listContainerView.frame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar + 55, width: view.bounds.size.width, height: view.bounds.size.height - 55 - k_Height_NavigationtBarAndStatuBar)
        } else {
            segmentedView.frame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: view.bounds.size.width, height: 0)
            listContainerView.frame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: view.bounds.size.width, height: view.bounds.size.height - k_Height_NavigationtBarAndStatuBar)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // 处于第一个item的时候，才允许屏幕边缘手势返回
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // 离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        segmentedView.frame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: view.bounds.size.width, height: 55)
        listContainerView.frame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar + 55, width: view.bounds.size.width, height: view.bounds.size.height - 55 - k_Height_NavigationtBarAndStatuBar)
        
        segmentedView.backgroundColor = .white
    }
    
    @objc func share() {
        if YHLoginManager.shared.isLogin() {
            let model = self.hkList[segmentedView.selectedIndex]
            if model.tag.contains("日历") {
                guard let urlString = model.list.first, let url = URL(string: urlString) else {
                    return
                }
                let task = URLSession.shared.dataTask(with: url) { data, _, error in
                    DispatchQueue.main.async {
                        guard let data = data, error == nil else { return }
                        let image = UIImage(data: data)
                        if let image = image {
                            YHShareManager.shared.sendImageContent(image)
                        }
                    }
                }
                task.resume()
            } else {
                guard let urlString = model.list.first else {
                    return
                }
                YHShareManager.shared.sendLinkContent("一图看清香港办事", "", UIImage(named: "AppIcon") ?? UIImage(), link: urlString)
            }
        } else {
            YHOneKeyLoginManager.shared.oneKeyLogin()
        }
    }
}

extension YHHKEventCenterViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) {
    }
}

extension YHHKEventCenterViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        if let titleDataSource = segmentedView.dataSource as? JXSegmentedBaseDataSource {
            return titleDataSource.dataSource.count
        }
        return 0
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        return arrItemVCs[index] as JXSegmentedListContainerViewListDelegate
    }
}
