//
//  HistoricalShootingInfoViewController.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 历史拍摄信息详情页。
final class HistoricalShootingInfoViewController: BaseViewController, UITableViewDataSource {

    private let orderNumber: String
    private let orderAPI: OrderAPI
    private var response: MultiTravelShootHistoryResponse?
    private let tableView = UITableView(frame: .zero, style: .insetGrouped)

    init(orderNumber: String, orderAPI: OrderAPI? = nil) {
        self.orderNumber = orderNumber
        self.orderAPI = orderAPI ?? NetworkServices.shared.orderAPI
        super.init(nibName: nil, bundle: nil)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setupNavigationBar() {
        title = "历史拍摄"
    }

    override func setupUI() {
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { $0.edges.equalToSuperview() }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        Task { await loadData() }
    }

    private func loadData() async {
        showLoading()
        defer { hideLoading() }
        do {
            response = try await orderAPI.shootHistory(orderNumber: orderNumber)
            tableView.reloadData()
        } catch {
            showToast(error.localizedDescription)
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int { 1 }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        response?.photogSpotList.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
        guard let spot = response?.photogSpotList[indexPath.row] else { return cell }
        cell.textLabel?.text = spot.scenicSpotName
        cell.detailTextLabel?.text = "\(spot.photographerDisplayName) · \(spot.files.count)个素材"
        cell.accessoryType = .disclosureIndicator
        return cell
    }
}
