//
//  YHCircleViewController.swift
//  galaxy
//
//  Created by alexzzw on 2025/9/24.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import ESPullToRefresh
import JXSegmentedView

class YHCircleViewController: YHBaseViewController {
    
    lazy var viewModel: YHDynamicViewModel = YHDynamicViewModel()
    lazy var userInfoViewModel: YHInformationAuthorizeViewModel = YHInformationAuthorizeViewModel()
    var arr: [YHDynamicItem] = []
    
    lazy var circleCollectView: UICollectionView = {
        let flowLayout = YHHomeCollectionLayout()
        flowLayout.minimumInteritemSpacing = 7.0
        flowLayout.minimumColumnSpacing = 7.0
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        flowLayout.headerHeight = 112
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = .white
        collectionView.register(YHCircleCollectionViewCell.self, forCellWithReuseIdentifier: YHCircleCollectionViewCell.cellReuseIdentifier)
        collectionView.register(YHCircleHeaderReusableView.self, forSupplementaryViewOfKind: CollectionViewWaterfallElementKindSectionHeader, withReuseIdentifier: YHCircleHeaderReusableView.reuseIdentifier)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.alwaysBounceVertical = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        return collectionView
    }()
    
    lazy var publishButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = UIColor.brandGrayColor8
        btn.setImage(UIImage(named: "circle_publish_icon"), for: .normal)
        btn.setTitle("发布动态", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 15)
        btn.layer.cornerRadius = 22
        btn.addTarget(self, action: #selector(publishButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无动态", kEmptyOrderBgName)
        view.isHidden = true
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        requestList(true)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 私有方法
private extension YHCircleViewController {
    
    @objc private func loginSuccess() {
        requestList(true)
    }
    
    func setupUI() {
        gk_navigationBar.isHidden = true
        view.addSubview(circleCollectView)
        view.addSubview(publishButton)
        circleCollectView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        publishButton.snp.makeConstraints { make in
            make.width.equalTo(134)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-30)
        }
        
        view.addSubview(self.noDataView)
        
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(164)
        }
        
        publishButton.iconInLeft(spacing: 6)
        
        circleCollectView.es.addYHPullToRefresh {
            self.requestList(true)
        }
        
        circleCollectView.es.addInfiniteScrolling {
            self.requestList(false)
        }
        
        circleCollectView.es.stopPullToRefresh()
        circleCollectView.es.stopLoadingMore()
    }
    
    func requestList(_ firstPage: Bool) {
        let sourceType = 0
        self.viewModel.getList(firstPage, sourceType: sourceType) { [weak self] _, _ in
            guard let self = self else {
                return
            }
            let tempArr = self.viewModel.dynamicArr
            DispatchQueue.global().async {
                // 并行计算（内部会自动跳过已计算的）
                DispatchQueue.concurrentPerform(iterations: tempArr.count) { index in
                    tempArr[index].calHeightParam()
                }
                
                DispatchQueue.main.async {
                    self.arr = tempArr
                    self.noDataView.isHidden = self.arr.count > 0
                    self.circleCollectView.reloadData()
                    self.circleCollectView.es.stopLoadingMore()
                    self.circleCollectView.es.stopPullToRefresh()
                    if !self.viewModel.hasMore, self.arr.count > 0 {
                        self.circleCollectView.es.noticeNoMoreData()
                        self.circleCollectView.footer?.alpha = 1
                    }
                }
            }
        }
    }
    
