//
//  YHNameCardDynamicViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/9/28.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHNameCardDynamicViewController: YHBaseViewController {
    
    var userId: String = ""
    let viewModel: YHDynamicViewModel = YHDynamicViewModel()
    var arr: [YHDynamicItem] = []
    var vcCanScroll: Bool = false
    
    var isCurrentUser: Bool {
        get {
           return (!self.userId.isEmpty && self.userId == YHLoginManager.shared.userModel?.id)
        }
    }
    
    var userInfo: YHUserNameCardInfo?

    lazy var tableView: YHGestureTableView = {
        let tableView = YHGestureTableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 1
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHNameCardDynamicCell.self, forCellReuseIdentifier: YHNameCardDynamicCell.cellReuseIdentifier)
        tableView.es.addYHPullToRefresh {
            self.requestList(true)
        }
        tableView.es.addInfiniteScrolling {
            self.requestList(false)
        }
        return tableView
    }()
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("还未发布过动态", kEmptyOrderBgName)
        view.isHidden = true
        return view
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        gk_navigationBar.isHidden = true
        addObserver()
        view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }
        view.addSubview(self.noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(48)
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(149)
        }
        requestList(true)
    }

    func requestList(_ firstPage: Bool) {
        let sourceType = self.isCurrentUser ? 1 : 2
        let other_user_id = self.isCurrentUser ? "" : self.userId
        self.viewModel.getList(firstPage, sourceType: sourceType, other_user_id: other_user_id) { _, _ in
            self.arr.removeAll()
            self.arr.append(contentsOf: (self.viewModel.dynamicArr))
            self.noDataView.isHidden = self.arr.count > 0
            self.tableView.reloadData()
            self.tableView.es.stopLoadingMore()
            self.tableView.es.stopPullToRefresh()
            if !self.viewModel.hasMore, self.arr.count > 0 {
                self.tableView.es.noticeNoMoreData()
            }
        }
    }
    
    func addObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(beginDragging), name: Notification.Name(rawValue: "scrollViewWillBeginDragging0"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(endDragging), name: Notification.Name(rawValue: "scrollViewDidEndDragging0"), object: nil)
    }
}

extension YHNameCardDynamicViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHNameCardDynamicCell.cellReuseIdentifier, for: indexPath) as? YHNameCardDynamicCell else { return UITableViewCell() }
        if 0 <= indexPath.row, indexPath.row < self.arr.count {
            let model = self.arr[indexPath.row]
            cell.updateModel(model)
            cell.rePublishClick = {
                let user = YHCirclePublishViewController.UserInfo()
                if let userModel = self.userInfo {
                    user.userName = userModel.username
                    user.userTitle = userModel.position
                    user.avatar = userModel.avatar
                }
                
                var arr: [YHSelectMediaItem] = []
                for model in model.resource_urls {
                    let item = YHSelectMediaItem()
                    item.type = YHMediaType.image
                    item.imageURL = URL(string: model.url)
                    item.uploadState = .success
                    item.resourceURL = model
                    arr.append(item)
                }
                let publishVC = YHCirclePublishViewController(currentUser: user, id: model.id, mediaItems: arr, title: model.title, content: model.content)
                publishVC.completion = { [weak self] in
                    self?.requestList(true)
                }
                let nav = YHNavigationController(rootViewController: publishVC)
                nav.modalPresentationStyle = .fullScreen
                UIViewController.current?.present(nav, animated: true)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if 0 <= indexPath.row, indexPath.row < self.arr.count {
            let model = self.arr[indexPath.row]
            var url = YHBaseUrlManager.shared.businessH5Url() + "/community/activity/" + "\(model.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
            vc.isHideNavigationBar = true
            vc.isFullScreenFlag = true
            UIViewController.current?.navigationController?.pushViewController(vc)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1.0
    }
}

extension YHNameCardDynamicViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

// **********************************************************************************

extension YHNameCardDynamicViewController: UIScrollViewDelegate {
    // 控制滑动交互
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollViewSet: CGFloat = scrollView.contentOffset.y
        if vcCanScroll == false {// 不能滚动时
            scrollView.contentOffset = CGPoint(x: 0, y: 0)
        } else {
            if scrollViewSet <= 0 {
                scrollView.contentOffset = CGPoint(x: 0, y: 0)
                vcCanScroll = false
                NotificationCenter.default.post(name: Notification.Name(rawValue: "leaveTop0"), object: nil)
            } else {
                scrollView.contentOffset = CGPoint(x: 0, y: scrollViewSet)
            }
        }
    }
}

extension YHNameCardDynamicViewController {
    @objc func beginDragging() {
        tableView.isScrollEnabled = false
        vcCanScroll = false
    }
    
    @objc func endDragging() {
        tableView.isScrollEnabled = true
    }
}
