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

import UIKit
import IQKeyboardManagerSwift
import AttributedString

class YHResignUploadDocDetailViewController: YHBaseViewController {
    
    // 进入该页面以下三个参数必传
    // 订单id
    var id: Int = 0
    
    var materialModel: YHMaterialModel = YHMaterialModel() {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    var templateModel: YHResignUploadDetailModel = YHResignUploadDetailModel()
    var templateArr: [YHResignTemplateItemModel] = []
    
    var categoryId: Int = 0
    var supplementId: Int = 0
    
    
    var viewModel: YHResignUploadDetailViewModel = YHResignUploadDetailViewModel()
    
    var items:[YHResignUploadDetailFileListModel] = []
    
    var selectEditItem: YHResignUploadDetailFileListModel?
    lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()

    var renameInputView: YHFileRenameInputView = {
        let view = YHFileRenameInputView.inputView(defalutText: "请输入名称")
        return view
    }()

//    var renameInputView: YHFileRenameInputView = {
//        let view = YHFileRenameInputView.inputView(defalutText: "请输入名称")
//        return view
//    }()
    
    lazy var blackMaskView: UIView = {
        let view = UIView(frame:UIScreen.main.bounds)
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissed))
        view.addGestureRecognizer(tap)
        view.isHidden = true
        return view
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHResignMaterialNameCell.self, forCellReuseIdentifier: YHResignMaterialNameCell.cellReuseIdentifier)
        tableView.register(YHResignUploadDetailFileNameCell.self, forCellReuseIdentifier: YHResignUploadDetailFileNameCell.cellReuseIdentifier)
        tableView.register(cellWithClass: YHAdopterUploadTableViewCell.self)
        tableView.register(cellWithClass: YHAdopterIncomeFileCountTableViewCell.self)
        
        return tableView
    }()
    
    lazy var uploadBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("确认".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickUploadBtn), for: .touchUpInside)
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "资料上传"
        
        addKeyBoardNotify()
        createUI()
        requestMaterialDetail()
        
        renameInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            if let selectEditItem = selectEditItem, var text = text {
                // 重命名
                text = text + "." + selectEditItem.getFileSuffixName()
                selectEditItem.name = text
                tableView.reloadData()
            }
        }
    }
    
    deinit {
        removeNotify()
    }
    
    @objc func didClickUploadBtn() {
        
        
    }
    
    func createUI() {

        view.addSubview(uploadBtn)
        view.addSubview(tableView)
        view.addSubview(blackMaskView)
        view.addSubview(renameInputView)
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-98)
        }
        uploadBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(48.0)
            make.bottom.equalToSuperview().offset(-8-k_Height_safeAreaInsetsBottom())
        }
        renameInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHFileRenameInputView.height)
            make.bottom.equalToSuperview().offset(YHFileRenameInputView.height)
        }
    }
    
    func uploadImage(_ img: UIImage, imageName:String, callBack:((Bool, String)->())?) {
        // 先OSS上传得到URL
        self.viewModel.uploadImage(img) {
            [weak self] url, error 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 = YHResignUploadDetailFileListModel()
                    model.url = successUrl
                    model.name = fileName
                    model.uploadedAt = formattedDate
                    self.items.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 YHResignUploadDocDetailViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return templateArr.count
        }
        if section == 1 {
            return items.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateTemplateCell.cellReuseIdentifier, for: indexPath) as! YHCertificateTemplateCell
            cell.update(bottomMargin: 15)
            if 0 <= indexPath.row && indexPath.row < templateArr.count {
                cell.templateModel = templateArr[indexPath.row]
            }
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: YHResignUploadDetailFileNameCell.cellReuseIdentifier, for: indexPath) as! YHResignUploadDetailFileNameCell
            if 0 <= indexPath.row && indexPath.row < items.count {
                let item = items[indexPath.row]
                cell.updateModel(item)
                cell.editBlock = {
                    
                    [weak self] contentItem in
                    guard let self = self else { return }
                    selectEditItem = contentItem
                    var items = [YHCertificateEditItem(type:.rename, title:"重命名"),
                                 YHCertificateEditItem(type:.preview, title:"预览"),
                                 YHCertificateEditItem(type:.delete, title:"删除"),
                                 YHCertificateEditItem(type:.cancel, title:"取消")]
                    
                    if self.materialModel.status == YHMaterialStatus.completed.rawValue {
                        
                        items = [YHCertificateEditItem(type:.preview, title:"预览"),
                                 YHCertificateEditItem(type:.cancel, title:"取消")]
                    }
                    
                    YHCertificateEditSheetView.sheetView(items:items) {
                        [weak self] editType in
                        guard let self = self else { return }
                        print("editType:\(editType.rawValue)")
                        
                        if editType == .rename { // 重命名
                            IQKeyboardManager.shared.enable = false
                            
                            var name = contentItem.getFileNameWithoutSuffix()
                            if name.count > 30 {
                                name = name[safe: ..<30]!
                            }
                            renameInputView.textField.text = name
                            renameInputView.textField.becomeFirstResponder()
                            
                        } else if editType == .delete { // 删除
                            let msg = "您确定要删除文档\(contentItem.name)吗?"
                            YHTwoOptionAlertView.showAlertView(message:msg) { sure in
                                if !sure { return }
                                // 删除
                                var deleteIndex = -1
                                for (index, item) in self.materialModel.info.enumerated() {
                                    if contentItem.url == item.url {
                                        deleteIndex = index
                                        break
                                    }
                                }
                                
                                if deleteIndex == -1 { // 没有找到对应资料文件
                                    YHHUD.flash(message: "删除成功")
                                    return
                                }
                                self.materialModel.info.remove(at: deleteIndex)
                                self.tableView.reloadData()
                            }
                            
                        } else if editType == .preview { // 预览
                            print(contentItem.url)
                            self.viewModel.getPublicImageUrl(contentItem.url) { success, error in
                                if let success = success {
                                    self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName:contentItem.name)
                                }
                            }
                        }
                    }.show()
                }
            }
            return cell
        }
        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterUploadTableViewCell.self)
            cell.newFileBlock = {[weak self] in
                guard let self = self else { return }
                let count = self.items.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 = YHResignUploadDetailFileListModel()
                                model.url = item
                                model.name = "\(UInt64(timestamp))" + ".jpg"
//                                model.uploadedAt = formattedDate
                                self.items.append(model)
                            }
                            self.tableView.reloadData()
                        } else {
                            YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
                        }
                        
                    }
                }
                sheetView.show()
            }
            return cell
        }
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterIncomeFileCountTableViewCell.self)
            cell.setContentData(self.items.count)
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return 77.0
        }
        if indexPath.section == 2 {
            return 61
        }
        if indexPath.section == 3 {
            return 45
        }
        return 55.0
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 56
        }
        if section == 1 {
            return 96
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0 { // 证件示例模板
            
            let titlelabel = UILabel()
            titlelabel.textColor = UIColor.mainTextColor
            titlelabel.textAlignment = .left
            titlelabel.font = UIFont.PFSC_M(ofSize:17)
            titlelabel.text = "\(self.materialModel.getName())示例模板"
            titlelabel.numberOfLines = 0
            view.addSubview(titlelabel)
            
            titlelabel.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(16)
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
            }
            
            let tipsLabel = UILabel()
            tipsLabel.textColor = UIColor.labelTextColor2
            tipsLabel.textAlignment = .left
            tipsLabel.font = UIFont.PFSC_R(ofSize:14)
            tipsLabel.numberOfLines = 0
//            if !self.templateModel.remark.isEmpty {
//                tipsLabel.text = "注意事项：\(self.templateModel.remark)"
//            }
            view.addSubview(tipsLabel)
            
            tipsLabel.snp.makeConstraints { make in
                make.top.equalTo(titlelabel.snp.bottom).offset(5)
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.bottom.equalToSuperview().offset(-15)
            }
            return view
        }
        if section == 1 {
            // 证件标题和状态
            let titlelabel = UILabel()
            titlelabel.textColor = UIColor.mainTextColor
            titlelabel.textAlignment = .left
            titlelabel.font = UIFont.PFSC_M(ofSize:17)
            titlelabel.text = self.materialModel.getName()
            titlelabel.numberOfLines = 0
            view.addSubview(titlelabel)
            
            let statusLabel = UILabel()
            statusLabel.textAlignment = .center
            statusLabel.font = UIFont.PFSC_M(ofSize:10)
            statusLabel.layer.cornerRadius = kCornerRadius3
            statusLabel.clipsToBounds = true
            view.addSubview(statusLabel)
            
            var text = ""
            var textColor:UIColor = .clear
            var bgColor:UIColor = .clear
            
            
            if self.materialModel.status == YHMaterialStatus.review.rawValue {
                text = "审核中".local
                textColor = UIColor(hexString: "#FF9900")!
                bgColor = UIColor(hexString: "#FF9900", transparency: 0.08)!
                
            } else if self.materialModel.status == YHMaterialStatus.preUpload.rawValue {
                
                text = "待上传".local
                textColor = UIColor(hexString: "#2F7EF6")!
                bgColor = UIColor(hexString: "#2F7EF6", transparency: 0.08)!
                
            } else if self.materialModel.status == YHMaterialStatus.completed.rawValue {
                text =  "已完成".local
                textColor = UIColor(hexString: "#49D2B1")!
                bgColor = UIColor(hexString: "#49D2B1", transparency: 0.08)!
                
            } else if self.materialModel.status == YHMaterialStatus.rejected.rawValue {
                text =  "已驳回".local
                textColor = UIColor.failColor
                bgColor = UIColor(hexString: "#F81D22", transparency: 0.08)!
            }
            statusLabel.text = text
            statusLabel.textColor = textColor
            statusLabel.backgroundColor = bgColor
            
            let tipsLabel = UILabel()
            tipsLabel.textColor = .labelTextColor2
            tipsLabel.font = UIFont.PFSC_R(ofSize:14)
            tipsLabel.textAlignment = .left
            tipsLabel.numberOfLines = 0
            
            tipsLabel.text = "支持的文件格式为jpg/jpeg、png、bmp、doc/docx、xls/xlsx、pdf，最多可上传99张图片或文件"
            view.addSubview(tipsLabel)
            
            titlelabel.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(20)
                make.top.equalToSuperview()
            }
            
            statusLabel.snp.makeConstraints { make in
                make.centerY.equalTo(titlelabel)
                make.left.equalTo(titlelabel.snp.right).offset(4)
                make.right.lessThanOrEqualTo(view).offset(-20)
                make.height.equalTo(16)
                make.width.equalTo(38)
            }
            
            tipsLabel.snp.remakeConstraints { make in
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.top.equalTo(titlelabel.snp.bottom).offset(7)
                make.bottom.equalToSuperview().offset(-15)
            }
            
            if self.materialModel.status != YHMaterialStatus.rejected.rawValue {
                return view
            }
            
            if self.materialModel.audit_remark.isEmpty { // 无驳回理由
                return view
            }
            
            // 有驳回理由
            let rejectView = UIView()
            view.addSubview(rejectView)
            
            let warningImgV = UIImageView(image: UIImage(named: "my_cer_upload_warning"))
            rejectView.addSubview(warningImgV)
            
            let rejectTitleLabel = UILabel()
            rejectTitleLabel.textColor = .failColor
            rejectTitleLabel.font = UIFont.PFSC_R(ofSize:12)
            rejectTitleLabel.textAlignment = .left
            rejectTitleLabel.text = "驳回原因："
            rejectView.addSubview(rejectTitleLabel)
            
            let rejectContentLabel = UILabel()
            rejectContentLabel.textColor = .failColor
            rejectContentLabel.font = UIFont.PFSC_R(ofSize:12)
            rejectContentLabel.numberOfLines = 0
            rejectContentLabel.textAlignment = .left
            rejectContentLabel.text = self.materialModel.audit_remark
            rejectView.addSubview(rejectContentLabel)
            
            tipsLabel.snp.remakeConstraints { make in
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.top.equalTo(titlelabel.snp.bottom).offset(7)
                make.bottom.equalTo(rejectView.snp.top).offset(-20)
            }
            
            rejectView.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.bottom.equalToSuperview().offset(-12)
            }
            
            warningImgV.snp.makeConstraints { make in
                make.width.height.equalTo(14)
                make.left.top.equalTo(0)
            }
            
            rejectTitleLabel.snp.makeConstraints { make in
                make.centerY.equalTo(warningImgV)
                make.left.equalTo(warningImgV.snp.right).offset(4)
            }
            
            rejectContentLabel.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(warningImgV.snp.bottom).offset(7)
                make.bottom.equalToSuperview()
            }
            return view
        }
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01)
        return view
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 20.0
        }
        if section == 1 {
            return 60.0
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 { // 模板列表
            if 0 <= indexPath.row && indexPath.row < templateArr.count {
                let path = templateArr[indexPath.row]
                print(path.fileUrl)
                if !path.fileUrl.isEmpty {
                    self.previewFileTool.openXLSXRemoteFile(urlString:path.fileUrl, fileName:"预览")
                }
            }
             
        } else if indexPath.section == 1 { // 证件列表
            if 0 <= indexPath.row && indexPath.row < items.count {
                let cer = items[indexPath.row]
                if !cer.url.isEmpty {
                    print(cer.url)
                    self.viewModel.getPublicImageUrl(cer.url) { success, error in
                        if let success = success {
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName:cer.name)
                        }
                    }
                }
            }
        }
    }
    
    @objc func dismissed() {
        renameInputView.textField.resignFirstResponder()
    }
}

