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

import UIKit
import SnapKit

class YHResourceDetailViewController: YHBaseViewController {
    
    // MARK: - Properties
    /// 如果true，对应传入detailModel，否则，必传companyId
    var isMyCompany: Bool = false
    var companyId: Int = 0  // 只需要传入公司ID
    var detailModel: YHResourceDetailModel?  // 详情数据
    
    private lazy var viewModel: YHResourceViewModel = {
        return YHResourceViewModel()
    }()
    
    private lazy var messageHandler: YHIMMessageHandler = {
        return YHIMMessageHandler(
            viewController: self,
            navigationController: navigationController
        )
    }()
    
    // MARK: - UI Components
    
    // 背景图
    private lazy var bgIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "resource_detail_bg")
        view.contentMode = .scaleAspectFill
        view.clipsToBounds = true
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight), style: .grouped)
        view.estimatedSectionHeaderHeight = 0.01
        view.estimatedSectionFooterHeight = 0.01
        view.contentInsetAdjustmentBehavior = .never
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(YHResourceDetailHeaderCell.self, forCellReuseIdentifier: "HeaderCell")
        view.register(YHResourceDetailBaseInfoCell.self, forCellReuseIdentifier: "BaseInfoCell")
        view.register(YHResourceDetailDemandCell.self, forCellReuseIdentifier: "DemandCell")
        view.register(YHResourceDetailDocumentsCell.self, forCellReuseIdentifier: "DocumentsCell")
        return view
    }()
    
    private lazy var bottomBarView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var bottomActionView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var contactButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        button.setTitle("联系合作", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = UIColor.brandGrayColor8
        button.addTarget(self, action: #selector(contactButtonClicked), for: .touchUpInside)
        return button
    }()
    
    // MARK: - Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        if isMyCompany {
            if detailModel != nil {
                tableView.reloadData()
            } else {
                loadData(true)
            }
        } else {
            loadData(false)
        }
    }
    
    // MARK: - Setup
    
    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navBackgroundColor = .clear
        gk_backImage = UIImage(named: "nav_black_24")
        view.addSubview(bgIcon)
        view.addSubview(tableView)
        view.addSubview(bottomBarView)
        view.addSubview(bottomActionView)
        bottomActionView.addSubview(contactButton)
        setupConstraints()
        updateViewIsMine()
    }
    
    private func updateViewIsMine() {
        gk_navTitle = isMyCompany ? "我的企业" : "企业详情"
        bottomActionView.isHidden = isMyCompany
        updateRightBarButtonItem()
    }
    
    private func setupConstraints() {
        bgIcon.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        bottomBarView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
        
        bottomActionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomBarView.snp.top)
            make.height.equalTo(64)
        }
        
        if isMyCompany {
            tableView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.bottom.equalTo(bottomBarView.snp.top)
            }
        } else {
            tableView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.bottom.equalTo(bottomActionView.snp.top)
            }
        }
        
        contactButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(8)
            make.height.equalTo(46)
        }
        
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
    }
    
    private func updateRightBarButtonItem() {
        if isMyCompany {
            /*
             let rightButtonItem = UIBarButtonItem(image: UIImage(named: "name_card_authorize")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(authorizeBtnClicked))
             gk_navRightBarButtonItem = rightButtonItem
             gk_navItemRightSpace = 16
             */
            let rightButtonItem = UIBarButtonItem(
                image: UIImage(named: "name_card_authorize")?.withRenderingMode(.alwaysOriginal),
                style: .plain,
                target: self,
                action: #selector(moreButtonClicked)
            )
            gk_navRightBarButtonItem = rightButtonItem
            gk_navItemRightSpace = 16
        } else {
            // 不显示按钮了
            /*
            let rightButtonItem = UIBarButtonItem(
                image: UIImage(named: "share_item")?.withRenderingMode(.alwaysOriginal),
                style: .plain,
                target: self,
                action: #selector(shareButtonClicked)
            )
            gk_navRightBarButtonItem = rightButtonItem
            gk_navItemRightSpace = 16
             */
        }
    }
    
    // MARK: - Data
    
    private func loadData(_ isMine: Bool = false) {
        if isMine {
            // 直接调用详情接口
            YHHUD.show(.progress(message: "加载中..."))
            viewModel.getMyCompanyDetail { [weak self] detail, error in
                guard let self = self else { return }
                
                DispatchQueue.main.async {
                    YHHUD.hide()
                    
                    if let detail = detail {
                        self.detailModel = detail
                        self.tableView.reloadData()
                    } else {
                        YHHUD.flash(message: error?.errorMsg ?? "获取信息异常，请重试")
                    }
                }
            }
        } else {
            guard companyId > 0 else {
                YHHUD.flash(message: "公司ID无效")
                return
            }
            
            // 直接调用详情接口
            YHHUD.show(.progress(message: "加载中..."))
            viewModel.getCompanyDetail(companyId: companyId) { [weak self] detail, error in
                guard let self = self else { return }
                
                DispatchQueue.main.async {
                    YHHUD.hide()
                    if let detail = detail {
                        self.companyId = detail.id
                        self.detailModel = detail
                        self.tableView.reloadData()
                    } else if let error = error {
                        YHHUD.flash(message: error)
                    }
                }
            }
        }
        
    }
    
    // MARK: - Actions
    
    @objc private func shareButtonClicked() {
        // 分享功能
    }
    
    @objc private func moreButtonClicked() {
        // 更多操作，直接跳授权页
        guard let detailModel = detailModel else {
            YHHUD.flash(message: "请稍候")
            return
        }
        let ctl = YHCompanyAuthorizationViewController()
        ctl.detailModel = detailModel
        ctl.completionBlock = { [weak self] in
            self?.loadData(true)
        }
        navigationController?.pushViewController(ctl, animated: true)
    }
    
    @objc private func contactButtonClicked() {
        if !YHLoginManager.shared.isLogin() {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        if let detailModel = detailModel, !detailModel.yh_id.isEmpty {
            messageHandler.gotoChatVC(senderID: detailModel.yh_id)
        }
    }
}

