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

import UIKit
import JXSegmentedView

class YHResignMaterialListVC: YHBaseViewController {
    // 订单id
    var orderId: Int = 0
    // 批次id
    var batchId: Int = 0
    var viewModel: YHResignMaterialViewModel = YHResignMaterialViewModel()
    
    var items:[YHResignMaterialInfo] = [] {
        didSet {
            self.emptyDataTipsView.isHidden = self.items.count > 0
            self.tableView.reloadData()
        }
    }
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame:.zero, style:.grouped)
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hexString:"#F8F9FB")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHResignMaterialCell.self, forCellReuseIdentifier: YHResignMaterialCell.cellReuseIdentifier)
        tableView.backgroundView = emptyDataTipsView
        
        return tableView
    }()
    
    lazy var emptyDataTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无数据", kEmptyCommonBgName)
        view.topMargin = 168
        view.isHidden = true
        return view
    }()
    
    lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navigationBar.isHidden = true
        createUI()
    }
    
    func createUI() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(KScreenHeight - k_Height_NavigationtBarAndStatuBar - YHResinMaterialManageContainerVC.segmentHeight-4)
        }
        getData()
    }
    
    
    func getData() {
        
        self.tableView.reloadData()
    }
}

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if 0 <= section && section < items.count {
            let list = items[section]
            if list.isUnfold {
                return list.materials.count
            }
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHResignMaterialCell.cellReuseIdentifier, for: indexPath) as! YHResignMaterialCell
        
        if 0 <= indexPath.section && indexPath.section < items.count {
            let list = items[indexPath.section]
            if 0 <= indexPath.row, indexPath.row < list.materials.count {
                let item = list.materials[indexPath.row]
                cell.updateModel(item)
                cell.templateBlock = {
                    [weak self] in
                    guard let self = self else { return }
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.getTemplateInfo(templateId: item.template_id) {
                        [weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else { return }
                        if !success {
                            YHHUD.flash(message: "获取模板失败")
                            return
                        }
                        let view = YHResignTemplateSheetView.templateView(self.viewModel.templateDeail)
                        view.scanTemplateBlock = {
                            [weak self] path in
                            guard let self = self else { return }
                            if let url = path?.fileUrl, !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 list = items[indexPath.section]
            if 0 <= indexPath.row, indexPath.row < list.materials.count {
                let item = list.materials[indexPath.row]
                if item.status == YHMaterialStatus.unOpen.rawValue { // 未开始
                    return
                }
                if item.status == YHMaterialStatus.preUpload.rawValue { // 待上传
                    self.showUploadSheetView(item) {
                        let vc = YHResignMaterialUploadVC()
                        vc.materialId = item.id
                        vc.orderId = self.orderId
                        vc.batchId = self.batchId
                        self.navigationController?.pushViewController(vc)
                    }
                    return
                }
                // 非待上传的进入详情
                let vc = YHResignMaterialUploadVC()
                vc.materialId = item.id
                vc.orderId = self.orderId
                vc.batchId = self.batchId
                self.navigationController?.pushViewController(vc)
            }
        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 56.0 : 52.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        view.tag = section
        
        if 0 <= section && section < items.count {
            
            let titleLabel = UILabel()
            titleLabel.font = UIFont.PFSC_R(ofSize: 15)
            titleLabel.textColor = .mainTextColor
            view.addSubview(titleLabel)
            
            let info = items[section]
            titleLabel.text = info.title
            let img = info.isUnfold ? "resign_material_list_unfold" : "resign_material_list_fold"
            let arrowImgV = UIImageView(image: UIImage(named: img))
            view.addSubview(arrowImgV)
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(didClickSection(_ :)))
            view.addGestureRecognizer(tap)
            
            titleLabel.snp.makeConstraints { make in
                make.left.equalTo(16)
                make.top.equalTo(section == 0 ? 20.0 : 16.0)
                make.right.equalTo(arrowImgV.snp.left)
                make.bottom.equalTo(-16)
            }
            
            arrowImgV.snp.makeConstraints { make in
                make.width.height.equalTo(21.0)
                make.right.equalTo(-16)
                make.top.equalTo(titleLabel)
            }
        }
        return view
    }
    
    @objc func didClickSection(_ gesture: UIGestureRecognizer) {
        if let section = gesture.view?.tag {
            if 0 <= section && section < items.count {
                let info = items[section]
                info.isUnfold = !info.isUnfold
                self.tableView.reloadData()
            }
        }
    }
}


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

extension YHResignMaterialListVC {
    
    func showUploadSheetView(_ material:YHMaterialModel, _ success: (()->())?) {
        let sheetView = YHCertificateUploadSheetView.sheetView()
        sheetView.maxSelectImageCount = 9
        sheetView.tips = "支持的文件格式为jpg/jpeg、png、bmp、doc/docx、xls/xlsx、pdf，最多可上传99张图片或文件"
        sheetView.fileTypes = [ "public.image",
                                "com.adobe.pdf",
                                "com.microsoft.word.doc",
                                "org.openxmlformats.wordprocessingml.document",
                                "org.openxmlformats.spreadsheetml.sheet",
                                "com.microsoft.excel.xls",]
        sheetView.uploadFilesBlock = {
            [weak self] fileUrl in
            guard let self = self else { return }
            print(fileUrl)
            
            self.viewModel.uploadFilesWithMaterial(material:material, fileUrl: fileUrl) {
                [weak self] in
                guard let self = self else { return }
                success?()
            }
        }
        sheetView.uploadImageBlock = {
            [weak self] targetImgArr in
            guard let self = self else { return }
            self.viewModel.uploadImageArr(targetImgArr, material: material) {
                [weak self] in
                guard let self = self else { return }
                success?()
            }
        }
        sheetView.show()
    }
}
