//
//  YHAdopterIncomeDetailViewController.swift
//  galaxy
//
//  Created by EDY on 2024/8/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

class YHAdopterIncomeDetailViewController: YHBaseViewController {

    var tableView: UITableView!
    var nextButton: UIButton!
    var clickIndex = -1
    var file: [YHWorkExperienceFileModel] = []
    var data: YHAdopterDepositModel = YHAdopterDepositModel()
    var viewModel: YHAdopterIncomeViewModel = YHAdopterIncomeViewModel()
    var orderId: Int = 0

    lazy var previewFileTool: YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "上传存款证明"
        setView()
        getData()
    }
    
    func getData() {
        guard let resultModels = [YHAdopterFileModel].deserialize(from: data.urls) else {
            return
        }
        for item in resultModels {
            var tempFile = YHWorkExperienceFileModel()
            tempFile.fileName = item.name 
            tempFile.fileUrl = item.url 
            tempFile.uploadedAt = item.upload_date 
            file.append(tempFile)
        }
        tableView.reloadData()
    }
    
    func setView() {
        view.backgroundColor = .white
        tableView = {
            let tableView = UITableView(frame: .zero, style: .plain)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHAdopterIncomeTitleTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterIncomeFileTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterUploadTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterIncomeFileCountTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 8)
            make.bottom.left.right.equalTo(view)
        }
    
        nextButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.brandMainColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("确认", for: .normal)
            button.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(nextStep), for: .touchUpInside)
            return button
        }()
        view.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-8 - k_Height_safeAreaInsetsBottom())
            make.height.equalTo(48)
        }
        
        if data.status == 0 || data.status == 1 {
            nextButton.isHidden = true
        }
    }
    
    @objc func nextStep() {
        if file.count != 0 {
            viewModel.postDepositUpload(file: file, orderId: orderId) {[weak self] _, _ in
                guard let self = self else { return }
                self.navigationController?.popViewController(animated: true)
            }
        } else {
            YHHUD.flash(message: "请上传证明文件")
        }
    }
        
    func getFileNameWithoutSuffix(_ string: String) -> String {
        if string.isEmpty {
            return string
        }
        if !string.contains(".") {
            return string
        }
        if !string.pathExtension.isEmpty {
          let fileName = (string as NSString).deletingPathExtension
          return fileName
        }
        return ""
    }
    
    func uploadImage(_ img: UIImage, imageName: String, callBack: ((Bool, String) -> Void)?) {
        // 先OSS上传得到URL
        self.viewModel.uploadImage(img) {
            [weak self] url, _ in
            guard self != nil else { return }
            if let url = url, !url.isEmpty {
                callBack?(true, url)
                return
            }
            callBack?(false, "")
        }
    }
    
    func uploadFile(_ fileUrl: URL) {
        if let fileData = try? Data(contentsOf: fileUrl) {
            // 将文件数据上传到服务器
            let size = String(format: "%.2fM", Double(fileData.count)/(1024.0 * 1024.0))
//            print("\(size)")
            // 先OSS上传得到URL
            YHHUD.show(.progress(message: "上传中..."))
            self.viewModel.uploadFile(fileUrl.absoluteString) {
                [weak self] successUrl, error in
                
                YHHUD.hide()
                
                guard let self = self else { return }
                
                // 再调用业务接口
                if let successUrl = successUrl, !successUrl.isEmpty {
                    var fileName = fileUrl.lastPathComponent
                    if fileName.isEmpty {
                        fileName = successUrl.lastPathComponent
                    }
                    let suffixName = successUrl.pathExtension.lowercased()
                    let timestamp = Date().timeIntervalSince1970
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "yyyy.MM.dd HH:mm:ss"
                    let currentDate = Date()
                    let formattedDate = dateFormatter.string(from: currentDate)
                    let model = YHWorkExperienceFileModel()
                    model.fileUrl = successUrl
                    model.fileName = fileName
                    model.uploadedAt = formattedDate
                    self.file.append(model)
                    self.tableView.reloadData()
                    YHHUD.flash(message: "上传成功")
                    return
                }
                var msg = "上传文件失败"
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    msg = errorMsg
                }
                YHHUD.flash(message: msg)
            }
        } else {
            YHHUD.flash(message: "识别文件失败")
        }
    }
}

