//
//  OrderCasePoolHtmlCell.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/5.
//

import UIKit

class OrderCasePoolHtmlCell: UITableViewCell, UITextViewDelegate {

    @IBOutlet weak var contentTextView: UITextView!
    @IBOutlet weak var textViewH: NSLayoutConstraint!
    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentTextView.delegate = self
        self.contentTextView.isEditable = false
        self.contentTextView.allowsEditingTextAttributes = false
        self.contentTextView.isScrollEnabled = false
        self.contentTextView.dataDetectorTypes = .link
        if #available(iOS 11.0, *) {
            self.contentTextView.textDragInteraction?.isEnabled = false
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func loadData(_ string:String) {
        DispatchQueue.global().async {
            let attrStr = self.setContent(string)
            let resultStr = NSMutableAttributedString(attributedString: attrStr)
            let style = NSMutableParagraphStyle()
            style.lineSpacing = 6
            let attributes = [NSAttributedString.Key.paragraphStyle : style]
            resultStr.addAttributes(attributes, range: NSRange(location: 0, length: resultStr.length))
            let rect = resultStr.boundingRect(with: CGSize(width: CD.screenW - 32, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
            DispatchQueue.main.async {
                self.textViewH.constant = rect.size.height
                self.contentTextView.attributedText = resultStr
                self.contentTextView.linkTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.blue]
            }
        }
        
        DispatchQueue.global().async {
            let str = NSMutableAttributedString(attributedString: NSAttributedString(string: string))
            self.getImageurlFromHtml(webString: str)
        }
    }
    
    func setContent(_ str:String) -> NSAttributedString {
        let htmlString = "<html><head><style>img{width:\(CD.screenW-32) !important;height:auto}</style></head>\(str)</html>"
        let resultString = htmlString.replacingOccurrences(of: "<BR>", with: "")
        var attrStr: NSAttributedString? = nil
        do {
            if let data = resultString.data(using: .unicode) {
                attrStr = try NSAttributedString(data: data, options: [
                    .documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue
                ], documentAttributes: nil)
            }
        } catch {
        }
        return attrStr!
    }
    
    
    @available(iOS 10.0, *)
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
//        let webVc = TSHybridViewController(url: URL)
//        CD.visibleVC?.navigationController?.pushViewController(webVc, animated: true)
        return false
    }
    
    func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
        var arr:[(String,UIImage?)] = []
//        for item in imageurlArray {
//            arr.append((item.fileUrl, item.img))
//        }
        if !arr.isEmpty {
            showImages(arr, idx: characterRange.location)
        }
        return false
    }
    
    func getImageurlFromHtml(webString: NSMutableAttributedString) {
        if webString.length == 0 {
            return
        }
        let webStr = String(format: "%@", webString)
//        self.imageurlArray = []
        
        let parten = "<img(.*?)>"
        var reg: NSRegularExpression? = nil
        do {
            reg = try NSRegularExpression(pattern: parten, options: [])
        } catch {
        }
        
        if let match = reg?.matches(in: webStr, options: [], range: NSRange(location: 0, length: webString.length - 1)) {
            for result in match {
                let nsWebStr = NSString(format: "%@", webStr)
                let subString = nsWebStr.substring(with: result.range)
                var subReg:NSRegularExpression?
                do{
                    subReg = try NSRegularExpression(pattern: "http://(.*?)\"", options: [])
                } catch{
                }
                if let subMatch = subReg?.matches(in: subString, options: [], range: NSRange(location: 0, length: subString.count - 1)) {
                    if subMatch.count > 0 {
                        let subRes = subMatch.first
                        if var subRange = subRes?.range {
                            subRange.length = subRange.length - 1
//                            let nsSubString = NSString(format:"%@", subString)
//                            let imagekUrl = nsSubString.substring(with: subRange)
//                            let photo = SitePhotos()
//                            photo.fileUrl = imagekUrl
//                            self.imageurlArray.append(photo)
                        }
                    }else{
                        var subReg2:NSRegularExpression?
                        do{
                            subReg2 = try NSRegularExpression(pattern: "https://(.*?)\"", options: [])
                        } catch{
                        }
                        
                        if let subMatch2 = subReg2?.matches(in: subString, options: [], range: NSRange(location: 0, length: subString.count - 1)) {
                            if subMatch2.count > 0 {
                                let subRes = subMatch2.first
                                if var subRange = subRes?.range {
                                    subRange.length = subRange.length - 1
//                                    let nsSubString = NSString(format:"%@", subString)
//                                    let imagekUrl = nsSubString.substring(with: subRange)
//                                    let photo = SitePhotos()
//                                    photo.fileUrl = imagekUrl
//                                    self.imageurlArray.append(photo)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    func showImages(_ imgArr:[(String,UIImage?)], idx:Int = 0) {
        var photos:[GKPhoto] = []
        for item in imgArr {
            let  photo = GKPhoto()
            if !item.0.isEmpty {
                photo.url = URL(string: item.0)!
            }
            if item.1 != nil {
                photo.image = item.1
            }
            photos.append(photo)
        }
        let browser = GKPhotoBrowser(photos: photos, currentIndex: idx)
        browser.showStyle = .none
        browser.modalPresentationStyle = .overFullScreen
        browser.show(fromVC: CD.visibleVC!)
    }
}
extension OrderCasePoolHtmlCell: TCCell_RowCellUpdateProtocol {
    typealias DataSource = String
    typealias ConfigModel = (String, Int)
    
    func row_update(dataSource data: DataSource) {
        self.loadData(data)
    }
    
    func row_update(config data: ConfigModel) {
        
    }
    
    func row_update(callBack block: TCRowCallBack?) {
//        callback = block
    }
}
