//
//  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 viewModel = YHHKImmigrationRecordsViewModel()
    
    private lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无在港记录", kEmptyCommonBgName)
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 164)
        view.backgroundColor = .clear
        view.isHidden = true
        return view
    }()
    
    private lazy var datas: [YHHKRecordSectionType] = []
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.rowHeight = UITableView.automaticDimension
        view.estimatedRowHeight = 52.0
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(YHHKRecordsHeaderCell.self, forCellReuseIdentifier: YHHKRecordsHeaderCell.cellReuseIdentifier)
        view.register(YHHKRecordsExpandedCell.self, forCellReuseIdentifier: YHHKRecordsExpandedCell.cellReuseIdentifier)
        view.register(YHHKRecordsSectionHeaderCell.self, forCellReuseIdentifier: YHHKRecordsSectionHeaderCell.cellReuseIdentifier)
        view.register(YHHKRecordsLastStayCell.self, forCellReuseIdentifier: YHHKRecordsLastStayCell.cellReuseIdentifier)
        view.register(YHHKRecordsSummaryItemCell.self, forCellReuseIdentifier: YHHKRecordsSummaryItemCell.cellReuseIdentifier)
        view.register(YHHKRecordsDurationItemCell.self, forCellReuseIdentifier: YHHKRecordsDurationItemCell.cellReuseIdentifier)
        view.register(YHHKRecordsOccupyingSpaceCell.self, forCellReuseIdentifier: YHHKRecordsOccupyingSpaceCell.cellReuseIdentifier)
        
        return view
    }()
    
    private let orderId: Int
    init(orderId: Int) {
        self.orderId = orderId
        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)
        requestData()
    }

}

extension YHHKRecordsSummaryVC {
    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(tableView)
        view.addSubview(noDataView)
        
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kMargin).priority(.high)
            make.right.equalToSuperview().offset(-kMargin).priority(.high)
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(164)
        }
        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 requestData() {
        viewModel.getHKImmigrationRecordsSummary(orderId: orderId) { [weak self] recordsSummary, error in
            if let recordsSummary = recordsSummary {
                self?.updateVC(recordsSummary: recordsSummary)
            } else {
                printLog("YHHKRecordsSummaryVC:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self?.noDataView.isHidden = false
                self?.datas = []
                self?.tableView.reloadData()
            }
        }
    }
    
    private func updateVC(recordsSummary: YHHKImmigrationRecordsSummaryModel) {
        guard recordsSummary.list.count > 0 else {
            noDataView.isHidden = false
            datas = []
            tableView.reloadData()
            return
        }
        var sections: [YHHKRecordSectionType] = [.header("在港逗留情况")]
        // 优先过滤大于等于90 .filter { $0.not_in_hk_days >= 90 }
        recordsSummary.list.forEach { [weak self] record in
            guard let self = self else {
                return
            }
            var summaryItems: [YHHKRecordItemDetailType] = [.detailHeader("逗留共\(record.sum_days)天（\(record.sum_times)次）")]
            if record.last_stay_date.count > 0 {
                summaryItems.append(.lastStay("上次逗留：\(self.getShortDateString(record.last_stay_date))"))
            }
            record.statistics.forEach { item in
                let summaryItem = YHHKRecordItemDetailType.summaryItem("\(item.year)年 \(item.sum_days)天（\(item.sum_times)次）")
                summaryItems.append(summaryItem)
            }
            var type: YHHKNonPresenceRecordType = .normal
            var periodItems: [YHHKRecordItemDetailType] = []
            if record.not_in_hk_days >= 90 && record.not_in_hk_days < 180 {
                type = .over90
            } else if record.not_in_hk_days >= 180 {
                type = .over180
            }
            // 产品定的显示超过180天的详细记录
            if record.details.count > 0 {
                periodItems.append(.detailHeader("超180天未在港"))
            }
            record.details.forEach { item in
                let duration = YHHKRecordItemDetailType.duration(self.getShortDateString(item.start_date), self.getShortDateString(item.end_date), "\(item.days)天")
                periodItems.append(duration)
            }
            
            let expandedSec1 = YHHKRecordsExpandedSection(title: record.username, type: type, summaryItems: summaryItems, periodItems: periodItems)
            let section = YHHKRecordSectionType.expandedItem(expandedSec1)
            sections.append(section)
        }
        guard sections.count > 1 else {
            noDataView.isHidden = false
            datas = []
            tableView.reloadData()
            return
        }
        datas = sections
        noDataView.isHidden = true
        tableView.reloadData()
    }
    
    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.subItems.count - 1 {
                cellType = .bottom
            } else {
                cellType = .mid
            }
        case .detailHeader:
            if indexPath.row == model.summaryItems.count {
                cellType = .single
            } else {
                cellType = .top
            }
        default:
            break
        }
        return cellType
    }
    
    private func getShortDateString(_ dateString: String) -> String {
        // 2024-05-20 00:00:00 -> 2024-05-20
        let inputFormatter = DateFormatter()
        inputFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        if let date = inputFormatter.date(from: dateString) {
            let outputFormatter = DateFormatter()
            outputFormatter.dateFormat = "yyyy-MM-dd"
            let formattedDateString = outputFormatter.string(from: date)
            return formattedDateString
        }
        return dateString
    }
}

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)
                let isBottom = (indexPath.section == datas.count - 1) && !model.isExpanded
                cell.setupCellInfo(title: model.title, status: model.type, isExpanded: model.isExpanded, isShowBottomLine: isShowBottomLine, isBottom: isBottom)
                
                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 {
                        let cellType = getSubCellType(model: model, indexPath: indexPath, subType: subType)
                        cell.setupCellInfo(title: title, cellType: cellType)
                        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)
                        let isBottom = indexPath.section == datas.count - 1 && indexPath.row == model.subItems.count
                        cell.setupCellInfo(isShow, isBottom: isBottom)
                        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
    }
}
