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

import UIKit
import CoreImage
import Vision
import Photos

class YHInvatationShareViewController: YHBaseViewController {
    var stepView: YHShareStepView!
    var bottomView: UIView!
    var leftButton: YHShareButton!
    var centerButton: YHShareButton!
    var rightButton: YHShareButton!
    
    lazy var myCollectView = {
        // 设置布局方向
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: KScreenWidth, height: KScreenHeight - k_Height_NavigationtBarAndStatuBar - 148)
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = .horizontal
        
        let collectinoView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectinoView.backgroundColor = .white
        collectinoView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        collectinoView.register(YHShareOneCollectionViewCell.self, forCellWithReuseIdentifier:YHShareOneCollectionViewCell.cellReuseIdentifier)
        collectinoView.register(YHShareTwoCollectionViewCell.self, forCellWithReuseIdentifier:YHShareTwoCollectionViewCell.cellReuseIdentifier)
        collectinoView.delegate = self
        collectinoView.dataSource = self
        collectinoView.translatesAutoresizingMaskIntoConstraints = false
        collectinoView.alwaysBounceVertical = true
        collectinoView.bounces = false
        collectinoView.isPagingEnabled = true
        collectinoView.showsHorizontalScrollIndicator = false
        collectinoView.showsVerticalScrollIndicator = false
        return collectinoView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        loadData()
    }
}

extension YHInvatationShareViewController {
    func getData() {
        
    }
    
    func updateDataSource() {
        
    }
    
    func setView() {
        view.backgroundColor = .contentBkgColor
        gk_navTitle = "分享活动"
        view.addSubview(myCollectView)
        myCollectView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(-148)
        }
        
        bottomView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(148)
        }
        
        leftButton = {
            let button = YHShareButton()
            button.setContent("invitation_with_gifts_share_left", "保存海报")
            button.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
            return button
        }()
        bottomView.addSubview(leftButton)
        leftButton.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.left.equalTo(42)
            make.height.equalTo(74)
            make.width.equalTo(52)
        }
        
        centerButton = {
            let button = YHShareButton()
            button.setContent("invitation_with_gifts_share_center", "微信好友")
            button.addTarget(self, action: #selector(wxClick), for: .touchUpInside)
            return button
        }()
        bottomView.addSubview(centerButton)
        centerButton.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.centerX.equalToSuperview()
            make.height.equalTo(74)
            make.width.equalTo(52)
        }
        
        rightButton = {
            let button = YHShareButton()
            button.setContent("invitation_with_gifts_share_right", "朋友圈")
            button.addTarget(self, action: #selector(peopleClick), for: .touchUpInside)
            return button
        }()
        bottomView.addSubview(rightButton)
        rightButton.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.right.equalTo(-42)
            make.height.equalTo(74)
            make.width.equalTo(52)
        }
        
        stepView = {
            let view = YHShareStepView()
            return view
        }()
        view.addSubview(stepView)
        stepView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top).offset(-41.5)
            make.height.equalTo(1.5)
            make.width.equalTo(35)
        }
    }
    
    func loadData() {

    }
    
    @objc func saveBtnClick() {
        let currentPage = self.currentPage(collectionView: myCollectView)
        if currentPage == 0 {
            let cell = myCollectView.cellForItem(at: IndexPath(row: currentPage, section: 0)) as! YHShareOneCollectionViewCell
            guard let combinedImage = combinedImageFrom(imageView: cell.centerImageView) else { return }
            saveImageToPhotosAlbum(image: combinedImage)
        } else {
            let cell = myCollectView.cellForItem(at: IndexPath(row: currentPage, section: 0)) as! YHShareTwoCollectionViewCell
            guard let combinedImage = combinedImageFrom(imageView: cell.centerImageView) else { return }
            saveImageToPhotosAlbum(image: combinedImage)
        }
    }
    
    func saveImageToPhotosAlbum(image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                DispatchQueue.main.async {
                    YHHUD.flash(message: "保存成功")
                }
            } else {
                YHHUD.flash(message: "保存失败，请检查系统权限")
            }
        }
    }
    
    @objc func wxClick() {
//        guard let combinedImage = combinedImageFrom(imageView: centerImageView) else { return }
        YHShareManager.shared.sendLinkContent("香港身份规划专属礼包，限时领取!", "1000元折扣福利券，资深银河规划专家1V1评估方案", UIImage(named: "invitation_with_gifts_share_other") ?? UIImage(), link: YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=lkhtj-app&customer_id=\(YHLoginManager.shared.userModel?.id ?? "")&scene_id=30")
//        YHShareManager.shared.sendImageContent(combinedImage)
    }
    
    @objc func peopleClick() {
//        guard let combinedImage = combinedImageFrom(imageView: centerImageView) else { return }
//        YHShareManager.shared.sendImageContent(combinedImage, WXSceneTimeline)
        YHShareManager.shared.sendLinkContent("香港身份规划专属礼包，限时领取!", "1000元折扣福利券，资深银河规划专家1V1评估方案", UIImage(named: "invitation_with_gifts_share_other") ?? UIImage(), link: YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=lkhtj-app&customer_id=\(YHLoginManager.shared.userModel?.id ?? "")&scene_id=30", WXSceneTimeline)

    }
    
    func generateQRCode(from string: String) -> UIImage? {
        guard let data = string.data(using: .ascii, allowLossyConversion: false) else {
            return nil
        }

        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setValue(data, forKey: "inputMessage")

        guard let outputImage = filter?.outputImage else {
            return nil
        }

        let context = CIContext()
        if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
            return UIImage(cgImage: cgImage)
        }

        return nil
    }
    
    func combinedImageFrom(imageView: UIImageView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 0.0)
        // 首先绘制 imageView 的内容
        imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
        // 获取合成后的图像
        let combinedImage = UIGraphicsGetImageFromCurrentImageContext()

        // 结束绘图上下文
        UIGraphicsEndImageContext()

        return combinedImage
    }
    
    func currentPage(collectionView: UICollectionView) -> Int {
        let pageWidth = collectionView.frame.width
        let offset = collectionView.contentOffset
        return Int(offset.x / pageWidth)
    }
}

