//
//  YHLifeDetailViewController.swift
//  galaxy
//
//  Created by edy on 2024/7/26.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHLifeDetailViewController: YHBaseViewController {

    var tabId: String = ""
    var productModel: YHProductModel = YHProductModel()
    var codeUrl: String = ""
    var downloadUrl: String = ""
    
    var imgItems: [YHHomeIdentityItem] = []
    var scrollContentY: CGFloat = 0.0
    var isShowBottomView: Bool = false
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        if self.tableView.contentOffset.y >= k_Height_NavigationtBarAndStatuBar/2.0 {
            return .darkContent
        }
        return .lightContent

    }
    
    lazy var viewModel: YHHomePageViewModel = {
        let vm = YHHomePageViewModel()
        return vm
    }()
    
    lazy var shareView: YHShareViewOnTablebarView = {
        let view = YHShareViewOnTablebarView()
        view.block = { tag in
            if tag == 0 {
                // 分享小程序
                let path = "/pages/commodityInfo/commodityInfo?categoryId=3&levelId=\(self.tabId)&productId=\(self.productModel.id)&from=wxApp"
                let shareTitle = "好友力荐新品，速来围观，不容错过！"
                YHShareManager.shared.shareToMiniProgram(path: path, shareTitle: shareTitle)
                
            } else {
                // 预约咨询
                YHConsultantQRCodeView.codeView(self.codeUrl, downloadUrl: self.downloadUrl).show()
            }
        }
        return view
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        tableView.register(YHHomeIdentityCell.self, forCellReuseIdentifier: YHHomeIdentityCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.bounces = false
        tableView.tableHeaderView = self.headerView
        tableView.separatorStyle = .none
        return tableView
    }()
    
    lazy var fakeTableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        tableView.register(YHHomeIdentityCell.self, forCellReuseIdentifier: YHHomeIdentityCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.bounces = false
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: self.headerHeight))
        tableView.tableHeaderView = view
        tableView.separatorStyle = .none
        return tableView
    }()
    
    lazy var navBar: YHCustomNavigationBar = {
        let bar = YHCustomNavigationBar.navBar()
        bar.backgroundColor = .clear
        bar.backButton.setImage(UIImage(named: "back_icon_white"), for: .normal)
        bar.backBlock = {
            [weak self] in
            guard let self = self else { return }
            self.navigationController?.popViewController(animated: true)
        }
        return bar
    }()
    
    lazy var navView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        view.addSubview(self.navBar)
        self.navBar.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_NavContentBar)
        }
        return view
    }()
    
    var headerHeight: CGFloat = KScreenWidth+44.0+9.0
    
    lazy var headerView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenWidth+44.0+9.0))
        view.backgroundColor = .white
        view.addSubview(self.headImgView)
        headImgView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(KScreenWidth)
        }
        self.segmentedView.dataSource = segmentedDataSource
        view.addSubview(self.segmentedView)
        let left = 20.0-Self.tabGap
        self.segmentedView.snp.makeConstraints { make in
            make.left.equalTo(left)
            make.right.equalTo(-left)
            make.height.equalTo(44)
            make.top.equalTo(headImgView.snp.bottom).offset(8.0)
        }
        return view
    }()
    
    lazy var headImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "global_default_image")
        return imgView
    }()
        
    lazy var segmentedView: JXSegmentedView = {
       let segmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 44))
        segmentedView.delegate = self
        // 配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorHeight = 2
        indicator.indicatorCornerRadius = 0.0
        indicator.indicatorColor = .brandMainColor
        segmentedView.indicators = [indicator]
        segmentedView.defaultSelectedIndex = 0
        segmentedView.backgroundColor = .white
        let lineView = UIView()
        lineView.backgroundColor = .separatorColor
        segmentedView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(1.0)
            make.height.equalTo(1.0)
        }
        return segmentedView
    }()
    
    lazy var topSegmentedView: JXSegmentedView = {
       let segmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 44))
        segmentedView.delegate = self
        segmentedView.dataSource = segmentedDataSource
        // 配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorHeight = 2
        indicator.indicatorCornerRadius = 0.0
        indicator.indicatorColor = .brandMainColor
        segmentedView.indicators = [indicator]
        segmentedView.defaultSelectedIndex = 0
        segmentedView.backgroundColor = .white
        segmentedView.isHidden = true
        let lineView = UIView()
        lineView.backgroundColor = .separatorColor
        segmentedView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(1.0)
            make.height.equalTo(1.0)
        }
        return segmentedView
    }()
    
    static let tabWidth = 64.0
    // 默认为4个tab
    static let tabGap = (KScreenWidth-20.0*2-tabWidth*4.0)/3.0
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titleNormalFont = UIFont.PFSC_R(ofSize: 16)
        dataSource.titleNormalColor = UIColor.init(hex: 0x94A3B8)
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 16)
        dataSource.titleSelectedColor = .mainTextColor
        dataSource.itemWidth = Self.tabWidth
        dataSource.itemSpacing = Self.tabGap
        dataSource.itemWidthSelectedZoomScale = 1.0
        dataSource.isItemSpacingAverageEnabled = false
        return dataSource
    }()
    
    var titles: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createUI()
        loadData()
    }
    
    func createUI() {
    
        gk_navigationBar.isHidden = true
        self.view.backgroundColor = .white
        self.view.addSubview(self.fakeTableView)
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.shareView)
        self.view.addSubview(self.topSegmentedView)
        self.view.addSubview(self.navView)
        self.navView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
        self.shareView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(YHShareViewOnTablebarView.viewH)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(self.shareView.snp.top).offset(KScreenHeight*Double(10.0))
        }
        self.fakeTableView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(self.shareView.snp.top).offset(KScreenHeight*Double(10.0))
        }
        let left = 20.0-Self.tabGap
        self.topSegmentedView.snp.makeConstraints { make in
            make.left.equalTo(left)
            make.right.equalTo(-left)
            make.height.equalTo(44)
            make.top.equalTo(self.navView.snp.bottom)
        }
    }
}

