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

import UIKit
import JXSegmentedView
import ESPullToRefresh

class YHHomeIdentityItem {
    var url: String = ""
    var img: UIImage? = nil
    var imgView: UIImageView = UIImageView()
    func getSize() -> CGSize {
        if let img = self.img, img.size.width > 0.0,  img.size.height > 0.0{
            return CGSize(width:img.size.width, height: (img.size.height/img.size.width) * KScreenWidth)
        }
        return CGSize(width: KScreenWidth, height: KScreenWidth)
    }
    init(url: String = "", img: UIImage? = nil) {
        self.url = url
        self.img = img
    }
}

class YHHomeIdentityListVC: YHBaseViewController {

    var detailId: String = ""
    var imgItems:[YHHomeIdentityItem] = []

    var scrollContentY: CGFloat = 0.0
    var isShowBottomView: Bool = false
    
    lazy var viewModel: YHHomePageViewModel = {
        let vm = YHHomePageViewModel()
        return vm
    }()
    
    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.tableHeaderView = self.headerView
        tableView.separatorStyle = .none
        return tableView
    }()
    
    lazy var headerView:UIView = {
        let view = UIView(frame: CGRectMake(0, 0, KScreenWidth, 8.0+KScreenWidth+44.0+9.0))
        view.clipsToBounds = true
        view.backgroundColor = .white
        view.addSubview(self.headImgView)
        headImgView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(8.0)
            make.left.right.equalToSuperview()
            make.height.equalTo(headImgView.snp.width)
        }
        self.segmentedView.dataSource = segmentedDataSource
        view.addSubview(self.segmentedView)
        let lineView = UIView()
        lineView.backgroundColor = .separatorColor
        view.addSubview(lineView)
        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)
        }
        lineView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1.0)
        }
        return view
    }()
    
    lazy var headImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "global_default_image")
        imgView.clipsToBounds = true
        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
        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.tableView)
        self.tableView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        self.tableView.es.addYHPullToRefresh {
            self.loadData()
        }
    }
}

extension YHHomeIdentityListVC: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if 0 <= index, index < self.imgItems.count {
            self.tableView.scrollToRow(at: IndexPath(row: index, section: 0), at: .top, animated: true)
        }
    }
}

extension YHHomeIdentityListVC: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YHHomeIdentityCell.cellReuseIdentifier, for: indexPath) as! YHHomeIdentityCell
        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 YHHomeIdentityListVC: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        printLog("offset: \(scrollView.contentOffset.y)")
        if scrollView.contentOffset.y <= self.headerView.height {
            if self.segmentedView.selectedIndex != 0 {
                self.segmentedView.defaultSelectedIndex = 0
                self.segmentedView.reloadDataWithoutListContainer()
            }
        }
        
        if scrollView.contentOffset.y >= 0 {
            let gap = 10.0
            if scrollView.contentOffset.y > self.scrollContentY+gap {
                self.scrollContentY = scrollView.contentOffset.y
                printLog("ABCD:\(self.scrollContentY), \(scrollView.contentOffset.y)")
                if !self.isShowBottomView {
                    self.isShowBottomView = true
                    printLog("ABC show: \(self.scrollContentY)")
                    var model = TabBarShareModel()
                    model.showFlag = true
                    if let product = self.viewModel.detailModel.products.first {
                        let path = "/pages/commodityInfo/commodityInfo?categoryId=2&levelId=\(self.detailId)&productId=\(product.id)&from=wxApp"
                        model.shareUrl = path
                    }
                    model.shareTitle = "好友力荐新品，速来围观，不容错过！"
                    model.codeUrl = self.viewModel.detailModel.imageURLDefault
                    model.downloadUrl = self.viewModel.detailModel.imageURLDefaultDownload
                    NotificationCenter.default.post(name: YhConstant.YhNotification.changeShareViewStatusOnTabBarNotifiction, object: model)

                }
                
            } else if scrollView.contentOffset.y < self.scrollContentY-gap {
                printLog("ABCD:\(self.scrollContentY), \(scrollView.contentOffset.y)")
                self.scrollContentY = scrollView.contentOffset.y
                if self.isShowBottomView {
                    self.isShowBottomView = false
                    printLog("ABC hide: \(self.scrollContentY)")
                    var model = TabBarShareModel()
                    model.showFlag = false
                    NotificationCenter.default.post(name: YhConstant.YhNotification.changeShareViewStatusOnTabBarNotifiction, object: model)
                }
            }
        }
    }
}

extension YHHomeIdentityListVC {
    
    func loadData() {
        let params:[String: Any] = ["categoryId": "2",
                                    "levelId": self.detailId]
        self.viewModel.getGoodsCategoryDetail(params: params) {
            [weak self] success, error in
            
            self?.tableView.es.stopPullToRefresh()
            
            guard let self = self else { return }
            self.titles.removeAll()
            self.imgItems.removeAll()
            for product in self.viewModel.detailModel.products {
                self.headImgView.kf.setImage(with: URL(string: product.image), placeholder: UIImage(named: "global_default_image"))
                for detail in product.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.tableView.reloadData()
            requestImages()
        }
    }
    
    func requestImages() {
        let ossGroup = DispatchGroup()
        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()
                ossGroup.leave()
            }
        }
        ossGroup.notify(queue: .main) {
            self.tableView.reloadData()
        }
    }
}