// MARK: - UITableViewDataSource & UITableViewDelegate

extension YHResourceDetailViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let model = detailModel else {
            return UITableViewCell()
        }
        
        switch indexPath.section {
        case 0:
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell", for: indexPath) as? YHResourceDetailHeaderCell else {
                return UITableViewCell()
            }
            cell.configure(with: model)
            return cell
            
        case 1:
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "BaseInfoCell", for: indexPath) as? YHResourceDetailBaseInfoCell else {
                return UITableViewCell()
            }
            cell.configure(with: model)
            return cell
            
        case 2:
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "DemandCell", for: indexPath) as? YHResourceDetailDemandCell else {
                return UITableViewCell()
            }
            cell.configure(with: model)
            return cell
            
        case 3:
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "DocumentsCell", for: indexPath) as? YHResourceDetailDocumentsCell else {
                return UITableViewCell()
            }
            let images = model.company_information.map { $0.url }
            cell.configure(with: images)
            cell.onImageTapped = { [weak self] index in
                self?.showImageBrowser(at: index)
            }
            cell.onImageHeightChanged = { [weak self] in
                guard let self = self else { return }
                UIView.performWithoutAnimation {
                    self.tableView.reloadRows(at: [indexPath], with: .none)
                }
            }
            return cell
            
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 0 {
            var alpha = scrollView.contentOffset.y / k_Height_NavigationtBarAndStatuBar
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            gk_navBackgroundColor = .white
            gk_navTitle = isMyCompany ? "我的企业" : "企业详情"
        } else {
            gk_navBarAlpha = 0.0
            gk_navBackgroundColor = .clear
            gk_navTitle = nil
        }
    }
    
    private func showImageBrowser(at index: Int) {
        guard let companyInformation = detailModel?.company_information else { return }
        let images = companyInformation.map { $0.url }
        if images.count > index, images.count > 0 {
            printLog("显示图片浏览器，索引：\(index)，共\(images.count)张")
            YHPictureReviewManager.shared.showNetWorkPicturs(curIndex: index, arrPicturs: images)
        }
    }
}
