//
//  YHActivityListViewController.swift
//  galaxy
//
//  Created by EDY on 2024/6/17.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import JXSegmentedView
import UIKit

enum YHActivityStatus: Int {
    // 活动的状态 1：立即报名 2：已报名 3：活动结束 4：已取消报名

    case unknow = 0 // 未知
    case notApply = 1 // 立即报名
    case applied = 2 // 已报名
    case end = 3 // 活动结束
    case canceled = 4 // 已取消报名
    case soldout = 5 // 活动下架

    var titleForList: String {
        switch self {
        case .notApply:
            return "立即报名"
        case .applied:
            return "已报名"
        case .end:
            return "活动结束"
        case .canceled:
            return "立即报名"
        case .soldout:
            return "已下架"
        default:
            return ""
        }
    }

    var titleForMyApplyList: String {
        switch self {
        case .notApply:
            return "立即报名"
        case .applied:
            return "已报名"
        case .end:
            return "活动结束"
        case .canceled:
            return "已取消"
        case .soldout:
            return "已下架"
        default:
            return ""
        }
    }

    var titleForDetail: String {
        switch self {
        case .notApply:
            return "立即报名"
        case .applied:
            return "查看行程单"
        case .end:
            return "活动结束"
        case .canceled:
            return "立即报名"
        case .soldout:
            return "已下架"
        default:
            return ""
        }
    }

    var activityColor: UIColor {
        switch self {
        case .notApply:
            return UIColor.brandMainColor
        case .applied:
            return UIColor.successColor
        case .end:
            return UIColor.mainTextColor30
        case .canceled:
            return UIColor.brandMainColor
        case .soldout:
            return UIColor.mainTextColor30
        default:
            return UIColor.clear
        }
    }

    var activityColorForMyApplyList: UIColor {
        switch self {
        case .notApply:
            return UIColor.brandMainColor
        case .applied:
            return UIColor.successColor
        case .end:
            return UIColor.mainTextColor30
        case .canceled:
            return UIColor.mainTextColor30
        case .soldout:
            return UIColor.mainTextColor30
        default:
            return UIColor.clear
        }
    }
}

/*
 活动列表 或 我的报名活动
 */
class YHActivityListViewController: YHBaseViewController {
    var type: Int = 0 // 0-活动列表  1-我的报名活动

    lazy var viewModel: YHActivityViewModel = {
        let vm = YHActivityViewModel()
        return vm
    }()

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHActivityListCell.self, forCellReuseIdentifier: YHActivityListCell.cellReuseIdentifier)
        tableView.backgroundView = self.emptyDataTipsView
        tableView.tableHeaderView = self.headerView
        return tableView
    }()
    
    lazy var headerView: UIView = {
        let radio = 88.0/335.0
        let imgWidth = KScreenWidth - 20.0 * 2
        let imgHeight = imgWidth * radio
        var height = imgHeight + 16.0
        let view = UIView(frame: CGRect(x: 20, y: 0, width: imgWidth, height: height))
        let imgV = UIImageView(frame: CGRect(x: 0, y: 16, width: imgWidth, height: imgHeight))
        imgV.image = UIImage(named: "activity_header_img")
        view.addSubview(imgV)
        let tap = UITapGestureRecognizer(target: self, action: #selector(didHeaderClicked))
        view.addGestureRecognizer(tap)
        return view
    }()

    lazy var emptyDataTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无活动", kEmptyCommonBgName)
        view.topMargin = 222
        view.isHidden = true
        return view
    }()
    
    lazy var messageHandler: YHIMMessageHandler = {
        return YHIMMessageHandler(
            viewController: self,
            navigationController: navigationController
        )
    }()

    // MARK: - 生命周期方法

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        gk_navigationBar.isHidden = true
        gk_navigationBar.backgroundColor = .white

        view.addSubview(tableView)

        if type == 1 {
            gk_navTitle = "我的活动"
            gk_navigationBar.isHidden = false
            gk_navigationBar.backgroundColor = .clear

            tableView.snp.makeConstraints { make in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.bottom.equalToSuperview()
                make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            }
        } else {
            tableView.snp.makeConstraints { make in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.bottom.equalToSuperview()
                make.top.equalToSuperview()
            }
        }

        tableView.es.addYHPullToRefresh {
            self.loadFirstData()
        }

        tableView.es.addInfiniteScrolling {
            self.loadMoreData()
        }

        emptyDataTipsView.isHidden = viewModel.arrActivityListData.count > 0 ? true : false
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadFirstData()
    }
}

