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

import UIKit
import IQKeyboardManagerSwift

class YHResignCertificateDetailEVisaViewController: YHBaseViewController {
    
    var tableView: UITableView!
    var nextButton: UIButton!
    var clickIndex = -1
    var file: [YHWorkExperienceFileModel] = []
    var data: YHResignCertificateModel = YHResignCertificateModel()
        
    var viewModel: YHResignCertificateDetailViewModel = YHResignCertificateDetailViewModel()
    var isDisablEdit: Bool = false
    var orderId: Int = 0

    lazy var previewFileTool: YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "上传电子签证"
        gk_navBarAlpha = 1
        gk_navBackgroundColor = .white
        setView()
        getData()
    }
    
    func getData() {
        isDisablEdit = data.status == ResignCertificateStatus.Complete.rawValue

        if data.cert_info.e_visa_url.count != 0 {
            let model = YHWorkExperienceFileModel()
            model.fileName = data.cert_info.name
            model.fileUrl = data.cert_info.e_visa_url
            model.uploadedAt = data.cert_info.upload_at
            file = [model]
        }
        tableView.reloadData()
        nextButton.snp.remakeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-8 - k_Height_safeAreaInsetsBottom())
            make.height.equalTo(isDisablEdit ? 0 : 48)
        }
    }
    
    func setView() {
        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: YHResignCertificateEvisaTableViewCell.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)
        }

    }
    
    @objc func nextStep() {
        if file.count != 0 {
            let eVisa: [String: Any] = ["name": file.first?.fileName ?? "",
                                        "e_visa_url": file.first?.fileUrl ?? "",
                                        "upload_at": file.first?.uploadedAt ?? "",
                                        "submit": true]
            let params: [String: Any] = [
                "eVisa": eVisa,
                "id": data.id
            ]
            viewModel.submitResignCertificateUpdate(params) { success, error in
                if success {
                    YHHUD.flash(message: "保存成功")
                    self.navigationController?.popViewController()
                    
                } else {
                    let msg = error?.errorMsg ?? "保存失败,请重试"
                    YHHUD.flash(message: msg)
                }
            }
        } 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 = [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 YHResignCertificateDetailEVisaViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHResignCertificateEvisaTableViewCell.self)
            let str = "* " + data.name + "的电子签证"
            let attributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.PFSC_M(ofSize: 17),
                .foregroundColor: UIColor.mainTextColor
            ]
            let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
            let starRange = NSRange(location: 0, length: 2)
            questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
            cell.titleLabel.attributedText = questionAttrStr
            cell.dataModel = self.data
            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 {
                    let items = [YHCertificateEditItem(type: .preview, title: "预览"),
                                 YHCertificateEditItem(type: .rename, title: "重命名"),
                                 YHCertificateEditItem(type: .delete, 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 { // 删除
                            file = []
                            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()
                }
            }
            cell.newFileBlock = {[weak self] in
                guard let self = self else { return }
                let sheetView = YHCertificateUploadSheetView.sheetView()
                sheetView.tips = ""
                sheetView.maxSelectImageCount = 1
                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
        }
        
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
}