    @objc func publishButtonClicked() {
        if !YHLoginManager.shared.isLogin() {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        
        YHHUD.show(.progress(message: ""))
        userInfoViewModel.requestUserInfo { [weak self] _, _ in
            YHHUD.hide()
            guard let self = self else {
                return
            }
            if self.userInfoViewModel.model.username.isEmpty {
                YHGrayCommonAlertView.show("", "请先完善个人信息后再来发布动态", "返回", "前往完善", fullGuestureEnable: false) {
                } callBack: { [weak self] in
                    guard let self = self else {
                        return
                    }
                    let userInfoPage = YHInformationAuthorizationStepOneViewController()
                    self.navigationController?.pushViewController(userInfoPage)
                }
            } else {
                let user = YHCirclePublishViewController.UserInfo()
                user.userName = self.userInfoViewModel.model.username
                user.userTitle = self.userInfoViewModel.model.position
                user.avatar = self.userInfoViewModel.model.avatar
                let publishVC = YHCirclePublishViewController(currentUser: user)
                publishVC.completion = { [weak self] in
                    self?.requestList(true)
                }
                let nav = YHNavigationController(rootViewController: publishVC)
                nav.modalPresentationStyle = .fullScreen
                present(nav, animated: true)
            }
        }
        
    }
    
    // MARK: - 头部按钮处理方法
    func handleHeaderButtonTap(at index: Int) {
        switch index {
        case 0: // 找客户
            handleFindCustomerAction()
        case 1: // 找服务
            handleFindServiceAction()
        case 2: // 拓人脉
            handleExpandNetworkAction()
        case 3: // 办活动
            handleOrganizeEventAction()
        default:
            break
        }
    }
    
    private func handleFindCustomerAction() {
        let dict = [YHResourceViewController.selectTypeKey: YHResourceFilterType.demand.rawValue]
        NotificationCenter.default.post(name: YhConstant.YhNotification.goResourceVCNotifiction, object: nil, userInfo: dict)
    }
    
    private func handleFindServiceAction() {
        let dict = [YHResourceViewController.selectTypeKey: YHResourceFilterType.service.rawValue]
        NotificationCenter.default.post(name: YhConstant.YhNotification.goResourceVCNotifiction, object: nil, userInfo: dict)
    }
    
    private func handleExpandNetworkAction() {
        NotificationCenter.default.post(name: YhConstant.YhNotification.goConnectionVCNotifiction, object: nil)
    }
    
    private func handleOrganizeEventAction() {
        NotificationCenter.default.post(name: YhConstant.YhNotification.goActivityVCNotifiction, object: nil)
    }
    
    private func gotoCircleDetailPage(id: String) {
        var url = YHBaseUrlManager.shared.businessH5Url() + "/community/activity/\(id)"
        
        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            let urlHasParam = String.hasQueryParameters(urlString: url)
            if urlHasParam {
                url = url + "&param=" + token
            } else {
                url = url + "?param=" + token
            }
        }
        var tUrl = url
        if !url.contains("navigationH=") {
            tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            if url.contains("?") {
                tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            }
        }
        let vc = YHH5WebViewVC()
        vc.url = tUrl
        navigationController?.pushViewController(vc)
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension YHCircleViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard arr.count > indexPath.row else {
            return UICollectionViewCell()
        }
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHCircleCollectionViewCell.cellReuseIdentifier, for: indexPath) as? YHCircleCollectionViewCell else {
            return UICollectionViewCell()
        }
        let model = arr[indexPath.row]
        cell.listModel = model
        // 暂不处理，可能出现渲染问题
//        cell.onImageHeightChanged = { [weak self] in
//            guard let self = self else {
//                return
//            }
//            UIView.performWithoutAnimation {
//                self.circleCollectView.reloadData()
//            }
//        }
        cell.clickHeartEvent = { [weak self, weak cell] in
            guard let self = self else {
                return
            }
            if !YHLoginManager.shared.isLogin() {
                YHOneKeyLoginManager.shared.oneKeyLogin()
                return
            }
            let operation = model.like_self ? 2 : 1
            self.viewModel.getLike(model.id, operation) { success, _ in
                if success {
                    model.like_self = !model.like_self
                    if model.like_self {
                        model.like_count += 1
                    } else {
                        model.like_count -= 1
                    }
                    cell?.updateLikeState(isLike: model.like_self, currentModel: model)
                }
            }
        }
        
        return cell
    }
    
    // MARK: - Header View
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == CollectionViewWaterfallElementKindSectionHeader, let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: YHCircleHeaderReusableView.reuseIdentifier, for: indexPath) as? YHCircleHeaderReusableView {
            
            headerView.delegate = self
            
            return headerView
        }
        
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard arr.count > indexPath.row else { return }
        let model = arr[indexPath.row]
        printLog("\(model.img_width_use) \(model.img_height_use) \(model.img_width_cell) \(model.img_height_cell)")
        // https://test-businessh5.galaxy-immi.com/community/activity/1
        gotoCircleDetailPage(id: model.id)

    }
}

// MARK: - CollectionViewWaterfallLayoutDelegate
extension YHCircleViewController: CollectionViewWaterfallLayoutDelegate {
    
    func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        if indexPath.row < arr.count {
            let model = arr[indexPath.row]
            return CGSize(width: model.img_width_cell, height: model.img_height_cell)
        }
        
        let width = (KScreenWidth - 47) / 2
        return CGSize(width: width, height: 200.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: 110)
    }
}

// MARK: - JXSegmentedListContainerViewListDelegate
extension YHCircleViewController: JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        return view
    }
}

// MARK: - YHCircleHeaderButtonsViewDelegate
extension YHCircleViewController: YHCircleHeaderButtonsViewDelegate {
    
    func headerButtonsView(_ view: YHCircleHeaderButtonsView, didTapButtonAt index: Int) {
        handleHeaderButtonTap(at: index)
    }
}