extension YHActivityListViewController {
    
    @objc func didHeaderClicked() {
        YHGrayCommonAlertView.show("联系银河管家", "银河可为您组织线下活动，快来与我们聊聊您的需求吧~", "取消", "前往联系", fullGuestureEnable: false) {
            
        } callBack: { [weak self] in
            guard let self = self else {
                return
            }
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.getActiticyYhId { id in
                YHHUD.hide()
                if id.isEmpty {
                    YHHUD.flash(message: "获取银河ID失败")
                    return
                }
                self.messageHandler.gotoChatVC(senderID: id)
            }
        }
    }
    
    func loadMoreData() {
        viewModel.getActivityList(firstFlag: false, type: type) { [weak self] _, _ in
            guard let self = self else { return }
            self.tableView.reloadData()
            self.emptyDataTipsView.isHidden = self.viewModel.arrActivityListData.count > 0 ? true : false

//            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.35, execute: {
            self.tableView.es.stopLoadingMore()
            if self.viewModel.hasMoreForActivityList == false {
                self.tableView.es.noticeNoMoreData()
                self.tableView.footer?.alpha = 1
            }
//            })

            self.tableView.reloadData()
        }
    }

    func loadFirstData() {
        viewModel.getActivityList(firstFlag: true, type: type) { [weak self] _, _ in
            guard let self = self else { return }

            self.tableView.es.stopPullToRefresh()

            self.tableView.reloadData()
            self.emptyDataTipsView.isHidden = self.viewModel.arrActivityListData.count > 0 ? true : false
            self.tableView.es.stopPullToRefresh()
            self.emptyDataTipsView.isHidden = self.viewModel.arrActivityListData.count > 0 ? true : false

            if self.viewModel.hasMoreForActivityList == false {
                self.tableView.es.noticeNoMoreData()
                if self.viewModel.arrActivityListData.count > 0 {
                    self.tableView.footer?.alpha = 1
                } else {
                    self.tableView.footer?.alpha = 0
                }
            }
        }
    }
}

extension YHActivityListViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if viewModel.arrActivityListData.count > 0 {
            return viewModel.arrActivityListData.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHActivityListCell.cellReuseIdentifier, for: indexPath) as? YHActivityListCell else { return UITableViewCell() }
        cell.sessionIndex = indexPath.section
        cell.type = type

        if indexPath.section < viewModel.arrActivityListData.count {
            cell.dataModel = viewModel.arrActivityListData[indexPath.section]
        }
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 185.0
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section < viewModel.arrActivityListData.count {
            let model = viewModel.arrActivityListData[indexPath.section]

            if type == 1 {
                if model.status.int == 2 {
                    gotoActivityTravelVC(checkId: model.checkId)
                    return
                } else if model.status.int == 5 {
                    YHHUD.flash(message: "已下架")
                    return
                }
            }

            let vc = YHActivityDetailViewController()
            vc.activityId = String(model.id)
            vc.activityName = model.name
            navigationController?.pushViewController(vc)
        }
    }

    func gotoActivityTravelVC(checkId: String = "") {
        if let nav = navigationController {
            let rrr = nav.viewControllers.contains { $0.isKind(of: YHActivityTravelViewController.self) }
            if rrr {
                var targetVc: UIViewController?
                for (_, value) in nav.viewControllers.enumerated() {
                    if value.isKind(of: YHActivityTravelViewController.self) {
                        targetVc = value
                        break
                    }
                }

                if let vc = targetVc {
                    navigationController?.popToViewController(vc, animated: true)
                }
                return
            }
        }

        // 行程单详情
        let vc = YHActivityTravelViewController()
        vc.travelId = checkId
        navigationController?.pushViewController(vc)
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20.0
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth - 16.0 * 2, height: 20))
        view.backgroundColor = .clear
        return view
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth - 16.0 * 2, height: 0.001))
        view.backgroundColor = .clear
        return view
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}

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