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

import UIKit
import JXSegmentedView

class YHHKRecordsSummaryVC: YHBaseViewController {
    
    private lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无在港记录", kEmptyCommonBgName)
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 164)
        view.backgroundColor = .clear
        return view
    }()
    
    private lazy var datas: [YHHKRecordSectionType] = {
        let firstSection = YHHKRecordSectionType.header("在港逗留情况")
        let summaryItems1: [YHHKRecordItemDetailType] = [.detailHeader("逗留共300天（2次）"), .lastStay("上次逗留：2024-10-04"), .summaryItem("2024年 270天（2次）"), .summaryItem("2024年 30天（2次）")]
        let periodItems1: [YHHKRecordItemDetailType] = [.detailHeader("超90天未在港"), .duration("2023-10-04", "2023-12-04", "60天"), .duration("2024-12-04", "2023-01-04", "60天")]
        let expandedSec1 = YHHKRecordsExpandedSection(title: "章一刀", type: .over90, summaryItems: summaryItems1, periodItems: periodItems1)
        let secondSection = YHHKRecordSectionType.expandedItem(expandedSec1)
        
        let summaryItems2: [YHHKRecordItemDetailType] = [.detailHeader("逗留共300天（5次）"), .lastStay("上次逗留：2024-10-04"), .summaryItem("2024年 270天（2次）"), .summaryItem("2024年 30天（3次）")]
        let periodItems2: [YHHKRecordItemDetailType] = [.detailHeader("超200天未在港"), .duration("2023-10-04", "2023-12-04", "60天"), .duration("2024-12-04", "2023-01-04", "30天")]
        let expandedSec2 = YHHKRecordsExpandedSection(title: "李晓梅", type: .over180, summaryItems: summaryItems2, periodItems: periodItems2)
        let thirdSection = YHHKRecordSectionType.expandedItem(expandedSec2)
        
        return [firstSection, secondSection, thirdSection]
    }()
    
    private lazy var tableView: YHGestureTableView = {
        let view = YHGestureTableView(frame: .zero, style: .plain)
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.rowHeight = UITableView.automaticDimension
        view.estimatedRowHeight = 52.0
        view.layer.cornerRadius = 6
        view.clipsToBounds = true
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(cellWithClass: YHHKRecordsHeaderCell.self)
        view.register(cellWithClass: YHHKRecordsExpandedCell.self)
        view.register(cellWithClass: YHHKRecordsSectionHeaderCell.self)
        view.register(cellWithClass: YHHKRecordsLastStayCell.self)
        view.register(cellWithClass: YHHKRecordsSummaryItemCell.self)
        view.register(cellWithClass: YHHKRecordsDurationItemCell.self)
        view.register(cellWithClass: YHHKRecordsOccupyingSpaceCell.self)
        
        return view
    }()

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

}

extension YHHKRecordsSummaryVC {
    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kMargin).priority(.high)
            make.right.equalToSuperview().offset(-kMargin).priority(.high)
            make.top.bottom.equalToSuperview()
        }
        tableView.tableHeaderView = UIView(frame: CGRect.init(x: 0, y: 0, width: KScreenWidth, height: kMargin))
        tableView.tableFooterView = UIView(frame: CGRect.init(x: 0, y: 0, width: KScreenWidth, height: kMargin))
    }
    
    private func getSubCellType(model: YHHKRecordsExpandedSection, indexPath: IndexPath, subType: YHHKRecordItemDetailType) -> YHResignRoundCellType {
        var cellType: YHResignRoundCellType = .top
        switch subType {
        case .lastStay, .summaryItem:
            if indexPath.row == model.summaryItems.count {
                cellType = .bottom
            } else {
                cellType = .mid
            }
        case .duration:
            if indexPath.row == model.periodItems.count {
                cellType = .bottom
            } else {
                cellType = .mid
            }
        default:
            break
        }
        return cellType
    }
}

extension YHHKRecordsSummaryVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        let secType = datas[section]
        switch secType {
        case .header:
            return 1
        case let .expandedItem(model):
            return model.isExpanded ? model.subItems.count + 1 : 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let secType = datas[indexPath.section]
        switch secType {
        case let .header(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsHeaderCell.cellReuseIdentifier) as? YHHKRecordsHeaderCell {
                cell.setupCellInfo(title)
                return cell
            }
        case let .expandedItem(model):
            if indexPath.row == 0, let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsExpandedCell.cellReuseIdentifier) as? YHHKRecordsExpandedCell {
                let isShowBottomLine = !model.isExpanded && (indexPath.section != datas.count - 1)
                cell.setupCellInfo(title: model.title, status: model.type, isExpanded: model.isExpanded, isShowBottomLine: isShowBottomLine)
                return cell
            }
            if model.isExpanded, model.subItems.count > indexPath.row - 1, indexPath.row - 1 >= 0 {
                let subType = model.subItems[indexPath.row - 1]
                switch subType {
                case let .summaryItem(title):
                    if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsSummaryItemCell.cellReuseIdentifier) as? YHHKRecordsSummaryItemCell {
                        let cellType = getSubCellType(model: model, indexPath: indexPath, subType: subType)
                        cell.setupCellInfo(title: title, cellType: cellType)
                        return cell
                    }
                case let .detailHeader(title):
                    if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsSectionHeaderCell.cellReuseIdentifier) as? YHHKRecordsSectionHeaderCell {
                        cell.setupCellInfo(title: title, cellType: .top)
                        return cell
                    }
                case let .lastStay(title):
                    if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsLastStayCell.cellReuseIdentifier) as? YHHKRecordsLastStayCell {
                        let cellType = getSubCellType(model: model, indexPath: indexPath, subType: subType)
                        cell.setupCellInfo(title: title, cellType: cellType)
                        return cell
                    }
                case let .duration(from, to, total):
                    if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsDurationItemCell.cellReuseIdentifier) as? YHHKRecordsDurationItemCell {
                        let cellType = getSubCellType(model: model, indexPath: indexPath, subType: subType)
                        cell.setupCellInfo(title: "\(from)至\(to)", detail: total, cellType: cellType)
                        return cell
                    }
                case .occupyingSpace:
                    if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsOccupyingSpaceCell.cellReuseIdentifier) as? YHHKRecordsOccupyingSpaceCell {
                        let isShow = indexPath.row == model.subItems.count && (indexPath.section != datas.count - 1)
                        cell.setupCellInfo(isShow)
                        return cell
                    }
                }
            }
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard datas.count > indexPath.section else {
            return 0
        }
        let secType = datas[indexPath.section]
        switch secType {
        case .header:
            return 52
        case let .expandedItem(model):
            if indexPath.row == 0 {
                return 54
            } else if model.isExpanded, model.subItems.count > indexPath.row - 1, indexPath.row - 1 >= 0 {
                let subType = model.subItems[indexPath.row - 1]
                switch subType {
                case .summaryItem, .lastStay, .duration:
                    return UITableView.automaticDimension
                case .detailHeader:
                    return 46
                case .occupyingSpace:
                    return 16
                }
            }
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard datas.count > indexPath.section else {
            tableView.deselectRow(at: indexPath, animated: true)
            return
        }
        var secType = datas[indexPath.section]
        if case var .expandedItem(model) = secType, indexPath.row == 0 {
            model.isExpanded.toggle()
            secType = .expandedItem(model)
            datas[indexPath.section] = secType
            tableView.performBatchUpdates { [weak tableView] in
                tableView?.reloadSections(IndexSet(integer: indexPath.section), with: .automatic)
            }
        }
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
}

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