//
//  YHPlanShareViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/3/29.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

enum YHPlanShareBgType: Int {
    case link = 1
    case pdf = 2
}

class YHPlanShareBgView: UIView, JXSegmentedListContainerViewListDelegate {
    
    let bgWidth = 293.0
    let bgHeight = 380.0

    var type: YHPlanShareBgType = .link {
        didSet {
            imgV.image = type == .link ? UIImage(named: "plan_share_link_bg") :  UIImage(named: "plan_share_pdf_bg")
            imgV.snp.remakeConstraints { make in
                make.width.equalTo( type == .link ? bgWidth : 217)
                make.height.equalTo(bgHeight)
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
            }
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    lazy var imgV: UIImageView = {
        let imgV = UIImageView()
        imgV.image = UIImage(named: "plan_share_link_bg")
        return imgV
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUI() {
        self.addSubview(imgV)
        imgV.snp.makeConstraints { make in
            make.width.equalTo(bgWidth)
            make.height.equalTo(bgHeight)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
    }
    
    func listView() -> UIView {
        return self
    }
    
}

class YHPlanShareViewController: YHBaseViewController {

    var type: YHPlanShareBgType = .link
    var shareUrl: String = ""
    var pdfCreateUrl: String = ""
    var pdfDownloadUrl: String = ""
    let viewModel = YHPlanViewModel()
    let segmentTitles = ["分享链接", "分享PDF"]
    let bgWidth = 293.0
    let bgHeight = 380.0
    
    lazy var segmentedView: JXSegmentedView = {
       let view = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: KScreenWidth, height: 30))
        view.backgroundColor = .clear
        view.delegate = self

        // 配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorHeight = 2
        indicator.indicatorCornerRadius = 0.0
        indicator.indicatorColor = UIColor.mainTextColor
        view.indicators = [indicator]
        view.dataSource = segmentedDataSource
        view.listContainer = listContainerView
        return view
    }()
    
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = segmentTitles
        dataSource.titleNormalFont = UIFont.PFSC_R(ofSize: 16)
        dataSource.titleNormalColor = UIColor.init(hex: 0x94A3B8)
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 16)
        dataSource.titleSelectedColor = .mainTextColor
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = 64
        dataSource.itemSpacing = 22
        return dataSource
    }()
    
