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

import UIKit

class YHActivityDetailViewController: YHBaseViewController {
    var activityId: String = ""
    var activityName: String = ""
    lazy var viewModel: YHActivityViewModel = {
        let vm = YHActivityViewModel()
        return vm
    }()

    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(YHActivityDetailCell.self, forCellReuseIdentifier: YHActivityDetailCell.cellReuseIdentifier)

        tableView.register(YHActivityDetailCell0.self, forCellReuseIdentifier: YHActivityDetailCell0.cellReuseIdentifier)
        tableView.register(YHActivityDetailCell1.self, forCellReuseIdentifier: YHActivityDetailCell1.cellReuseIdentifier)
        tableView.register(YHActivityDetailCell2.self, forCellReuseIdentifier: YHActivityDetailCell2.cellReuseIdentifier)

//        tableView.register(YHActivityDetailInfoCell.self, forCellReuseIdentifier: YHActivityDetailInfoCell.cellReuseIdentifier)

        tableView.tableHeaderView = nil
        tableView.tableFooterView = nil

        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0

        return tableView
    }()

    lazy var topView: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFill
        view.image = UIImage(named: "activity_detail_top_bkg")
        return view
    }()

    lazy var bottomView: YHActivityDetailBottomView = {
        let view = YHActivityDetailBottomView()
        return view
    }()

    // MARK: - 生命周期方法

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

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

extension YHActivityDetailViewController {
    func gotoTheRightVcForStatus() {
        guard let model = viewModel.activityDetailModel else {
            return
        }

        if let status = YHActivityStatus(rawValue: model.status.int ?? 0) {
            switch status {
            case .notApply:
//                printLog("立即报名")
                showApplyUI()
            case .applied:
                printLog("已报名")
                gotoActivityTravelVC()
            case .canceled:
//                printLog("已取消报名")
                showApplyUI()
            case .end:
                printLog("活动已结束")
//                YHHUD.flash(message: "活动已结束")
            case .soldout:
                printLog("已下架")
            default:
                printLog("")
            }
        }
    }

    func gotoActivityTravelVC() {
        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 = viewModel.activityDetailModel?.checkId ?? ""
        navigationController?.pushViewController(vc)
    }

    func showApplyUI() {
        YHApplyActivityAlert.showApplyActivityAlertView(name: viewModel.activityDetailModel?.businessCardName ?? "") { tag, name, number, phone in
            if tag {
                printLog(tag)
                printLog(name)
                printLog(number)
                printLog(phone)
                if tag {
                    let param = ["id": self.activityId,
                                 "name": name,
                                 "mobile": phone,
                                 "number": number]
                    self.applyActivity(param: param)
                }
            }
        }
    }

    func setupUI() {
        gk_navigationBar.isHidden = false
        gk_navigationBar.backgroundColor = .clear
        gk_backImage = UIImage(named: "activity_nav_back")

        view.backgroundColor = .white

        // 1.
        view.addSubview(tableView)
        view.addSubview(bottomView)
        view.addSubview(topView)

        // 2.
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }

        // 3.
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(YHActivityDetailBottomView.viewH)
        }

        bottomView.block = { [weak self] _ in
            // 判断是否登录成功
            if YHLoginManager.shared.isLogin() {
                self?.gotoTheRightVcForStatus()
            } else {
                YHOneKeyLoginManager.shared.oneKeyLogin()
                YHLoginManager.shared.loginSuccessActionBlock = { [weak self] in
                    guard self != nil else { return }
                    self?.loadData()
                    YHLoginManager.shared.loginSuccessActionBlock = nil
                }
            }
        }

        // 4.
        topView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(114)
        }
    }

    func loadData() {
        if !activityId.isEmpty {
            viewModel.getActivityDetailData(activityID: activityId) { success, error in
                if success {
                    self.requestImages()
                    // bottomView
                    self.bottomView.dataModel = self.viewModel.activityDetailModel
                } else {
                    let msg = error?.errorMsg ?? "获取数据出错"
                    YHHUD.flash(message: msg)
                    self.navigationController?.popViewController()
                }

                // tableView
                self.tableView.reloadData()
            }
        } else {
            YHHUD.flash(message: "参数错误")
            navigationController?.popViewController()
        }
    }

    func requestImages() {
        guard let detailModel = viewModel.activityDetailModel else {
            return
        }
        let ossGroup = DispatchGroup()
        for item in detailModel.coverItems {
            ossGroup.enter()
            item.imgView.kf.setImage(with: URL(string: item.url)) { result in
                switch result {
                case let .success(value):
                    let size = value.image.size
                    let scale = size.width > 0 ? Double(size.height / size.width) : 0.0
                    if scale > 0 {
                        item.height = scale * item.width
                    }
                case let .failure(error):
                    print("Job failed: \(error.localizedDescription)")
                }
                ossGroup.leave()
            }
        }
        ossGroup.notify(queue: .main) {
            self.tableView.reloadData()
        }
    }

    func applyActivity(param: [String: Any]) {
        viewModel.applyActivity(param: param) { success, error in
            if success {
                YHHUD.flash(message: "报名成功")
                self.loadData()
                DispatchQueue.main.async {
                    let vc = YHApplyActivityResultViewController()
                    vc.isSuccessFlag = true
                    vc.activityTravelId = self.viewModel.travelModel?.id ?? ""
                    vc.activityName = self.viewModel.activityDetailModel?.name ?? self.activityName
                    self.navigationController?.pushViewController(vc)
                }
            } else {
                if error?.errorCode == 10001 {
                    let vc = YHApplyActivityResultViewController()
                    vc.isSuccessFlag = false
                    vc.activityTravelId = self.viewModel.travelModel?.id ?? ""
                    vc.activityName = self.viewModel.activityDetailModel?.name ?? self.activityName
                    self.navigationController?.pushViewController(vc)
                } else {
                    let msg = error?.errorMsg ?? "报名失败,请重试"
                    YHHUD.flash(message: msg)
                }
            }
        }
    }
}

extension YHActivityDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.arrActivityDetail.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHActivityDetailCell.cellReuseIdentifier, for: indexPath) as? YHActivityDetailCell else {
            return UITableViewCell()
        }
        cell.dataModel = viewModel.activityDetailModel

        if indexPath.row < viewModel.arrActivityDetail.count {
            let model = viewModel.arrActivityDetail[indexPath.row]

            if model.type == 0 {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHActivityDetailCell0.cellReuseIdentifier, for: indexPath) as? YHActivityDetailCell0 else {
                    return UITableViewCell()
                }
                cell.dataModel = model.activityDetailModel ?? YHActivityDetailModel()
                return cell

            } else if model.type == 1 {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHActivityDetailCell1.cellReuseIdentifier, for: indexPath) as? YHActivityDetailCell1 else {
                    return cell
                }
                cell.dataModel = model.activityDetailModel ?? YHActivityDetailModel()
                return cell

            } else if model.type == 2 {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHActivityDetailCell2.cellReuseIdentifier, for: indexPath) as? YHActivityDetailCell2 else {
                    return cell
                }
                cell.dataModel = model.activityDetailModel ?? YHActivityDetailModel()
                return cell
            }
        }
        return cell
    }

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