//
//  YHActivityTravelViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/6/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHActivityTravelViewController: YHBaseViewController {
    
    // vm对象
    lazy var viewModel: YHActivityViewModel = {
        let vm = YHActivityViewModel()
        return vm
    }()
    
    // 活动行程单Id
    var travelId: String = ""
    
    // tableView
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.clear
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHActivityTravelCell.self, forCellReuseIdentifier: YHActivityTravelCell.cellReuseIdentifier)
        tableView.tableHeaderView =  nil
        tableView.tableFooterView = nil
        
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        
        return tableView
    }()
    
    lazy var topBkgImageV: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFill
        view.image = UIImage(named: "activity_travel_bkg")
        return view
    }()
    
    // MARK: - 生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    override func backItemClick(_ sender: Any) {
//        if viewModel.didChange {
//            YHCommonAlertView.show("", "您尚未保存修改，确定关闭吗？", "仍然关闭", "继续编辑", fullGuestureEnable: false) {
//                self.navigationController?.popViewController()
//            } callBack: {
//            }
//        } else {
//            self.navigationController?.popViewController()
//        }
        gotoActivityVC()
    }
    
    /// 是否可以返回，包括点击返回和手势返回，默认YES
    override func navigationShouldPop() -> Bool {
//        if viewModel.didChange {
//            YHCommonAlertView.show("", "您尚未保存修改，确定关闭吗？", "仍然关闭", "继续编辑", fullGuestureEnable: false) {
//                self.navigationController?.popViewController()
//            } callBack: {
//            }
//            return false
//        }
        gotoActivityVC()
        return false
    }
    
}

extension YHActivityTravelViewController {
    func gotoActivityVC() {
        
        if let vc = UIApplication.shared.keyWindow?.rootViewController as? YHTabBarViewController {
            if vc.selectedIndex == 4 {
                if let nav = self.navigationController {
                    let rrr = nav.viewControllers.contains { $0.isKind(of: YHActivityListViewController.self) }
                    if rrr {
                        
                        var  targetVc: UIViewController?
                        for(_, value) in nav.viewControllers.enumerated() {
                            if value.isKind(of: YHActivityListViewController.self) {
                                targetVc = value
                                break
                            }
                        }
                        
                        if let vc = targetVc {
                            navigationController?.popToViewController(vc, animated: true)
                        }
                        return
                    }
                }
            } else if vc.selectedIndex == 3 {
                
                if let nav = self.navigationController {
                    let rrr = nav.viewControllers.contains { $0.isKind(of: YHCommunityViewController.self) }
                    if rrr {
                        var  targetVc: UIViewController?
                        for(_, value) in nav.viewControllers.enumerated() {
                            if value.isKind(of: YHCommunityViewController.self) {
                                targetVc = value
                                break
                            }
                        }
                        
                        if let vc = targetVc {
                            navigationController?.popToViewController(vc, animated: true)
                        }
                        return
                    }
                }
            }
        }
       
    }
    
    func setupUI() {
        gk_navigationBar.isHidden = false
        gk_navigationBar.backgroundColor = .clear
        gk_navBarAlpha = 0
        gk_navTitle = "活动行程单"
        
        view.backgroundColor = UIColor.pageBkgColor
        
        // 1.
        view.addSubview(topBkgImageV)
        view.addSubview(tableView)
        
        topBkgImageV.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(332)
        }
        
        tableView.contentInsetAdjustmentBehavior = .never
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalToSuperview()
        }
    }
    
    func loadData() {
        if !travelId.isEmpty {
            viewModel.getActivityTravelDetail(travelId: travelId) { success, error in
                if success {
                    self.tableView.reloadData()
                } else {
                    let msg = error?.errorMsg ?? "获取数据出错"
                    YHHUD.flash(message: msg)
                    self.navigationController?.popViewController()
                }
            }
        } else {
            YHHUD.flash(message: "参数错误")
            navigationController?.popViewController()
        }
    }
    
    func cancelActivityApply() {
        viewModel.cancelActivityTravel(travelId: travelId) { [weak self] (success, error) in
            if success {
                YHHUD.flash(message: "已取消报名")
                self?.loadData()
            } else {
                let msg = error?.errorMsg ?? "取消失败"
                YHHUD.flash(message: msg)
            }
        }
    }
    
    func clickBottomButton() {
        if self.viewModel.activityTravelModel?.status.int == 2 {
            // 取消
            YHCommonAlertView.show("", "是否取消报名?", "是", "否", fullGuestureEnable: false) {
                self.cancelActivityApply()
            } callBack: {
            }
            
        } else if self.viewModel.activityTravelModel?.status.int == 4 {
            
            if let nav = self.navigationController {
                let rrr = nav.viewControllers.contains { $0.isKind(of: YHActivityDetailViewController.self) }
                if rrr {
                    
                    var  targetVc: UIViewController?
                    for(_, value) in nav.viewControllers.enumerated() {
                        if value.isKind(of: YHActivityDetailViewController.self) {
                            targetVc = value
                            break
                        }
                    }
                    
                    if let vc = targetVc {
                        navigationController?.popToViewController(vc, animated: true)
                    }
                    return
                }
            }
            
            let vc = YHActivityDetailViewController()
            vc.activityId = String(self.viewModel.activityTravelModel?.id ?? 0)
            vc.activityName = self.viewModel.activityDetailModel?.name ?? ""
            navigationController?.pushViewController(vc)
        }
    }
}

extension YHActivityTravelViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHActivityTravelCell.cellReuseIdentifier, for: indexPath) as? YHActivityTravelCell else { return UITableViewCell() }
        cell.dataModel = viewModel.activityTravelModel
        cell.block = {[weak self] in
            self?.clickBottomButton()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}