extension YHAdopterIncomeDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if data.status == 0 || data.status == 1 {
            return 2
        }
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterIncomeTitleTableViewCell.self)
            cell.dataSource = data
            return cell
        }
        if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterIncomeFileTableViewCell.self)
            cell.dataSource = self.file
            cell.experienceListBlock = {[weak self] model, type in
                guard let self = self else { return }
                if type == .click {
                    self.viewModel.getPublicImageUrl(model.fileUrl) { success, _ in
                        YHHUD.hide()
                        if let success = success {
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "")
                        }
                    }
                }
                if type == .delete {
                    var items = [YHCertificateEditItem(type: .preview, title: "预览"),
                                 YHCertificateEditItem(type: .rename, title: "重命名"),
                                 YHCertificateEditItem(type: .delete, title: "删除"),
                                 YHCertificateEditItem(type: .cancel, title: "取消")]
                    if data.status == 0 || data.status == 1 {
                        items = [YHCertificateEditItem(type: .preview, title: "预览"),
                                 YHCertificateEditItem(type: .cancel, title: "取消")]
                    }
                    
                    YHCertificateEditSheetView.sheetView(items: items) {
                        [weak self] editType in
                        guard let self = self else { return }
                        if editType == .rename {
                            IQKeyboardManager.shared.isEnabled = false
                            var name = getFileNameWithoutSuffix(model.fileName)
                            if name.count > 30 {
                                name = name[safe: ..<30]!
                            }
                            let view = YHPrincipleFileRenameView.renameView(name: name)
                            view.confirmBlock = {
                                [weak self] text in
                                guard let self = self else { return }
                                model.fileName = text
                                self.tableView.reloadData()
                            }
                            view.show()
                        } else if editType == .delete { // 删除
                            for (index, item) in file.enumerated() {
                                if item.fileUrl == model.fileUrl {
                                    file.remove(at: index)
                                }
                            }
                            self.tableView.reloadData()
                        } else if editType == .preview { // 预览
                            self.viewModel.getPublicImageUrl(model.fileUrl) { success, _ in
                                YHHUD.hide()
                                if let success = success {
                                    self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "")
                                }
                            }
                        }
                    }.show()
                }
            }
            return cell
        }
        if indexPath.row == 2 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterUploadTableViewCell.self)
            cell.newFileBlock = {[weak self] in
                guard let self = self else { return }
                let count = self.file.count
                if count >= 10 {
                    YHHUD.flash(message: "最多上传10个图片或文件")
                    return
                }
                var maxCount = 10 - count
                if maxCount > 9 {
                    maxCount = 9
                }
                let sheetView = YHCertificateUploadSheetView.sheetView()
                sheetView.tips = "支持的文件格式为jpg/jpeg、png、pdf，最多可上传10张图片或文件"
                sheetView.maxSelectImageCount = maxCount
                sheetView.fileTypes = [ "public.image",
                                        "com.adobe.pdf"]
                sheetView.uploadFilesBlock = {
                    [weak self] fileUrl in
                    guard let self = self else { return }
                    print(fileUrl)
                    uploadFile(fileUrl)
                }
                sheetView.uploadImageBlock = {
                    [weak self] imgArr in
                    guard let self = self else { return }
                    let group = DispatchGroup()
                    var successArr: [String] = []
                    var failArr: [YHSelectImageItem] = []

                    YHHUD.show(.progress(message: "上传中..."))
                    for item in imgArr {
                        if let image = item.data {
                            group.enter()
                            uploadImage(image, imageName: item.name) {
                                success, url  in
                                if success {
                                    successArr.append(url)
                                } else {
                                    failArr.append(item)
                                }
                                group.leave()
                            }
                        }
                    }
                    
                    // 等待所有任务完成
                    group.notify(queue: .main) {
                        YHHUD.hide()
                        // 所有任务完成，回到主线程继续执行
                        if imgArr.count == successArr.count {
                            YHHUD.flash(message: "上传成功")
                            for item in successArr {
                                let timestamp = Date().timeIntervalSince1970
                                let dateFormatter = DateFormatter()
                                dateFormatter.dateFormat = "yyyy.MM.dd HH:mm:ss"
                                let currentDate = Date()
                                let formattedDate = dateFormatter.string(from: currentDate)
                                let model = YHWorkExperienceFileModel()
                                model.fileUrl = item
                                model.fileName = "\(UInt64(timestamp))" + ".jpg"
                                model.uploadedAt = formattedDate
                                self.file.append(model)
                            }
                            self.tableView.reloadData()
                        } else {
                            YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
                        }
                        
                    }
                }
                sheetView.show()
            }
            return cell
        }
        if indexPath.row == 3 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterIncomeFileCountTableViewCell.self)
            cell.setContentData(self.file.count)
            return cell
        }
        
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            if self.data.status == 2 {
                return 139
            } else {
                return 106
            }
        }
        if indexPath.row == 1 {
            let count = self.file.count
            if count == 0 {
                return 0
            } else {
                return CGFloat(55 * count + 16)
            }
        }
        if indexPath.row == 2 {
            return 61
        }
        return 45
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
}