    lazy var listContainerView: JXSegmentedListContainerView! = {
        let view = JXSegmentedListContainerView(dataSource: self, type: .scrollView)
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var bottomShareView: YHPlanShareView = {
        let v = YHPlanShareView(frame: .zero)
        v.type = .link
        v.clickBlock = { [weak self] type, eventType in
            guard let self = self else { return }
            
            if eventType == .cancel {
                self.navigationController?.popViewController(animated: true)
                return
            }
            
            if type == .link {
                if eventType == .wechat {
                    let iconImg = UIImage(named: "plan_share_icon") ?? UIImage()
                    YHShareManager.shared.sendLinkContent("香港续签至永居方案分析", "具体方案您可以联系专属顾问和生活管家深入咨询", iconImg, link: shareUrl)
                    
                } else if eventType == .copyLink {
                    let pasteBoard = UIPasteboard.general
                    pasteBoard.string = shareUrl
                    YHHUD.flash(message: "复制成功")
                }
                
            } else if type == .pdf {
                
                if let sourceUrl = URL(string: pdfDownloadUrl) {
                    let fileName = getPDFFileName()
                    let destinationURL = self.planDocumentFileUrl.appendingPathComponent(fileName)
                    if eventType == .wechat {
                        if FileManager.default.fileExists(atPath: destinationURL.path) {
                            let fileName = destinationURL.lastPathComponent
                            let fileExtension = destinationURL.pathExtension
                            YHShareManager.shared.shareFileToWeChat(fileUrl: destinationURL, filename: fileName, ext: fileExtension)
                            return
                        }
                        YHHUD.flash(message: "请先点击保存PDF")
                        
                    } else if eventType == .saveImg {
                        
//                        if FileManager.default.fileExists(atPath: destinationURL.path) {
//                            YHHUD.flash(message: "已下载PDF")
//                            return
//                        }
//                        
                        if pdfDownloadUrl.isEmpty {
                            requestPDF(isShowLoading: true)

                        } else {
                            downloadPDF(pdfDownloadUrl, isShowLoading: true)
                        }
                    }
                }
            }
        }
        return v
    }()
    
    lazy var shareLinkBgView: YHPlanShareBgView = {
        let v = YHPlanShareBgView()
        v.type = .link
        return v
    }()
    
    lazy var sharePdfBgView: YHPlanShareBgView = {
        let v = YHPlanShareBgView()
        v.type = .pdf
        return v
    }()
    
    lazy var planDocumentFileUrl: URL = {
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
//        let planDirectoryURL = documentsURL.appendingPathComponent("plan")
        return documentsURL
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.backgroundColor = .clear
        view.backgroundColor = .init(hex: 0xF5F6F8)
        view.addSubview(segmentedView)
        view.addSubview(listContainerView)
        view.addSubview(bottomShareView)
        
        segmentedView.snp.makeConstraints { make in
            make.top.equalTo(8+k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(34)
            make.width.equalTo(64.0*2.0 + 24.0 + 22*2)
            make.centerX.equalToSuperview()
        }
        
        listContainerView.snp.makeConstraints { make in
            make.top.equalTo(segmentedView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.width.equalTo(bgWidth)
            make.height.equalTo(bgHeight)
        }
        
        bottomShareView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(216)
        }
        
        if pdfDownloadUrl.isEmpty {
            requestPDF(isShowLoading: false)

        } else {
            downloadPDF(pdfDownloadUrl, isShowLoading: false)
        }
    }
    
    func requestPDF(isShowLoading: Bool) {
        
        if isShowLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        self.viewModel.requetPDFUrl(self.pdfCreateUrl) { [weak self] url in
            YHHUD.hide()
            guard let self = self else { return }
            self.pdfDownloadUrl = url
            self.downloadPDF(url, isShowLoading: isShowLoading)
        }
    }
    
    func downloadPDF(_ urlString: String, isShowLoading: Bool) {
        
        guard let url = URL(string: urlString) else {
            YHHUD.flash(message: "下载PDF失败")
            return
        }
        
        if isShowLoading {
            YHHUD.show(.progress(message: "下载中..."))
        }
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        let task = session.downloadTask(with: url) { [weak self] (locationUrl, response, error) in
            DispatchQueue.main.async {
                YHHUD.hide()
                guard let self = self else { return }
                guard let locationUrl = locationUrl, error == nil else {
                    print("下载失败: \(error?.localizedDescription ?? "未知错误")")
                    YHHUD.flash(message: "下载PDF失败")
                    return
                }
                if let res = response {
                    printLog(res.suggestedFilename)
                }
                self.savePDF(sourceUrl: url, locationUrl: locationUrl, isShowLoading: isShowLoading)
            }
        }
        task.resume()
    }
    
    func getPDFFileName() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd" // HH:mm:ss
        let dateString = dateFormatter.string(from: Date())
        return "香港续签至永居方案" + dateString + ".pdf"
    }
    
    func savePDF(sourceUrl: URL, locationUrl: URL, isShowLoading: Bool) {
        
        let fileManager = FileManager.default
        
        // 保存文件到 plan 目录
        let fileName = getPDFFileName()
        let destinationURL = self.planDocumentFileUrl.appendingPathComponent(fileName)
        do {
            // 如果文件已存在，先移除
            if fileManager.fileExists(atPath: destinationURL.path) {
                try fileManager.removeItem(at: destinationURL)
            }
            try fileManager.moveItem(at: locationUrl, to: destinationURL)
            print("文件已保存到: \(destinationURL.path)")
            print("文件源地址: \(locationUrl.path)")
            if isShowLoading {
                YHHUD.flash(message: "下载PDF成功")
            }

        } catch {
            print("保存文件失败: \(error.localizedDescription)")
            if isShowLoading {
                YHHUD.flash(message: "下载PDF失败")
            }
        }
    }
}

extension YHPlanShareViewController: JXSegmentedViewDelegate {
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        
        if index == 1 {
            self.type = .pdf
        } else {
            self.type = .link
        }
        bottomShareView.type = self.type
    }
}

extension YHPlanShareViewController: JXSegmentedListContainerViewDataSource {
    
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentTitles.count
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
       
        if index ==  0 {
            return shareLinkBgView
        }
        return sharePdfBgView
    }
}
