//
//  EmailListDetailController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/9.
//

import UIKit
import WebKit


class EmailListDetailController: BaseViewController {

    private let scrollView = UIScrollView()
    private let contentStack = UIStackView()
    private let textView = UITextView()
    private let webView = WKWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    var detail:EmailMessageModel?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setdetail()
        setRead()
    }
    
    private func setRead() -> Void {
        if detail?.labelids?.contains("UNREAD") ?? false {
            let msgid = detail?.messageId ?? ""
            PMEmailManager.shareManager.markMessageAsRead(messageId: msgid) {[weak self] success, error in
                guard let self = self else { return }
                if success {
                    var all = PMEmailManager.shareManager.messageFilter
                    for (i,var child) in all.enumerated() {
                        if var data:[EmailMessageModel] = child.child as? [EmailMessageModel] {
                            for (j,var d) in data.enumerated() {
                                if d.messageId == msgid {
                                    var labels:NSMutableSet = NSMutableSet(array: d.labelids ?? [])
                                    labels.remove("UNREAD")
                                    d.labelids = labels.allObjects as? [String] ?? []
                                    data[j] = d
                                    child.child = data
                                    all[i] = child
                                    break
                                }
                            }
                        }
                    }
                    PMEmailManager.shareManager.messageFilter = all
                    PMEmailManager.shareManager.allMessage = all
                }
            }
        }
    }
    
    private func setdetail() -> Void {
        let send = detail?.payload?.headers?.from ?? " "
        LT.text = (send.count > 0 ? send.substring(to: send.index(send.startIndex, offsetBy: 1)) : "")
        SendL.text = send.components(separatedBy: " ").first
        ToEmail.text = "To:\(detail?.payload?.headers?.to ?? "")"
        dateL.text = detail?.payload?.headers?.date?.EmailDateFromat().string("dd MMM")
        titleL.text = detail?.payload?.headers?.subject
        loadMessageData()
    }
    
    private func loadMessageData() {
        // 解析正文
        let (plainText, html) = (detail?.payload?.body.plainText,detail?.payload?.body.html)
        if let html = html {
            webView.isHidden = false
            textView.isHidden = true
            webView.loadHTMLString(html, baseURL: nil)
        } else  if let plainText = plainText {
            webView.isHidden = true
            textView.isHidden = false
            textView.text = plainText
            textView.sizeToFit()
            self.view.layoutIfNeeded()
            DispatchQueue.main.async {
                self.textView.snp.makeConstraints { make in
                    make.height.equalTo(self.textView.contentSize.height)
                }
                self.scrollView.contentSize = CGSizeMake(0, self.textView.contentSize.height + 10)
            }
        }
    }
    
    private func setup() -> Void {
        line.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(titleView.snp.bottom).offset(20)
            make.height.equalTo(1)
        }
        LT.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(15)
            make.top.equalTo(line.snp.bottom).offset(15)
            make.size.equalTo(CGSizeMake(40, 40))
        }
        SendL.snp.makeConstraints { make in
            make.left.equalTo(LT.snp.right).offset(4)
            make.right.equalTo(dateL.snp.left).inset(-5)
            make.bottom.equalTo(LT.snp.centerY).offset(-2)
        }
        ToEmail.snp.makeConstraints { make in
            make.left.equalTo(LT.snp.right).offset(4)
            make.right.equalTo(dateL.snp.left).inset(-5)
            make.top.equalTo(LT.snp.centerY).offset(2)
        }
        dateL.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(marginLR)
            make.centerY.equalTo(LT.snp.centerY).offset(2)
            make.width.equalTo(55)
        }
        line1.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(LT.snp.bottom).offset(15)
            make.height.equalTo(1)
        }
        titleL.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(marginLR)
            make.top.equalTo(line1.snp.bottom).offset(20)
        }
        view.addSubview(scrollView)
        scrollView.contentInsetAdjustmentBehavior = .never
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15))
            make.top.equalTo(titleL.snp.bottom).offset(15)
        }
        contentStack.axis = .vertical
        contentStack.spacing = 16
        contentStack.alignment = .fill
        scrollView.addSubview(contentStack)
        contentStack.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.equalTo(scrollView.snp.leading)
            make.width.equalTo(scrollView.snp.width)
        }
        
        textView.isEditable = false
        textView.font = .systemFont(ofSize: 14)
        textView.textColor = UIColor.colorWithHex(hexStr: "#666666")
        textView.isScrollEnabled = false
        textView.textContainerInset = .zero
        
        // WebView配置
        webView.isHidden = true
        webView.navigationDelegate = self
        let script = """
        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
        document.getElementsByTagName('head')[0].appendChild(meta);
        """
        webView.evaluateJavaScript(script)
        contentStack.addArrangedSubview(textView)
        contentStack.addArrangedSubview(webView)
    }
    
    
    private lazy var LT: UILabel = {
        let l = UILabel()
        l.Radius = 20
        l.text = "G"
        l.font = UIFont.systemFont(ofSize: 20, weight: .heavy)
        l.textAlignment = .center
        l.textColor = .white
        l.backgroundColor = UIColor.colorWithHex(hexStr: "#0082FF")
        view.addSubview(l)
        return l
    }()
    
    private lazy var SendL: UILabel = {
        let l = UILabel()
        l.text = ""
        l.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        l.textColor = UIColor.colorWithHex(hexStr: "#333333")
        view.addSubview(l)
        return l
    }()
    
    private lazy var ToEmail: UILabel = {
        let l = UILabel()
        l.text = ""
        l.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        l.textColor = UIColor.colorWithHex(hexStr: "#666666")
        view.addSubview(l)
        return l
    }()
    
    private lazy var dateL: UILabel = {
        let l = UILabel()
        l.text = ""
        l.textAlignment = .right
        l.font = UIFont.systemFont(ofSize: 12, weight: .regular)
        l.textColor = UIColor.colorWithHex(hexStr: "#B3B3B3")
        view.addSubview(l)
        return l
    }()
    
    private lazy var titleL: UILabel = {
        let l = UILabel()
        l.text = ""
        l.numberOfLines = 2
        l.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        l.textColor = UIColor.colorWithHex(hexStr: "#333333")
        view.addSubview(l)
        return l
    }()
    
    private lazy var line: UIView = {
        let l = UIView()
        l.backgroundColor = UIColor.colorWithHex(hexStr: "#EBEFF5")
        view.addSubview(l)
        return l
    }()
    
    private lazy var line1: UIView = {
        let l = UIView()
        l.backgroundColor = UIColor.colorWithHex(hexStr: "#EBEFF5")
        view.addSubview(l)
        return l
    }()

}


extension EmailListDetailController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.02) {
            Print(webView.scrollView.contentSize)
            webView.snp.makeConstraints { make in
                make.height.equalTo(webView.scrollView.contentSize.height+10)
            }
            self.scrollView.contentSize = CGSizeMake(0, webView.scrollView.contentSize.height + 10)
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // 禁止外部链接跳转
        if navigationAction.navigationType == .linkActivated {
            Print(navigationAction.request.url?.absoluteString)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
    
}
