//
//  YHCertificateResourceUploadVC.swift
//  galaxy
//
//  Created by edy on 2024/3/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView
import UniformTypeIdentifiers
import IQKeyboardManagerSwift
import SwifterSwift

class YHGCCertificateListVC: YHBaseViewController {

    var orderId: Int?
    var status: YHCertificateUploadStatus = .all
    var items: [YHSupplementInfo] = []
    var viewModel: YHCertificateViewModel = YHCertificateViewModel()
    var categoryInfo: YHCategoryData!
    lazy var previewFileTool: YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hexString: "#F8F8F8")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateInfoCell.self, forCellReuseIdentifier: YHCertificateInfoCell.cellReuseIdentifier)
        tableView.backgroundView = emptyDataTipsView
        return tableView
    }()
    
    lazy var emptyDataTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("没有找到相关资料哦~", kEmptyCommonBgName)
        view.topMargin = 130
        view.isHidden = false
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navigationBar.isHidden = true
        createUI()
        requestList(status: status)
    }
    
    func createUI() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(KScreenHeight - k_Height_NavigationtBarAndStatuBar - YHCertificateListContainerVC.segmentHeight)
        }
    }
}

extension YHGCCertificateListVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateInfoCell.cellReuseIdentifier, for: indexPath) as? YHCertificateInfoCell else { return UITableViewCell() }
        
        if 0 <= indexPath.section && indexPath.section < items.count {
            let item = items[indexPath.section]
            cell.updateModel(item)
            cell.templateBlock = {
                [weak self] in
                guard let self = self else { return }
                let view = YHCertificateTemplateSheetView.templateView(item.templateInfo)
                view.scanTemplateBlock = {
                    [weak self] path in
                    guard let self = self else { return }
                    if let url = path?.url, !url.isEmpty {
                        print(url)
                        self.previewFileTool.openXLSXRemoteFile(urlString: url, fileName: "预览")
                    }
                }
                view.show()
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        if 0 <= indexPath.section && indexPath.section < items.count {
            let item = items[indexPath.section]
            
            if item.checkStatus == YHCertificateUploadStatus.preUpload.rawValue { // 待上传
                showUploadSheetView(supplementId: item.id)
                return
            }
            // 非待上传的进入详情
            let vc = YHGCCertificateUploadContentListVC()
            vc.orderId = orderId ?? 0
            vc.categoryId = categoryInfo.categoryId
            vc.supplementId = item.id
            self.navigationController?.pushViewController(vc)
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 14.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return UIView()
    }
}

// MARK: - JXSegmentedListContainerViewListDelegate
extension YHGCCertificateListVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension YHGCCertificateListVC {
    
    func requestList(status: YHCertificateUploadStatus, extra: [String: Any] = [:]) {
        
        /*
        // 状态
        "status_all": "",
        // 类型
        "template_cate_id": "",
        // 搜索
        "keywork": "",
         */
        
        var params: [String: Any] = [
                                    "order_id": orderId ?? 0,
                                    "node": "1",
                                    "state": "1",
                                    "category_id": categoryInfo.categoryId,
                                    "supplement_ids": []]
        if !extra.isEmpty {
           params += extra
        }
        
        print(params)
        // state: 3:待上传 2:已驳回 1:已完成 0:审核中
        viewModel.getCertificateList(params: params) {
            
            [weak self] listInfo, error in
            guard let self = self else { return }
            
            items.removeAll()
            if let listInfo = listInfo {
                let arr = listInfo.supplementList
                var results: [YHSupplementInfo] = []
                if status == .all {
                    results.append(contentsOf: arr)
                } else {
                    for item in arr {
                        if item.checkStatus == status.rawValue {
                            results.append(item)
                        }
                    }
                }
                items.append(contentsOf: results)
            }
            // 数量统计
            NotificationCenter.default.post(name: countStatisticsNotify, object: [self.status: items.count])
            emptyDataTipsView.isHidden = items.count > 0
            self.tableView.reloadData()
            
            if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                YHHUD.flash(message: errorMsg, duration: 3)
            }
        }
    }
    
    func showUploadSheetView(supplementId: Int) {
        let orderID = self.orderId ?? 0
        self.viewModel.showUploadSheetView(supplementId: supplementId) {
            [weak self] in
            guard let self = self else { return }
            DispatchQueue.main.async {
                 let vc = YHGCCertificateUploadContentListVC()
                 vc.orderId = orderID
                 vc.categoryId = self.categoryInfo.categoryId
                 vc.supplementId = supplementId
                 self.navigationController?.pushViewController(vc)
            }
        }
    }
}
