//
//  YHResignDocumentManagementVC.swift
//  galaxy
//
//  Created by alexzzw on 2024/9/10.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHResignDocumentManagementVC: YHBaseViewController {
    
    enum RowType {
        case header(_ title: String, _ detail: String)
        case content(_ title: String, _ status: YHResignDocumentStatus, _ docId: Int)
    }
    private var datas: [[RowType]] = []
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame:.zero, style:.grouped)
        view.estimatedSectionHeaderHeight = 16.0
        view.estimatedSectionFooterHeight = 0.01
        view.sectionHeaderHeight = 16.0
        view.sectionFooterHeight = 0.01
        view.contentInsetAdjustmentBehavior = .never
        view.showsVerticalScrollIndicator = false
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.rowHeight = 52
        view.tableFooterView = UITableViewHeaderFooterView()
        view.register(YHResignDocumentHeaderCell.self, forCellReuseIdentifier: YHResignDocumentHeaderCell.cellReuseIdentifier)
        view.register(YHResignDocumentContentCell.self, forCellReuseIdentifier: YHResignDocumentContentCell.cellReuseIdentifier)
        return view
    }()
    
    private lazy var viewModel = YHResignDocumentViewModel()
    // 进签字再出来就要显示loading
    private var isNeedShowLoading: Bool = true
    private let orderId: Int
    private var id: Int = 0
    
    init(orderId: Int, id: Int = 0) {
        self.orderId = orderId
        self.id = id
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let needLoading = isNeedShowLoading
        isNeedShowLoading = false
        requestData(isNeedLoading: needLoading)
    }
}

extension YHResignDocumentManagementVC {
    private func setupUI() {
        gk_navTitle = "续签文书管理"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview()
        }
    }
}

extension YHResignDocumentManagementVC {
    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getDocumentList(orderId: orderId, id: id) { [weak self] success, error in
            if isNeedLoading {
                YHHUD.hide()
            }
            if success {
                self?.updateVC()
            } else {
                printLog("YHResignDocumentManagementVC:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self?.datas = []
                self?.tableView.reloadData()
            }
        }
    }
    
    private func updateVC() {
        guard viewModel.documentList.data.count > 0 else {
            datas = []
            tableView.reloadData()
            return
        }
        let list = viewModel.documentList.data
        datas = list.compactMap ({ documentModel in
            guard let state = YHResignDocumentStage(rawValue: documentModel.stage) else {
                return nil
            }
            var section: [RowType] = [.header(state.title(), "(\(documentModel.applyName))")]
            documentModel.docs.forEach { detailModel in
                if let docType = YHResignDocumentType(rawValue: detailModel.docType), let status = YHResignDocumentStatus.getStatus(detailModel.docStatus) {
                    let row = RowType.content(docType.title, status, detailModel.id)
                    section.append(row)
                }
            }
            return section
        })
        tableView.reloadData()
    }
}

extension YHResignDocumentManagementVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        datas.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        return datas[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return UITableViewCell()
        }
        let item = sectionArr[indexPath.row]
        var cellType: YHResignRoundCellType = .mid
        
        if sectionArr.count == 1 {
            cellType = .single
        } else if indexPath.row == 0 {
            cellType = .top
        } else if indexPath.row == sectionArr.count - 1 {
            cellType = .bottom
        } else {
            cellType = .mid
        }
        
        switch item {
        case let .header(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentHeaderCell.cellReuseIdentifier) as? YHResignDocumentHeaderCell {
                cell.setupCellInfo(title: title, detail: detail, cellType: cellType)
                return cell
            }
        case let .content(title, status, _):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentContentCell.cellReuseIdentifier) as? YHResignDocumentContentCell {
                cell.setupCellInfo(title: title, cellType: cellType, status: status)
                return cell
            }
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard datas.count > indexPath.section else {
            return
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return
        }
        let item = sectionArr[indexPath.row]
        
        switch item {
        case .header:
            return
        case let .content(title, _, docId):
            let controller = YHResignDocumentDetailViewController(docId, title)
            navigationController?.pushViewController(controller)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
}