extension YHLifeDetailViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
        // 悬停的tab和滚动的tab 选择状态保持一致
        if segmentedView == self.topSegmentedView {
            self.segmentedView.defaultSelectedIndex = index
            self.segmentedView.reloadDataWithoutListContainer()
            
        } else {
            self.topSegmentedView.defaultSelectedIndex = index
            self.topSegmentedView.reloadDataWithoutListContainer()
        }
        
        if 0 <= index, index < self.imgItems.count {
            self.fakeTableView.scrollToRow(at: IndexPath(row: index, section: 0), at: .top, animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute: {
                let rect = self.fakeTableView.rectForRow(at: IndexPath(row: index, section: 0))
                var y = rect.origin.y - k_Height_NavigationtBarAndStatuBar-45.0+2.0
                if y > self.fakeTableView.contentSize.height-self.fakeTableView.height {
                    y = self.fakeTableView.contentSize.height-self.fakeTableView.height
                }
                self.tableView.setContentOffset(CGPoint(x: 0, y: y), animated: true)
            })
        }
    }
}

extension YHLifeDetailViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.fakeTableView {
            return
        }
        
        var percent = scrollView.contentOffset.y/k_Height_NavigationtBarAndStatuBar
        if percent < 0.0 {
            percent = 0.0
        } else if percent > 1.0 {
            percent = 1.0
        }
        navView.backgroundColor = UIColor(hex: 0xFFFFFF, alpha: percent)
        
        if percent >= 0.5 {
            navBar.backButton.setImage(UIImage(named: "back_icon"), for: .normal)
            navBar.title = self.productModel.name
            setNeedsStatusBarAppearanceUpdate()

        } else {
            navBar.backButton.setImage(UIImage(named: "back_icon_white"), for: .normal)
            navBar.title = ""
            setNeedsStatusBarAppearanceUpdate()
        }
 
        if scrollView.contentOffset.y >= (self.headerHeight-k_Height_NavigationtBarAndStatuBar-45.0) {
            topSegmentedView.isHidden = false
        } else {
            topSegmentedView.isHidden = true
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == self.fakeTableView {
            return
        }
        self.updateSelectIndex(scrollView)
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView == self.fakeTableView {
            return
        }
        self.updateSelectIndex(scrollView)
    }
    
    func updateSelectIndex(_ scrollView: UIScrollView) {
        
        var selectIndex = -1
        if self.imgItems.count > 0 {
            for index in 0..<self.imgItems.count {
                let rect = self.tableView.rectForRow(at: IndexPath(row: index, section: 0))
                // row 到顶部选择tab的距离 row 在tab下方 距离为证， row 在tab上方 距离为负
                let y = rect.origin.y-k_Height_NavigationtBarAndStatuBar-45.0-self.tableView.contentOffset.y
                
                if y > -rect.size.height {
                    selectIndex = index
                    break
                }
            }
        }
        // section 没有在可见区域出现
        if selectIndex < 0 {
            if let arr = self.tableView.indexPathsForVisibleRows, let lastIndexPath = arr.last {
                selectIndex = lastIndexPath.row
            }
        } else {
            if self.imgItems.count >= 2 {
                let gap = self.tableView.contentSize.height-self.tableView.contentOffset.y
                if selectIndex == self.imgItems.count-2, self.tableView.height-1.0 <= gap, gap <= self.tableView.height+1.0 {
                    // 滑动到底部需要定位到最后一个index
                    selectIndex = self.imgItems.count-1
                }
            }
        }
        
        self.topSegmentedView.defaultSelectedIndex = selectIndex
        self.topSegmentedView.reloadDataWithoutListContainer()
        self.segmentedView.defaultSelectedIndex = selectIndex
        self.segmentedView.reloadDataWithoutListContainer()
        
    }
}

