//
//  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
        return tableView
    }()

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

    // 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 {
    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 {
        var height: CGFloat = 16.0
        if section != 0 {
            height = 20.0
        }
        return height
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var height: CGFloat = 16.0
        if section != 0 {
            height = 20.0
        }

        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth - 16.0 * 2, height: height))
        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
    }
}
