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

import UIKit
import Photos
import VisualEffectView

class YHPlanPolicyImageInfo {
    var model: YHPlanCaseModel = YHPlanCaseModel()
    var imgView: UIImageView = UIImageView()
    let height: CGFloat = 520.0
    var width: CGFloat = 520.0
}

class YHPlanPolicyDetailViewController: YHBaseViewController {
   
    var firstAppear: Bool = true
    var arr: [YHPlanCaseModel] = [] {
        didSet {
            imgs.removeAll()
            for item in arr {
                let model = YHPlanPolicyImageInfo()
                model.model = item
                imgs.append(model)
            }
            self.collectionView.reloadData()
        }
    }
    
    var currentIndex: Int = 0
    
    var imgs: [YHPlanPolicyImageInfo] = []
    
    lazy var bgImgView: UIImageView =  {
        let v = UIImageView()
        v.clipsToBounds = true
        return v
    }()
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0.0
        layout.minimumLineSpacing = 0.0
        layout.scrollDirection = .horizontal
    
        let collectView = UICollectionView(frame: CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar+24.0, width: KScreenWidth, height: 520), collectionViewLayout: layout)
        collectView.backgroundColor = .clear
        collectView.delegate = self
        collectView.dataSource = self
        collectView.register(YHPlanShareImageCell.self, forCellWithReuseIdentifier: YHPlanShareImageCell.cellReuseIdentifier)
        collectView.isPagingEnabled = true
        collectView.showsHorizontalScrollIndicator = false
        return collectView
    }()
    
    lazy var blurView: VisualEffectView = {
        let blurView = VisualEffectView()
        blurView.colorTint = UIColor(hex: 0xAFAFAF).withAlphaComponent(0.15)
        blurView.blurRadius = 16
        blurView.scale = 1
        return blurView
    }()
    
    lazy var shareBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .white
        btn.setTitle("分享", for: .normal)
        btn.setTitleColor(.mainTextColor, for: .normal)
        btn.titleLabel?.font = .PFSC_M(ofSize: 16)
        btn.layer.cornerRadius = 3.0
        btn.addTarget(self, action: #selector(didShareBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    @objc func didShareBtnClicked() {
        let view = YHPlanLinkShareView.alertView()
        view.clickBlock = { [weak self] type in
            guard let self = self else { return }
            
            if 0 <= currentIndex, currentIndex < arr.count {
                let model = arr[currentIndex]
                if type == .wechat {
                    sendImageToWechat(model.image_poster)
                    
                } else if type == .copyLink {
                    let pasteBoard = UIPasteboard.general
                    pasteBoard.string = model.image_poster
                    YHHUD.flash(message: "复制成功")
                    
                } else if type == .saveImg {
                    saveImgFromUrl(model.image_poster)
                }
            }
        }
        view.show()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        gk_backImage = UIImage(named: "nav_back_white")
        gk_navTitle = "\(currentIndex+1)/\(arr.count)"
        gk_navTitleColor = .white
        view.backgroundColor = .init(hex: 0x000000, alpha: 1.0)
        view.addSubview(bgImgView)
        view.addSubview(blurView)
        view.addSubview(collectionView)
        view.addSubview(shareBtn)
        
        bgImgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        blurView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar+24.0)
            make.height.equalTo(520)
        }
        
        shareBtn.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(46)
            make.top.equalTo(collectionView.snp.bottom).offset(32)
        }
        
        loadImgs()
        showBgImage(index: currentIndex)
    }
    
    func showBgImage(index: Int) {
        if 0 <= index, index < arr.count {
            let model = arr[index]
            if let url = URL(string: model.image_poster) {
                bgImgView.kf.setImage(with: url)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if firstAppear {
            collectionView.scrollToItem(at: IndexPath(row: currentIndex, section: 0), at: .top, animated: false)
            firstAppear = false
        }
    }
    
    func loadImgs() {
        let ossGroup = DispatchGroup()
        for item in imgs {
            ossGroup.enter()
            item.imgView.kf.setImage(with: URL(string: item.model.image_poster)) { result in
                switch result {
                case let .success(value):
                    let size = value.image.size
                    let scale = size.height > 0 ? Double(size.width / size.height) : 1.0
                    if scale > 0 {
                        item.width = scale * item.height
                        printLog("IMG_SIZE: \(item.width), \(item.height)")
                    }
                case let .failure(error):
                    print("Job failed: \(error.localizedDescription)")
                }
                ossGroup.leave()
            }
        }
        ossGroup.notify(queue: .main) {
            self.collectionView.reloadData()
        }
    }
}

extension YHPlanPolicyDetailViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    // 返回单元格数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imgs.count
    }
    
    // 返回每个单元格的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return CGSize(width: KScreenWidth, height: 520)
    }
    
    // 返回自定义单元格
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHPlanShareImageCell.cellReuseIdentifier, for: indexPath) as? YHPlanShareImageCell else {
            return UICollectionViewCell()
        }
        if 0 <= indexPath.item && indexPath.item < imgs.count {
            let model = imgs[indexPath.item]
            cell.model = model
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if 0 <= indexPath.item && indexPath.item < imgs.count {
            let model = imgs[indexPath.item]
            YHPictureReviewManager.shared.showNetWorkPicturs(curIndex: 0, arrPicturs: [model.model.image_poster])

        }
    }
}

extension YHPlanPolicyDetailViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        currentIndex = Int(scrollView.contentOffset.x/KScreenWidth)
        gk_navTitle = "\(currentIndex+1)/\(arr.count)"
        showBgImage(index: currentIndex)

    }
}

extension YHPlanPolicyDetailViewController {
    
    func saveImgFromUrl(_ urlString: String) {
        
        guard let url = URL(string: urlString) else {
            YHHUD.flash(message: "保存失败")
            return
        }
        
        YHHUD.show(.progress(message: "下载中..."))
        let task = URLSession.shared.dataTask(with: url) { data, _, error in
            DispatchQueue.main.async {
                YHHUD.hide()
                guard let data = data, error == nil else { return YHHUD.flash(message: "保存成功") }
                let image = UIImage(data: data)
                if let image = image {
                    // 保存图片到图库
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }, completionHandler: { success, error in
                        if success {
                            // 图片保存成功
                            DispatchQueue.main.async {
                                YHHUD.flash(message: "保存成功")
                            }
                        } else if let error = error {
                            // 保存失败
                            DispatchQueue.main.async {
                                YHHUD.flash(message: "保存失败")
                            }
                            print("保存图片出错: \(error.localizedDescription)")
                        }
                    })
                }
            }
        }
        task.resume()
    }
    
    func sendImageToWechat(_ urlString: String) {
        
        guard let url = URL(string: urlString) else {
            return
        }
        let task = URLSession.shared.dataTask(with: url) { data, _, error in
            DispatchQueue.main.async {
                guard let data = data, error == nil else { return }
                let image = UIImage(data: data)
                if let image = image {
                    YHShareManager.shared.sendImageContent(image)
                }
            }
        }
        task.resume()
    }
}
