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

import UIKit
import JXSegmentedView

class YHHKRecordsContentVC: YHBaseViewController {
    enum UserType: Int {
        case main = 1
        case spouse = 2
        case children = 3
    }
    
    enum RowType {
        case customer(_ title: String, _ detail: String)
        case info(_ title: String, _ detail: String, _ topMargin: CGFloat = 18, _ bottomMargin: CGFloat = 18)
        case remark(_ title: String, _ detail: String)
        case edit(_ title: String, _ editModel: YHHKImmigrationEditRecordModel)
    }
    
    private lazy var viewModel = YHHKImmigrationRecordsViewModel()
    
    private var datas: [[RowType]] = []
    
    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 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.register(YHHKRecordsCustomerItemCell.self, forCellReuseIdentifier: YHHKRecordsCustomerItemCell.cellReuseIdentifier)
        view.register(YHHKRecordsInfoItemCell.self, forCellReuseIdentifier: YHHKRecordsInfoItemCell.cellReuseIdentifier)
        view.register(YHHKRecordsRemarkCell.self, forCellReuseIdentifier: YHHKRecordsRemarkCell.cellReuseIdentifier)
        view.register(YHHKRecordsEditButtonCell.self, forCellReuseIdentifier: YHHKRecordsEditButtonCell.cellReuseIdentifier)
        return view
    }()
    
    private let orderId: Int
    private let userType: UserType
    init(orderId: Int, userType: UserType) {
        self.orderId = orderId
        self.userType = userType
        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 YHHKRecordsContentVC {
    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()
            make.right.equalToSuperview()
            make.top.bottom.equalToSuperview()
        }
        
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(164)
        }
        
        tableView.tableFooterView = UIView(frame: CGRect.init(x: 0, y: 0, width: KScreenWidth, height: kMargin))
    }
    
    private func requestData() {
        viewModel.getHKImmigrationRecordsSingle(orderId: orderId, userType: userType.rawValue) { [weak self] recordsSingleModel, error in
            if let recordsSingleModel = recordsSingleModel {
                self?.updateVC(recordsSingleModel: recordsSingleModel)
            } else {
                printLog("YHHKRecordsContentVC:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self?.noDataView.isHidden = false
                self?.datas = []
                self?.tableView.reloadData()
            }
        }
    }
    
    private func updateVC(recordsSingleModel: YHHKImmigrationRecordsSingleModel) {
        guard recordsSingleModel.list.count > 0 else {
            noDataView.isHidden = false
            datas = []
            tableView.reloadData()
            return
        }
        var sections: [[RowType]] = []
        recordsSingleModel.list.forEach { record in
            var section: [RowType] = [.customer("客户", record.updated_at)]
            let name = record.users.reduce("") { partialResult, item in
                partialResult.count > 0 ? partialResult + "、" + item.user_name : partialResult + item.user_name
            }
            section.append(.info("逗留人员：", name, 18, 9))
            section.append(.info("出入境时间：", "\(record.start_date) ~ \(record.end_date)", 9, 18))
            if record.remark.count > 0 {
                section.append(.remark("备注：", record.remark))
            }
            let editModel = YHHKImmigrationEditRecordModel()
            editModel.id = record.id
            editModel.order_id = orderId
            editModel.users = record.users
            editModel.start_date = record.start_date
            editModel.end_date = record.end_date
            editModel.remark = record.remark
            
            section.append(.edit("编辑", editModel))
            sections.append(section)
        }
        guard sections.count > 0 else {
            noDataView.isHidden = false
            datas = []
            tableView.reloadData()
            return
        }
        datas = sections
        noDataView.isHidden = true
        tableView.reloadData()
    }
}

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

extension YHHKRecordsContentVC: 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 sectionArr = datas[section]
        return sectionArr.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 row = sectionArr[indexPath.row]
        switch row {
        case let .customer(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsCustomerItemCell.cellReuseIdentifier) as? YHHKRecordsCustomerItemCell {
                cell.setupCellInfo(title: title, detail: detail)
                return cell
            }
        case let .info(title, detail, top, bottom):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsInfoItemCell.cellReuseIdentifier) as? YHHKRecordsInfoItemCell {
                cell.setupCellInfo(title: title, detail: detail, topMargin: top, bottomMargin: bottom)
                return cell
            }
        case let .remark(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsRemarkCell.cellReuseIdentifier) as? YHHKRecordsRemarkCell {
                cell.setupCellInfo(title: title, detail: detail)
                return cell
            }
        case let .edit(title, _):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsEditButtonCell.cellReuseIdentifier) as? YHHKRecordsEditButtonCell {
                cell.setupCellInfo(title: title)
                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 row = sectionArr[indexPath.row]
        if case let .edit(_, editModel) = row {
            let vc = YHHKRecordsEditContentVC(orderId: orderId, pageType: .edit, editModel: editModel)
            navigationController?.pushViewController(vc)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard datas.count > indexPath.section else {
            return 0
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return 0
        }
        let row = sectionArr[indexPath.row]
        switch row {
        case .customer:
            return 52
        case .info:
            return UITableView.automaticDimension
        case .remark:
            return 146
        case .edit:
            return 52
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
}