extension YHResignUploadDocDetailViewController {
    
    func addKeyBoardNotify() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func removeNotify() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if notification.userInfo != nil {
            
            guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {return }

            let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
            self.blackMaskView.isHidden = !isKeyboardShow
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileRenameInputView.height)
            
            if !isKeyboardShow {
                IQKeyboardManager.shared.enable = true
            }
            
            self.renameInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}

extension YHResignUploadDocDetailViewController {
    
    func requestMaterialDetail() {
        viewModel.getUploadDocDetail(id: id) {[weak self] success, err in
            guard let self = self else { return }
            self.tableView.reloadData()
        }
//        YHHUD.show(.progress(message: "加载中..."))
//        viewModel.getMaterialDeal(orderId: orderId, id: batchId, materialId: materialId) {
//            [weak self] success, error  in
//            YHHUD.hide()
//            guard let self = self else { return }
//            
//            self.materialModel = self.viewModel.materialDeal
//            self.items = self.materialModel.info
//            
//            if self.materialModel.status == YHMaterialStatus.completed.rawValue {
//                self.uploadBtn.isHidden = true
//            } else {
//                self.uploadBtn.isHidden = false
//                self.uploadBtn.alpha = (items.count >= 99 ? 0.5 : 1.0)
//            }
//            
//            self.tableView.snp.remakeConstraints { make in
//                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
//                make.left.right.equalToSuperview()
//                if self.materialModel.status == YHMaterialStatus.completed.rawValue {
//                    make.bottom.equalToSuperview()
//                } else {
//                    make.bottom.equalTo(self.uploadBtn.snp.top).offset(-34)
//                }
//            }
//            self.tableView.reloadData()
//            self.requestTemplate()
//            
//            if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
//                YHHUD.flash(message: errorMsg, duration:3)
//            }
//        }
    }
    
}


