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

import UIKit

class YHResignDocumentDetailViewController: YHBaseViewController {
    
    private var editEvent: (() -> Void)?
    private var submitEvent: (() -> Void)?
    private var signatureConfirmationEvent: (() -> Void)?
    private var previewEvent: (() -> Void)?
    private var infoConfirmationEvent: (() -> Void)?

    enum RowType {
        case tips(_ title: String, _ detail: NSAttributedString)
        case content(_ title: String, _ fileName: String, _ status: YHResignDocumentStatus, _ config: YHResignDocumentStatusCell.ButtonsConfig)
    }
    
    private var datas: [[RowType]] {
        let normalText = "请主申请人完成电子签字请您尽快核对信息，如信息有误，可进行在线编辑如信息无误，"
        let attText = "请您在右下角的位置完成电子签字"
        let attStr = NSMutableAttributedString(string: normalText + attText)
        attStr.setAttributes([.foregroundColor: UIColor.brandMainColor], range: NSRange(location: normalText.count, length: attText.count))
        let config = getStatusButtonsConfig(docType: docType, status: status)
        let firstSetcion: [RowType] = [.tips("​填写指引", attStr)]
        let secondSetcion: [RowType] = [.content("文书稿件", "雇主的推荐信(仅签字)深圳华为科技有限公司.doc", .awaitingSignature, config)]
        
        return [firstSetcion, secondSetcion]
    }
    
    private var docType: YHResignDocumentType
    private var status: YHResignDocumentStatus = .awaitingSignature
    init(_ docType: YHResignDocumentType,  _ status: YHResignDocumentStatus) {
        self.docType = docType
        self.status = status
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    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.tableFooterView = UITableViewHeaderFooterView()
        view.rowHeight = UITableView.automaticDimension
        view.register(YHResignDocumentTipsCell.self, forCellReuseIdentifier: YHResignDocumentTipsCell.cellReuseIdentifier)
        view.register(YHResignDocumentStatusCell.self, forCellReuseIdentifier: YHResignDocumentStatusCell.cellReuseIdentifier)
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        editEvent = {
            print("###editEvent")
        }
        
        submitEvent = {
            print("###submitEvent")
        }
        
        signatureConfirmationEvent = {
            print("###signatureConfirmationEvent")
        }
        
        previewEvent = {
            print("###previewEvent")
        }
        
        infoConfirmationEvent = {
            print("###infoConfirmationEvent")
        }
        tableView.reloadData()
    }
}

extension YHResignDocumentDetailViewController {
    private func setupUI() {
        gk_navTitle = docType.title
        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 YHResignDocumentDetailViewController: 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]
        
        switch item {
        case let .tips(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentTipsCell.cellReuseIdentifier) as? YHResignDocumentTipsCell {
                cell.setupCellInfo(title: title, detail: detail)
                return cell
            }
        case let .content(title, fileName, status, config):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentStatusCell.cellReuseIdentifier) as? YHResignDocumentStatusCell {
                cell.setupCellInfo(title: title, fileName: fileName, status: status, buttonsConfig: config)
                return cell
            }
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
}

extension YHResignDocumentDetailViewController {
    private func getStatusButtonsConfig(docType: YHResignDocumentType, status: YHResignDocumentStatus) -> YHResignDocumentStatusCell.ButtonsConfig {
        var config = YHResignDocumentStatusCell.ButtonsConfig()
        /*
         private var editEvent: (() -> Void)?
         private var submitEvent: (() -> Void)?
         private var signatureConfirmationEvent: (() -> Void)?
         private var previewEvent: (() -> Void)?
         private var infoConfirmationEvent: (() -> Void)?
         */
        var actions: [(() -> Void)] = []
        switch docType {
        case .powerOfAttorney, .settlementPlan, .explanatoryStatement:
            switch status {
            case .pendingConfirmation, .awaitingSignature:
                config.names = ["在线编辑", "提交", "签字确认"]
                if let editEvent = editEvent {
                    actions.append(editEvent)
                }
                if let submitEvent = submitEvent {
                    actions.append(submitEvent)
                }
                if let signatureConfirmationEvent = signatureConfirmationEvent {
                    actions.append(signatureConfirmationEvent)
                }
                config.actions = actions
                config.style = .three
            case .finalizing, .underReview, .completed:
                if let previewEvent = previewEvent {
                    actions.append(previewEvent)
                }
                config.names = ["查看"]
                config.actions = actions
                config.style = .one
            }
        case .qmasDoc:
            switch status {
            case .pendingConfirmation:
                if let infoConfirmationEvent = infoConfirmationEvent {
                    actions.append(infoConfirmationEvent)
                }
                config.names = ["信息确认"]
                config.actions = actions
                config.style = .one
            case .finalizing, .underReview, .completed:
                if let previewEvent = previewEvent {
                    actions.append(previewEvent)
                }
                config.names = ["查看"]
                config.actions = actions
                config.style = .one
            case .awaitingSignature:
                if let infoConfirmationEvent = infoConfirmationEvent {
                    actions.append(infoConfirmationEvent)
                }
                if let signatureConfirmationEvent = signatureConfirmationEvent {
                    actions.append(signatureConfirmationEvent)
                }
                config.names = ["信息确认", "签字确认"]
                config.actions = actions
                config.style = .two
            }
        }
        return config
    }
}