extension YHInvatationShareViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.row == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHShareOneCollectionViewCell.cellReuseIdentifier, for: indexPath) as! YHShareOneCollectionViewCell
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHShareTwoCollectionViewCell.cellReuseIdentifier, for: indexPath) as! YHShareTwoCollectionViewCell
            return cell
        }
        
    }
}

extension YHInvatationShareViewController: UIScrollViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let currentPage = self.currentPage(collectionView: myCollectView)
        if currentPage == 0 {
            stepView.stepOneView.backgroundColor = UIColor(hex: 0x94a3b8)
            stepView.stepTwoView.backgroundColor = UIColor(hex: 0x94a3b8).withAlphaComponent(0.3)
        } else {
            stepView.stepOneView.backgroundColor = UIColor(hex: 0x94a3b8).withAlphaComponent(0.3)
            stepView.stepTwoView.backgroundColor = UIColor(hex: 0x94a3b8)
        }
    }
}

class YHShareOneCollectionViewCell: UICollectionViewCell {
    static let cellReuseIdentifier = "YHShareOneCollectionViewCell"
    var centerImageView: UIImageView!
    var imageView: UIImageView!
    var logoImageView: UIImageView!
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        self.backgroundColor = UIColor(hex: 0xededed)
        centerImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_share_detail")
            return view
        }()
        contentView.addSubview(centerImageView)
        centerImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(480)
            make.width.equalTo(270)
        }
        
        imageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_share_detail")
            return view
        }()
        centerImageView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.bottom.equalTo(-57)
            make.right.equalTo(-27)
            make.width.height.equalTo(56)
        }
        
        logoImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "share_icon")
            return view
        }()
        imageView.addSubview(logoImageView)
        logoImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(17)
        }
        let qrString = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=lkhtj-app&customer_id=\(YHLoginManager.shared.userModel?.id ?? "")&scene_id=30"
        if let qrCode = qrString.generateQRCode() {
            // 可以将qrCode设置为UIImageView的image属性来显示二维码
            imageView.image = qrCode
        }
    }
    
//    func generateQRCode(from string: String) -> UIImage? {
//        guard let data = string.data(using: .ascii, allowLossyConversion: false) else {
//            return nil
//        }
//
//        let filter = CIFilter(name: "CIQRCodeGenerator")
//        filter?.setValue(data, forKey: "inputMessage")
//
//        guard let outputImage = filter?.outputImage else {
//            return nil
//        }
//
//        let context = CIContext()
//        if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
//            return UIImage(cgImage: cgImage)
//        }
//
//        return nil
//    }
}

class YHShareTwoCollectionViewCell: UICollectionViewCell {
    static let cellReuseIdentifier = "YHShareTwoCollectionViewCell"
    var centerImageView: UIImageView!
    var imageView: UIImageView!
    var logoImageView: UIImageView!
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        self.backgroundColor = UIColor(hex: 0xededed)
        centerImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_share_detail2")
            return view
        }()
        contentView.addSubview(centerImageView)
        centerImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(480)
            make.width.equalTo(270)
        }
        
        imageView = {
            let view = UIImageView()
            view.image = UIImage(named: "invitation_with_gifts_share_detail")
            return view
        }()
        centerImageView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.bottom.equalTo(-46)
            make.right.equalTo(-36)
            make.width.height.equalTo(68)
        }
        
        logoImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "share_icon")
            return view
        }()
        imageView.addSubview(logoImageView)
        logoImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        if let qrCode = generateQRCode(from: YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=lkhtj-app&customer_id=\(YHLoginManager.shared.userModel?.id ?? "")&scene_id=30") {
            // 可以将qrCode设置为UIImageView的image属性来显示二维码
            imageView.image = qrCode
        }
    }
    
    func generateQRCode(from string: String) -> UIImage? {
        guard let data = string.data(using: .ascii, allowLossyConversion: false) else {
            return nil
        }

        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setValue(data, forKey: "inputMessage")

        guard let outputImage = filter?.outputImage else {
            return nil
        }

        let context = CIContext()
        if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
            return UIImage(cgImage: cgImage)
        }

        return nil
    }
}
