//
//  OrderEvaluationQRCodeVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/11.
//

import UIKit

public struct R_OrderEvaluationQRCode {
    static func router(_ urlStr: String) {
        let vc = OrderEvaluationQRCodeVc.cd_storyboard("Order", from: "OrderEvaluationQRCodeVc") as! OrderEvaluationQRCodeVc
        vc.modalTransitionStyle = .crossDissolve
        vc.modalPresentationStyle = .custom
        vc.urlStr = urlStr
        CD.present(vc, animated: false)
    }
}

class OrderEvaluationQRCodeVc: UIViewController {

    @IBOutlet weak var lab_title: UILabel!
    @IBOutlet weak var img_code: UIImageView!
    @IBOutlet weak var bgView: UIView!
    
    var urlStr = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        lab_title.text = "扫码评价".languageString()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        img_code.image = setUpQRCodeImage(urlStr, size: CGSize(w: 200, h: 200))
        
        bgView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        UIView.animate(withDuration: 0.3) {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.bgView.transform = CGAffineTransform(scaleX: 1, y: 1)
        }
    }
    
    @IBAction func close(_ sender: UIButton) {
        UIView.animate(withDuration: 0.3) {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.bgView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        } completion: { _ in
            self.dismiss(animated: false)
        }
    }
    
    func setUpQRCodeImage(_ urlStr: String, size: CGSize) -> UIImage?
    {
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else {return nil}
        filter.setDefaults()
        
        let contentData = urlStr.data(using: String.Encoding.utf8)
        filter.setValue(contentData, forKey: "inputMessage")
        
        guard let ciImage = filter.outputImage else {return nil}
        let context = CIContext(options: nil)
        let bitmapImage = context.createCGImage(ciImage, from: ciImage.extent)

        let colorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue)

        let scale = min(size.width / ciImage.extent.width, size.height / ciImage.extent.height)
        bitmapContext!.interpolationQuality = CGInterpolationQuality.none
        bitmapContext?.scaleBy(x: scale, y: scale)
        bitmapContext?.draw(bitmapImage!, in: ciImage.extent)

        guard let scaledImage = bitmapContext?.makeImage() else {return nil}

        return UIImage(cgImage: scaledImage)
    }
}

