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

import UIKit

class YHCertificateSearchViewController: YHBaseViewController {

    var items:[YHSupplementInfo] = []
    var viewModel: YHCertificateViewModel = YHCertificateViewModel()
    var orderId : Int?
    var categoryInfo: YHCategoryData?

    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 previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    lazy var searchView:UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(searchBar)
        searchBar.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(16)
            make.size.equalTo(CGSize(width: KScreenWidth-32.0, height:YHCertificateSearchBar.height))
        }
        return view
    }()
    
    lazy var searchBar: YHCertificateSearchBar = {
        let bar = YHCertificateSearchBar(frame:CGRect(x: 0, y: 0, width:KScreenWidth-32, height:YHCertificateSearchBar.height))
        bar.searchBlock = {
            [weak self] text in
            guard let self = self else { return }
            requestList(keyWord: text)
        }
        bar.textChange = {
            [weak self] text in
            guard let self = self else { return }
            if isEmptyString(text) {
                requestList(keyWord: "")
            }
        }
        return bar
    }()
    
    lazy var emptyDataTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("没有找到相关资料哦~", kEmptySearchBgName)
        view.topMargin = 130
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "资料搜索".local
        createUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.requestList(keyWord: searchBar.textField.text)
    }
    
    func createUI() {
        view.addSubview(searchView)
        view.addSubview(tableView)
        searchView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(32+YHCertificateSearchBar.height)
        }
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(searchView.snp.bottom)
        }
    }
}

extension YHCertificateSearchViewController: 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 {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateInfoCell.cellReuseIdentifier, for: indexPath) as! YHCertificateInfoCell
        
        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 = YHCertificateUploadContentListVC()
            vc.orderId = orderId ?? 0
            vc.categoryId = self.categoryInfo?.categoryId ?? 0
            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()
    }
}

extension YHCertificateSearchViewController {
    
    func requestList(keyWord:String?) {
        
        /*
         // 状态
         "status_all": "",
         // 类型
         "template_cate_id": "",
         // 搜索
         "keyword": "",
         */
        let keywords = keyWord ?? ""
        let params:[String:Any] = [
                                    "node": "1",
                                    "state": "1",
                                    "supplement_ids": [],
                                    "order_id" : orderId ?? 0,
                                    "keyword": keywords]
        
        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 {
                categoryInfo = listInfo.categoryData
                let arr = listInfo.supplementList
                items.append(contentsOf: arr)
            }
            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
        let categoryId = self.categoryInfo?.categoryId ?? 0
        self.viewModel.showUploadSheetView(supplementId: supplementId) {
            [weak self] in
            guard let self = self else { return }
            DispatchQueue.main.async {
                 let vc = YHCertificateUploadContentListVC()
                 vc.orderId = orderID
                 vc.categoryId = categoryId
                 vc.supplementId = supplementId
                 self.navigationController?.pushViewController(vc)
            }
        }
    }
}