extension YHLifeDetailViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHHomeIdentityCell.cellReuseIdentifier, for: indexPath) as? YHHomeIdentityCell else {
            return UITableViewCell()
        }
        if 0 <= indexPath.row, indexPath.row < self.imgItems.count {
            let item = self.imgItems[indexPath.row]
            cell.image = item.img
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if 0 <= indexPath.row, indexPath.row < self.imgItems.count {
            let item = self.imgItems[indexPath.row]
            return item.getSize().height
        }
        return KScreenWidth
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.imgItems.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
}

extension YHLifeDetailViewController {
    
    func loadData() {
        self.titles.removeAll()
        self.imgItems.removeAll()
        for detail in self.productModel.details {
            let item = YHHomeIdentityItem()
            item.url = detail.image
            self.imgItems.append(item)
            self.titles.append(detail.name)
        }
        self.segmentedDataSource.titles = self.titles
        self.segmentedView.dataSource = self.segmentedDataSource
        self.segmentedView.reloadDataWithoutListContainer()
        self.topSegmentedView.dataSource = self.segmentedDataSource
        self.topSegmentedView.reloadDataWithoutListContainer()
        self.segmentedView.isHidden = self.titles.count <= 0
        self.tableView.reloadData()
        self.fakeTableView.reloadData()
        requestImages()
    }
    
    func requestImages() {
        let ossGroup = DispatchGroup()
        
        if let headImgUrl = self.productModel.banner.first {
            ossGroup.enter()
            self.headImgView.kf.setImage(with: URL(string: headImgUrl)) { result in
                switch result {
                case .success(let value):
                    var imgHeight = KScreenWidth
                    if value.image.size.height > 0.0, value.image.size.width > 0.0 {
                        imgHeight = KScreenWidth * (value.image.size.height/value.image.size.width)
                    }
                    self.headerHeight = imgHeight+44.0+9.0
                    self.headerView.height = self.headerHeight
                    self.headImgView.snp.updateConstraints { make in
                        make.height.equalTo(imgHeight)
                    }
                    self.tableView.tableHeaderView = self.headerView
                    self.fakeTableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: self.headerHeight))
                    self.view.setNeedsLayout()
                    self.view.layoutIfNeeded()
                    
                case .failure(let error):
                    print("image download failed: \(error.localizedDescription)")
                }
                self.tableView.reloadData()
                self.fakeTableView.reloadData()
                ossGroup.leave()
            }
        }
        
        for item in self.imgItems {
            ossGroup.enter()
            item.imgView.kf.setImage(with: URL(string: item.url)) { result in
                switch result {
                case .success(let value):
                    item.img = value.image
                case .failure(let error):
                    print("image download failed: \(error.localizedDescription)")
                }
                self.tableView.reloadData()
                self.fakeTableView.reloadData()
                ossGroup.leave()
            }
        }
        
        ossGroup.notify(queue: .main) {
            self.tableView.reloadData()
            self.fakeTableView.reloadData {
                // 此处是为了计算准确自定义布局的contentSize
                DispatchQueue.main.asyncAfter(deadline: .now()+0.3, execute: {
                    self.fakeTableView.setContentOffset(.zero, animated: false)
                    if self.imgItems.count > 0 {
                        self.fakeTableView.scrollToRow(at: IndexPath(row: self.imgItems.count-1, section: 0), at: .top, animated: true)
                    }
                    
                    self.tableView.snp.updateConstraints { make in
                        make.bottom.equalTo(self.shareView.snp.top)
                    }
                    self.fakeTableView.snp.updateConstraints { make in
                        make.bottom.equalTo(self.shareView.snp.top)
                    }
                    self.tableView.setNeedsLayout()
                    self.tableView.layoutIfNeeded()
                    self.fakeTableView.setNeedsLayout()
                    self.fakeTableView.layoutIfNeeded()
                })
            }
        }
    }
}
